text stringlengths 14 6.51M |
|---|
unit MathLib0;
(* copyright 1991 by Art Steinmetz *)
{ a collection of math routines }
interface
TYPE
myFloat = Double;
Cardinal = WORD;
GoalFunc = function(Var1 : myfloat) : myfloat;
VAR
{ Constants defined at run time }
HalfPI,
TwoPI ,
Radian ,
RadianDiv100,
ln10,
sqrt2 : myFloat;
FUNCTION max(a,b : INTEGER) : INTEGER;
FUNCTION min(a,b : INTEGER) : INTEGER;
{ TRIG FUNCTIONS }
{ -------------------------------------------------------------}
FUNCTION ArcCos(X: myFloat): myFloat;
{ -------------------------------------------------------------}
FUNCTION ArcSin(X: myFloat): myFloat;
{ -------------------------------------------------------------}
FUNCTION ArcTanH(X : Real): Real;
{ -------------------------------------------------------------}
function HexConv(num : LONGINT) : string;
{ -------------------------------------------------------------}
function Power(base,pwr : myFloat) : myFloat;
{ raise BASE to the RAISE power.
No negative numbers or error checking }
{ -------------------------------------------------------------}
function Factorial(X : WORD) : myFloat;
{ -------------------------------------------------------------}
function Binomial(n,j : WORD ; p : myFloat) : myFloat;
{ probability of "j" outcomes in "n" trials. Any "j" has liklihood "p" }
{ -------------------------------------------------------------}
function FastBinomial(n,j : WORD ; p, FactN : myFloat) : myFloat;
{ probability of "j" outcomes in "n" trials. Any "j" has liklihood "p" }
{ Assumes factorial of N has already been computed as FactN }
{ -------------------------------------------------------------}
function Normal(Z : myFloat) : myFloat;
{ Compute cumulative normal distribution.
Use a polynomial approximation.}
{ -------------------------------------------------------------}
PROCEDURE SeekGoal( Goal, Tolerance : myFloat;
VAR Variable : myFloat;
TestProc : GoalFunc);
implementation
{F+}
{ ---------------------------------------------------------------}
FUNCTION max(a,b : INTEGER) : INTEGER;
BEGIN
IF a > b THEN
max := a
ELSE
max := b;
END; {max}
{ ---------------------------------------------------------------}
FUNCTION min(a,b : INTEGER) : INTEGER;
BEGIN
IF a < b THEN
min := a
ELSE
min := b;
END; {max}
{ -------------------------------------------------------------}
FUNCTION ArcCos(X: myFloat): myFloat;
BEGIN
IF ABS(X) < 1 THEN ArcCos:= ARCTAN(SQRT(1-SQR(X))/X)
ELSE IF X = 1 THEN ArcCos:= 0
ELSE IF X =-1 THEN ArcCos:= PI;
END; { ArcCos. }
{ -------------------------------------------------------------}
FUNCTION ArcSin(X: myFloat): myFloat;
BEGIN
IF ABS(X) < 1 THEN ArcSin:= ARCTAN(X/SQRT(1-SQR(X)))
ELSE IF X = 1 THEN ArcSin:= HalfPI
ELSE IF X =-1 THEN ArcSin:=-HalfPI;
END; { ArcSin. }
{ -------------------------------------------------------------}
FUNCTION ArcTanH(X : Real): Real;
CONST
fudge = 0.999999; { ArcTanH(1.0) is undefined }
VAR A,T : myFloat;
BEGIN
T:=ABS(X);
IF NOT (T < 1) THEN
T := fudge; { should never happen }
A := 0.5 * LN((1 + T)/(1 - T));
IF X < 0 THEN ArcTanH := -A ELSE ArcTanH :=A;
END; { ArcTanH. }
{++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
function pwrint(num,pwr : LONGINT) : LONGINT;
var
i, temp : LONGINT;
begin
temp := 1;
if pwr > 0 then
for i := 1 to pwr do temp := temp * num
else temp := 1;
pwrint := temp;
end;
{++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
function HexConv(num : LONGINT) : string;
const
base = 16;
Hex : string[16] = '0123456789ABCEDF';
var
temp : string;
n,
check,
digit : LONGINT;
begin {HexConv}
n := 0;
temp := '';
{ if num > 4095 then writeln('ERROR! in hex conversion')
else
} repeat
n := n + 1;
check := pwrint(base,n);
digit := trunc(num/pwrint(base,n-1)) mod base;
temp := Hex[digit+1] + temp;
until check > num;
if length(temp) < 2 then temp := '0'+temp;
HexConv := temp;
end; {HexConv}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function Power(base,pwr : myFloat) : myFloat;
begin
Power := exp(ln(base) * pwr)
end;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
Function Factorial(X : WORD) : myFloat;
{ although not a REAL result we need to allow a large range }
{ should use recursion }
VAR
i : WORD;
temp : myFloat;
BEGIN
temp := X;
i := X;
WHILE i > 1 DO
BEGIN
i := i-1;
temp := temp * i;
END;
If temp = 0 then temp := 1;
Factorial := temp;
END; {Factorial}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function Binomial(n,j : WORD ; p : myFloat) : myFloat;
{ probability of "j" outcomes in "n" trials. Any "j" has liklihood "p" }
VAR
a,b,c,d : myFloat;
BEGIN
IF j > n THEN
Binomial := 0
ELSE
BEGIN
a := Factorial(n);
b := Factorial(j) * Factorial(n-j);
c := power(p,j);
d := power(1-p,n-j);
Binomial := a / b * c * d;
END;
END; { Binomial }
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function FastBinomial(n,j : WORD ; p, FactN : myFloat) : myFloat;
{ probability of "j" outcomes in "n" trials. Any "j" has liklihood "p" }
{ Assumes factorial of N has already been computed as FactN }
VAR
b,c,d : myFloat;
BEGIN
IF j > n THEN
FastBinomial := 0
ELSE
BEGIN
b := Factorial(j) * Factorial(n-j);
c := power(p,j);
d := power(1-p,n-j);
FastBinomial := FactN / b * c * d;
END;
END; { Binomial }
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function Normal(Z : myFloat) : myFloat;
{Compute cumulative normal distribution.
Use a polynomial approximation.}
const CA = 1.3302740;
CB = -1.8212560;
CC = 1.7814780;
CD = -0.3565638;
CE = 0.3193815;
CY = 0.2316419;
CZ = 0.3989423;
var N, NN, Y1, Z1 : myFloat;
begin
Y1 := 1/(1+CY*abs(Z));
Z1 := CZ * exp(-0.5*sqr(Z));
{ Following two lines could be one formula but myFloating point }
{ hardware stack can't handle it.}
N := (((CA * Y1+CB) * Y1 + CC) * Y1 + CD);
NN := (N * Y1 + CE) * Y1 * Z1;
if Z > 0 then
Normal := 1-NN
else
Normal := NN
end; {Normal}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure SeekGoal( Goal, Tolerance : myFloat;
VAR Variable : myFloat;
TestProc : GoalFunc);
{iteration routine to find a value}
const maxiter = 25;
var low,high,incr,
upper,lower,
n : myFloat;
done : boolean;
begin
n := 0;
high := Variable;
low := 0.00;
incr := (high - low)/2;
upper := Goal + tolerance;
lower := Goal - tolerance;
done := false;
repeat {goal seeking}
n := n + 1;
Variable := low + incr;
Goal := TestProc(Variable);
if Goal > upper then incr := incr/2
else if Goal < lower then low := low + incr
else done := true;
if n = maxiter then done := true;
until done; {goal seeking}
end;
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
BEGIN
ln10 := ln(10);
sqrt2 := sqrt(2);
HalfPI := Pi / 2.0;
TwoPI := Pi * 2.0;
Radian := Pi / 180.0;
RadianDiv100 := Pi / 18000.0; { PI/180/100 }
END.
{interface
implementation}
end. { MathLib0 }
|
//******************************************************************************
//*** LUA SCRIPT FUNCTIONS ***
//*** ***
//*** (c) Massimo Magnano 2006 ***
//*** ***
//*** ***
//******************************************************************************
// File : Lua_EnvironmentStrings.pas
//
// Description : Access from Lua scripts to EnvironmentStrings
//
//******************************************************************************
// Exported functions :
//
// GetVarValue(string VarString) return Value as String.
unit Lua_EnvironmentStrings;
interface
uses SysUtils, Lua, LuaUtils, EnvironmentStrings;
procedure RegisterFunctions(L: Plua_State;
OnGetVariable :TOnGetVariableFunction =Nil;
OnGetVariableTag :TObject =Nil);
implementation
const
HANDLE_ONGETVARIABLE ='Lua_ES_OnGetVariable';
HANDLE_ONGETVARIABLETAG ='Lua_ES_OnGetVariableTag';
function GetOnGetVariable(L: Plua_State): TOnGetVariableFunction;
begin
Result := TOnGetVariableFunction(LuaGetTableLightUserData(L, LUA_REGISTRYINDEX, HANDLE_ONGETVARIABLE));
end;
function GetOnGetVariableTag(L: Plua_State): TObject;
begin
Result := TObject(LuaGetTableLightUserData(L, LUA_REGISTRYINDEX, HANDLE_ONGETVARIABLETAG));
end;
// GetVarValue(string VarString) return Value as String.
function LuaGetVarValue(L: Plua_State): Integer; cdecl;
Var
NParams :Integer;
VarName :String;
xResult :String;
begin
Result := 0;
NParams := lua_gettop(L);
if (NParams=1)
then begin
try
VarName :=LuaToString(L, 1);
xResult :=EnvironmentStrings.ProcessPARAMString(VarName, GetOnGetVariable(L), GetOnGetVariableTag(L));
if (xResult<>'')
then begin
LuaPushString(L, xResult);
Result := 1;
end;
except
On E:Exception do begin
LuaError(L, ERR_Script+E.Message);
end;
end;
end;
end;
procedure RegisterFunctions(L: Plua_State;
OnGetVariable :TOnGetVariableFunction =Nil;
OnGetVariableTag :TObject =Nil);
begin
LuaSetTableLightUserData(L, LUA_REGISTRYINDEX,
HANDLE_ONGETVARIABLE, @OnGetVariable);
LuaSetTableLightUserData(L, LUA_REGISTRYINDEX,
HANDLE_ONGETVARIABLETAG, OnGetVariableTag);
LuaRegister(L, 'GetVarValue', LuaGetVarValue);
end;
end.
|
unit BCEditor.Editor.Search;
interface
uses
Classes, Controls,
BCEditor.Editor.Search.Map, BCEditor.Types,
BCEditor.Editor.Search.Highlighter;
const
BCEDITOR_SEARCH_OPTIONS = [soHighlightResults, soSearchOnTyping, soBeepIfStringNotFound, soShowSearchMatchNotFound];
type
TBCEditorSearch = class(TPersistent)
strict private
FEnabled: Boolean;
FEngine: TBCEditorSearchEngine;
FHighlighter: TBCEditorSearchHighlighter;
FMap: TBCEditorSearchMap;
FOnChange: TBCEditorSearchChangeEvent;
FOptions: TBCEditorSearchOptions;
FSearchText: String;
procedure DoChange;
procedure SetEnabled(const Value: Boolean);
procedure SetEngine(const Value: TBCEditorSearchEngine);
procedure SetHighlighter(const Value: TBCEditorSearchHighlighter);
procedure SetMap(const Value: TBCEditorSearchMap);
procedure SetOnChange(const Value: TBCEditorSearchChangeEvent);
procedure SetSearchText(const Value: String);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Enabled: Boolean read FEnabled write SetEnabled default True;
property Engine: TBCEditorSearchEngine read FEngine write SetEngine default seNormal;
property Highlighter: TBCEditorSearchHighlighter read FHighlighter write SetHighlighter;
property Map: TBCEditorSearchMap read FMap write SetMap;
property OnChange: TBCEditorSearchChangeEvent read FOnChange write SetOnChange;
property Options: TBCEditorSearchOptions read FOptions write FOptions default BCEDITOR_SEARCH_OPTIONS;
property SearchText: string read FSearchText write SetSearchText;
end;
implementation
{ TBCEditorSearchPanel }
constructor TBCEditorSearch.Create;
begin
inherited;
FSearchText := '';
FEngine := seNormal;
FMap := TBCEditorSearchMap.Create;
FHighlighter := TBCEditorSearchHighlighter.Create;
FOptions := BCEDITOR_SEARCH_OPTIONS;
FEnabled := True;
end;
destructor TBCEditorSearch.Destroy;
begin
FMap.Free;
FHighlighter.Free;
inherited;
end;
procedure TBCEditorSearch.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TBCEditorSearch) then
with Source as TBCEditorSearch do
begin
Self.FEnabled := FEnabled;
Self.FSearchText := FSearchText;
Self.FEngine := FEngine;
Self.FOptions := FOptions;
Self.FMap.Assign(FMap);
Self.FHighlighter.Assign(FHighlighter);
Self.DoChange;
end
else
inherited Assign(Source);
end;
procedure TBCEditorSearch.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(scRefresh);
end;
procedure TBCEditorSearch.SetOnChange(const Value: TBCEditorSearchChangeEvent);
begin
FOnChange := Value;
FMap.OnChange := FOnChange;
FHighlighter.OnChange := FOnChange;
end;
procedure TBCEditorSearch.SetEngine(const Value: TBCEditorSearchEngine);
begin
if FEngine <> Value then
begin
FEngine := Value;
if Assigned(FOnChange) then
FOnChange(scEngineUpdate);
end;
end;
procedure TBCEditorSearch.SetSearchText(const Value: String);
begin
FSearchText := Value;
if Assigned(FOnChange) then
FOnChange(scSearch);
end;
procedure TBCEditorSearch.SetEnabled(const Value: Boolean);
begin
if FEnabled <> Value then
begin
FEnabled := Value;
if Assigned(FOnChange) then
FOnChange(scSearch);
end;
end;
procedure TBCEditorSearch.SetHighlighter(const Value: TBCEditorSearchHighlighter);
begin
FHighlighter.Assign(Value);
end;
procedure TBCEditorSearch.SetMap(const Value: TBCEditorSearchMap);
begin
FMap.Assign(Value);
end;
end.
|
program fibo;
var
i, result : integer;
procedure fib(var return : integer; n : integer) ;
var r1, r2 : integer;
begin
if n <= 2 then return := 1
else begin
fib(r1,n-2);
fib(r2,n-1);
return := r1 + r2
end
end;
begin
for i := 1 to 20 do
begin
fib(result, i);
writeln(i, ' : ', result)
end
end.
|
unit Security.ChangePassword.View;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Hash, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Vcl.Buttons, Vcl.ExtCtrls, Vcl.Imaging.pngimage, Vcl.Imaging.jpeg,
PngSpeedButton, PngFunctions,
Security.ChangePassword.Interfaces
;
type
TSecurityChangePasswordView = class(TForm, iChangePasswordView, iChangePasswordViewEvents)
ShapeBodyRight: TShape;
ShapeBodyLeft: TShape;
ImageLogo: TImage;
LabelUsuario: TLabel;
LabelPassword: TLabel;
PanelTitle: TPanel;
ShapePanelTitleRight: TShape;
ShapePanelTitleLeft: TShape;
ShapePanelTitleTop: TShape;
PanelTitleBackgroung: TPanel;
PanelTitleLabelAutenticacao: TLabel;
PanelTitleDOT: TLabel;
PanelTitleLabelSigla: TLabel;
PanelTitleAppInfo: TPanel;
PanelTitleAppInfoVersion: TPanel;
PanelTitleAppInfoVersionValue: TLabel;
PanelTitleAppInfoVersionCaption: TLabel;
PanelTitleAppInfoUpdated: TPanel;
PanelTitleAppInfoUpdatedValue: TLabel;
PanelTitleAppInfoUpdatedCaption: TLabel;
PanelStatus: TPanel;
PanelStatusShapeLeft: TShape;
PanelStatusShapeRight: TShape;
PanelStatusShapeBottom: TShape;
PanelStatusBackground: TPanel;
LabelIPServerCaption: TLabel;
LabelIPComputerValue: TLabel;
PanelStatusBackgroundClient: TPanel;
LabelIPComputerCaption: TLabel;
LabelIPServerValue: TLabel;
PanelToolbar: TPanel;
ShapeToolbarLeft: TShape;
ShapeToolbarRight: TShape;
PanelPassword: TPanel;
PanelImagePassword: TPanel;
ImagePassword: TImage;
PanelImagePasswordError: TPanel;
ImagePasswordError: TImage;
EditPassword: TEdit;
PanelUsuario: TPanel;
PanelImageUsuario: TPanel;
ImageUsuario: TImage;
EditUsuario: TEdit;
LabelNewPassword: TLabel;
PanelNewPassword: TPanel;
PanelImageNewPassword: TPanel;
ImageNewPassword: TImage;
PanelImageNewPasswordError: TPanel;
ImageNewPasswordError: TImage;
EditNewPassword: TEdit;
LabelConfirmNewPassword: TLabel;
PanelConfirmNewPassword: TPanel;
PanelImageConfirmNewPassword: TPanel;
ImageConfirmNewPassword0: TImage;
PanelImageConfirmNewPasswordError: TPanel;
ImageConfirmNewPasswordError: TImage;
EditConfirmNewPassword: TEdit;
ShapePanelTitleBottom: TShape;
pl_Fundo: TPanel;
PngSpeedButtonOk: TPngSpeedButton;
PngSpeedButtonCancelar: TPngSpeedButton;
ShapeToolbarTop: TShape;
ShapeToolbarBottom: TShape;
procedure PngSpeedButtonCancelarClick(Sender: TObject);
procedure PngSpeedButtonOkClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EditPasswordChange(Sender: TObject);
procedure EditNewPasswordChange(Sender: TObject);
procedure EditConfirmNewPasswordChange(Sender: TObject);
procedure FormActivate(Sender: TObject);
strict private
FID : Int64;
FUsuario : string;
FPassword : string;
FNewPassword : String;
FChangedPassword: boolean;
FOnChangePassword: Security.ChangePassword.Interfaces.TChangePasswordNotifyEvent;
FOnResult : Security.ChangePassword.Interfaces.TResultNotifyEvent;
{ Strict private declarations }
function getUsuario: string;
procedure setUsuario(const Value: string);
function getID: Int64;
procedure setID(const Value: Int64);
function getPassword: string;
procedure setPassword(const Value: string);
function getNewPassword: string;
procedure setOnChangePassword(const Value: Security.ChangePassword.Interfaces.TChangePasswordNotifyEvent);
function getOnChangePassword: Security.ChangePassword.Interfaces.TChangePasswordNotifyEvent;
procedure setOnResult(const Value: Security.ChangePassword.Interfaces.TResultNotifyEvent);
function getOnResult: Security.ChangePassword.Interfaces.TResultNotifyEvent;
private
{ Private declarations }
procedure Validate;
procedure doChangePassword;
procedure doResult;
public
{ Public declarations }
function Events: iChangePasswordViewEvents;
published
{ Published declarations }
property Usuario : string read getUsuario write setUsuario;
property ID : Int64 read getID write setID;
property Password : string read getPassword write setPassword;
property NewPassword: string read getNewPassword;
property OnChangePassword: Security.ChangePassword.Interfaces.TChangePasswordNotifyEvent read getOnChangePassword write setOnChangePassword;
property OnResult : TResultNotifyEvent read getOnResult write setOnResult;
end;
var
SecurityChangePasswordView: TSecurityChangePasswordView;
implementation
uses
Security.Internal;
{$R *.dfm}
procedure TSecurityChangePasswordView.Validate;
const
ERR_EDIT_PASSWORD = 'A [Senha Atual] inválida. Acesso negado!';
ERR_EDIT_NEW_PASS = 'A [Nova Senha] deve ser diferente da [Senha Atual].';
ERR_EDIT_CONFIRMA = 'A [Confirmação] deve ser igual a [Nova Senha].';
var
LPassword : string;
LEditPassword : string;
LEditNewPassword : string;
LEditConfirmNewPassword: string;
begin
LPassword := Password;
LEditPassword := Trim(EditPassword.Text);
LEditNewPassword := Trim(EditNewPassword.Text);
LEditConfirmNewPassword := Trim(EditConfirmNewPassword.Text);
// Validações
Internal.Required(EditPassword, LEditPassword);
Internal.Required(EditNewPassword, LEditNewPassword);
Internal.Required(EditConfirmNewPassword, LEditConfirmNewPassword);
LEditPassword := Internal.MD5(LEditPassword.ToUpper);
LEditNewPassword := Internal.MD5(LEditNewPassword.ToUpper);
LEditConfirmNewPassword := Internal.MD5(LEditConfirmNewPassword.ToUpper);
Internal.Validate(EditPassword, not SameStr(LPassword, LEditPassword), ERR_EDIT_PASSWORD, PanelImagePasswordError, ImagePasswordError);
Internal.Validate(EditNewPassword, SameStr(LPassword, LEditNewPassword), ERR_EDIT_NEW_PASS, PanelImageNewPasswordError, ImageNewPasswordError);
Internal.Validate(EditConfirmNewPassword, not SameStr(LEditNewPassword, LEditConfirmNewPassword), ERR_EDIT_CONFIRMA, PanelImageConfirmNewPasswordError, ImageConfirmNewPasswordError);
FNewPassword := LEditNewPassword;
end;
procedure TSecurityChangePasswordView.doChangePassword;
var
LError: string;
begin
SelectFirst;
Validate;
FChangedPassword := False;
OnChangePassword(ID, NewPassword, LError, FChangedPassword); // Atricuição da nova senha
Internal.Die(LError);
if FChangedPassword then
Close;
end;
procedure TSecurityChangePasswordView.doResult;
begin
try
if not Assigned(FOnResult) then
Exit;
FOnResult(FChangedPassword);
finally
Application.NormalizeAllTopMosts;
BringToFront;
end;
end;
procedure TSecurityChangePasswordView.EditConfirmNewPasswordChange(Sender: TObject);
begin
PanelImageConfirmNewPasswordError.Visible := False;
end;
procedure TSecurityChangePasswordView.EditNewPasswordChange(Sender: TObject);
begin
PanelImageNewPasswordError.Visible := False;
end;
procedure TSecurityChangePasswordView.EditPasswordChange(Sender: TObject);
begin
PanelImagePasswordError.Visible := False;
end;
function TSecurityChangePasswordView.Events: iChangePasswordViewEvents;
begin
Result := Self;
end;
procedure TSecurityChangePasswordView.FormActivate(Sender: TObject);
begin
EditPassword.Clear;
EditNewPassword.Clear;
EditConfirmNewPassword.Clear;
FChangedPassword := False;
BringToFront;
Application.NormalizeAllTopMosts;
EditPassword.SetFocus;
end;
procedure TSecurityChangePasswordView.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Application.RestoreTopMosts;
doResult;
end;
procedure TSecurityChangePasswordView.FormDestroy(Sender: TObject);
begin
// if Assigned(DataSourceUser.DataSet) then
// DataSourceUser.DataSet.Free;
end;
procedure TSecurityChangePasswordView.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case Key of
VK_RETURN:
begin
if ActiveControl = EditConfirmNewPassword then
PngSpeedButtonOk.Click
else
SelectNext(ActiveControl, True, True);
Key := VK_CANCEL;
end;
end;
end;
procedure TSecurityChangePasswordView.PngSpeedButtonCancelarClick(Sender: TObject);
begin
FChangedPassword := False;
Close;
end;
procedure TSecurityChangePasswordView.PngSpeedButtonOkClick(Sender: TObject);
begin
doChangePassword;
end;
procedure TSecurityChangePasswordView.setID(const Value: Int64);
begin
FID := Value;
end;
function TSecurityChangePasswordView.getID:
Int64;
begin
Result := FID;
end;
procedure TSecurityChangePasswordView.setUsuario(const Value: string);
begin
FUsuario := Value;
EditUsuario.Text := Value;
end;
function TSecurityChangePasswordView.getUsuario: string;
begin
Result := FUsuario;
end;
procedure TSecurityChangePasswordView.setPassword(const Value: string);
begin
FPassword := Value;
end;
function TSecurityChangePasswordView.getPassword: string;
begin
Result := FPassword;
end;
function TSecurityChangePasswordView.getNewPassword: string;
begin
Result := FNewPassword;
end;
procedure TSecurityChangePasswordView.setOnChangePassword(const Value: Security.ChangePassword.Interfaces.TChangePasswordNotifyEvent);
begin
FOnChangePassword := Value;
end;
function TSecurityChangePasswordView.getOnChangePassword: Security.ChangePassword.Interfaces.TChangePasswordNotifyEvent;
begin
Result := FOnChangePassword;
end;
procedure TSecurityChangePasswordView.setOnResult(const Value: Security.ChangePassword.Interfaces.TResultNotifyEvent);
begin
FOnResult := Value;
end;
function TSecurityChangePasswordView.getOnResult: Security.ChangePassword.Interfaces.TResultNotifyEvent;
begin
Result := FOnResult;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLGameMenu<p>
Manages a basic game menu UI<p>
<b>History : </b><font size=-1><ul>
<li>16/03/11 - Yar - Fixes after emergence of GLMaterialEx
<li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter
<li>31/05/10 - Yar - Fixed for Linux x64
<li>22/04/10 - Yar - Fixes after GLState revision
<li>05/03/10 - DanB - More state added to TGLStateCache
<li>04/09/07 - DaStr - Fixed memory leak in TGLGameMenu
(BugtrackerID = 1787617) (thanks Pierre Lemerle)
<li>06/06/07 - DaStr - Added GLColor to uses (BugtrackerID = 1732211)
<li>30/03/07 - DaStr - Added $I GLScene.inc
<li>28/03/07 - DaStr - Renamed parameters in some methods
(thanks Burkhard Carstens) (Bugtracker ID = 1678658)
<li>26/03/07 - DaveK - back to TGLSceneObject for Material support
<li>16/02/07 - DaStr & DaveK - TGLGameMenu.MouseMenuSelect bugfixed (again)
Component made descendant of TGLBaseSceneObject
IGLMaterialLibrarySupported added
<li>20/12/06 - DaStr - TGLGameMenu.MouseMenuSelect bugfixed (thanks to Predator)
<li>03/27/06 - DaveK - added mouse selection support
<li>03/03/05 - EG - Creation
</ul></font>
}
unit GLGameMenu;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils,
GLScene, GLMaterial, GLBitmapFont, GLCrossPlatform, GLColor,
GLRenderContextInfo;
type
// TGLGameMenuScale
//
TGLGameMenuScale = (gmsNormal, gms1024x768);
// TGLGameMenu
//
{: Classic game menu interface made of several lines.<p> }
TGLGameMenu = class(TGLSceneObject, IGLMaterialLibrarySupported)
private
{ Private Properties }
FItems: TStrings;
FSelected: Integer;
FFont: TGLCustomBitmapFont;
FMarginVert, FMarginHorz, FSpacing: Integer;
FMenuScale: TGLGameMenuScale;
FBackColor: TGLColor;
FInactiveColor, FActiveColor, FDisabledColor: TGLColor;
FMaterialLibrary: TGLMaterialLibrary;
FTitleMaterialName: TGLLibMaterialName;
FTitleWidth, FTitleHeight: Integer;
FOnSelectedChanged: TNotifyEvent;
FBoxTop, FBoxBottom, FBoxLeft, FBoxRight: Integer;
FMenuTop: integer;
//implementing IGLMaterialLibrarySupported
function GetMaterialLibrary: TGLAbstractMaterialLibrary;
protected
{ Protected Properties }
procedure SetMenuScale(AValue: TGLGameMenuScale);
procedure SetMarginHorz(AValue: Integer);
procedure SetMarginVert(AValue: Integer);
procedure SetSpacing(AValue: Integer);
procedure SetFont(AValue: TGLCustomBitmapFont);
procedure SetBackColor(AValue: TGLColor);
procedure SetInactiveColor(AValue: TGLColor);
procedure SetActiveColor(AValue: TGLColor);
procedure SetDisabledColor(AValue: TGLColor);
function GetEnabled(AIndex: Integer): Boolean;
procedure SetEnabled(AIndex: Integer; AValue: Boolean);
procedure SetItems(AValue: TStrings);
procedure SetSelected(AValue: Integer);
function GetSelectedText: string;
procedure SetMaterialLibrary(AValue: TGLMaterialLibrary);
procedure SetTitleMaterialName(const AValue: string);
procedure SetTitleWidth(AValue: Integer);
procedure SetTitleHeight(AValue: Integer);
procedure ItemsChanged(Sender: TObject);
public
{ Public Properties }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Notification(AComponent: TComponent; Operation: TOperation);
override;
procedure BuildList(var rci: TRenderContextInfo); override;
property Enabled[AIndex: Integer]: Boolean read GetEnabled write SetEnabled;
property SelectedText: string read GetSelectedText;
procedure SelectNext;
procedure SelectPrev;
procedure MouseMenuSelect(const X, Y: integer);
published
{ Published Properties }
property MaterialLibrary: TGLMaterialLibrary read FMaterialLibrary write
SetMaterialLibrary;
property MenuScale: TGLGameMenuScale read FMenuScale write SetMenuScale
default gmsNormal;
property MarginHorz: Integer read FMarginHorz write SetMarginHorz default
16;
property MarginVert: Integer read FMarginVert write SetMarginVert default
16;
property Spacing: Integer read FSpacing write SetSpacing default 16;
property Font: TGLCustomBitmapFont read FFont write SetFont;
property TitleMaterialName: string read FTitleMaterialName write
SetTitleMaterialName;
property TitleWidth: Integer read FTitleWidth write SetTitleWidth default 0;
property TitleHeight: Integer read FTitleHeight write SetTitleHeight default
0;
property BackColor: TGLColor read FBackColor write SetBackColor;
property InactiveColor: TGLColor read FInactiveColor write SetInactiveColor;
property ActiveColor: TGLColor read FActiveColor write SetActiveColor;
property DisabledColor: TGLColor read FDisabledColor write SetDisabledColor;
property Items: TStrings read FItems write SetItems;
property Selected: Integer read FSelected write SetSelected default -1;
property OnSelectedChanged: TNotifyEvent read FOnSelectedChanged write
FOnSelectedChanged;
// these are the extents of the menu
property BoxTop: integer read FBoxTop;
property BoxBottom: integer read FBoxBottom;
property BoxLeft: integer read FBoxLeft;
property BoxRight: integer read FBoxRight;
// this is the top of the first menu item
property MenuTop: integer read FMenuTop;
//publish other stuff from TGLBaseSceneObject
property ObjectsSorting;
property VisibilityCulling;
property Position;
property Visible;
property OnProgress;
property Behaviours;
property Effects;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses
GLCanvas, OpenGLTokens, GLContext;
// ------------------
// ------------------ TGLGameMenu ------------------
// ------------------
// Create
//
constructor TGLGameMenu.Create(AOwner: TComponent);
begin
inherited;
ObjectStyle := ObjectStyle + [osDirectDraw];
FItems := TStringList.Create;
TStringList(FItems).OnChange := ItemsChanged;
FSelected := -1;
FMarginHorz := 16;
FMarginVert := 16;
FSpacing := 16;
FMenuScale := gmsNormal;
FBackColor := TGLColor.CreateInitialized(Self, clrTransparent, NotifyChange);
FInactiveColor := TGLColor.CreateInitialized(Self, clrGray75, NotifyChange);
FActiveColor := TGLColor.CreateInitialized(Self, clrWhite, NotifyChange);
FDisabledColor := TGLColor.CreateInitialized(Self, clrGray60, NotifyChange);
end;
// Destroy
//
destructor TGLGameMenu.Destroy;
begin
inherited;
FItems.Free;
Font := nil;
FBackColor.Free;
FInactiveColor.Free;
FActiveColor.Free;
FDisabledColor.Free;
end;
// Notification
//
procedure TGLGameMenu.Notification(AComponent: TComponent; Operation:
TOperation);
begin
inherited;
if Operation = opRemove then
begin
if AComponent = Font then
Font := nil;
if AComponent = MaterialLibrary then
MaterialLibrary := nil;
end;
end;
// BuildList
//
procedure TGLGameMenu.BuildList(var rci: TRenderContextInfo);
var
canvas: TGLCanvas;
buffer: TGLSceneBuffer;
i, w, h, tw, y: Integer;
color: TColorVector;
libMat: TGLLibMaterial;
begin
if Font = nil then
Exit;
case MenuScale of
gmsNormal:
begin
buffer := TGLSceneBuffer(rci.buffer);
canvas := TGLCanvas.Create(buffer.Width, buffer.Height);
end;
gms1024x768: canvas := TGLCanvas.Create(1024, 768);
else
canvas := nil;
Assert(False);
end;
try
// determine extents
h := FItems.Count * (Font.CharHeight + Spacing) - Spacing + MarginVert * 2;
if TitleHeight > 0 then
h := h + TitleHeight + Spacing;
w := TitleWidth;
for i := 0 to FItems.Count - 1 do
begin
tw := Font.TextWidth(FItems[i]);
if tw > w then
w := tw;
end;
w := w + 2 * MarginHorz;
// calculate boundaries for user
FBoxLeft := Round(Position.X - w / 2);
FBoxTop := Round(Position.Y - h / 2);
FBoxRight := Round(Position.X + w / 2);
FBoxBottom := Round(Position.Y + h / 2);
// paint back
if BackColor.Alpha > 0 then
begin
canvas.PenColor := BackColor.AsWinColor;
canvas.PenAlpha := BackColor.Alpha;
canvas.FillRect(FBoxLeft, FBoxTop, FBoxRight, FBoxBottom);
end;
canvas.StopPrimitive;
// paint items
y := Round(Position.Y - h / 2 + MarginVert);
if TitleHeight > 0 then
begin
if (TitleMaterialName <> '') and (MaterialLibrary <> nil) and (TitleWidth
> 0) then
begin
libMat := MaterialLibrary.LibMaterialByName(TitleMaterialName);
if libMat <> nil then
begin
libMat.Apply(rci);
repeat
GL.Begin_(GL_QUADS);
GL.TexCoord2f(0, 0);
GL.Vertex2f(Position.X - TitleWidth div 2, y + TitleHeight);
GL.TexCoord2f(1, 0);
GL.Vertex2f(Position.X + TitleWidth div 2, y + TitleHeight);
GL.TexCoord2f(1, 1);
GL.Vertex2f(Position.X + TitleWidth div 2, y);
GL.TexCoord2f(0, 1);
GL.Vertex2f(Position.X - TitleWidth div 2, y);
GL.End_;
until (not libMat.UnApply(rci));
end;
end;
y := y + TitleHeight + Spacing;
FMenuTop := y;
end
else
FMenuTop := y + Spacing;
for i := 0 to FItems.Count - 1 do
begin
tw := Font.TextWidth(FItems[i]);
if not Enabled[i] then
color := DisabledColor.Color
else if i = Selected then
color := ActiveColor.Color
else
color := InactiveColor.Color;
Font.TextOut(rci, Position.X - tw div 2, y, FItems[i], color);
y := y + Font.CharHeight + Spacing;
end;
finally
canvas.Free;
end;
end;
// SelectNext
//
procedure TGLGameMenu.SelectNext;
var
i: Integer;
begin
i := Selected;
repeat
i := i + 1;
until (i >= Items.Count) or Enabled[i];
if (i < Items.Count) and (i <> Selected) then
Selected := i;
end;
// SelectPrev
//
procedure TGLGameMenu.SelectPrev;
var
i: Integer;
begin
i := Selected;
repeat
i := i - 1;
until (i < 0) or Enabled[i];
if (i >= 0) and (i <> Selected) then
Selected := i;
end;
// SetMenuScale
//
procedure TGLGameMenu.SetMenuScale(AValue: TGLGameMenuScale);
begin
if FMenuScale <> AValue then
begin
FMenuScale := AValue;
StructureChanged;
end;
end;
// SetMarginHorz
//
procedure TGLGameMenu.SetMarginHorz(AValue: Integer);
begin
if FMarginHorz <> AValue then
begin
FMarginHorz := AValue;
StructureChanged;
end;
end;
// SetMarginVert
//
procedure TGLGameMenu.SetMarginVert(AValue: Integer);
begin
if FMarginVert <> AValue then
begin
FMarginVert := AValue;
StructureChanged;
end;
end;
// SetSpacing
//
procedure TGLGameMenu.SetSpacing(AValue: Integer);
begin
if FSpacing <> AValue then
begin
FSpacing := AValue;
StructureChanged;
end;
end;
// SetFont
//
procedure TGLGameMenu.SetFont(AValue: TGLCustomBitmapFont);
begin
if FFont <> nil then
FFont.RemoveFreeNotification(Self);
FFont := AValue;
if FFont <> nil then
FFont.FreeNotification(Self);
end;
// SetBackColor
//
procedure TGLGameMenu.SetBackColor(AValue: TGLColor);
begin
FBackColor.Assign(AValue);
end;
// SetInactiveColor
//
procedure TGLGameMenu.SetInactiveColor(AValue: TGLColor);
begin
FInactiveColor.Assign(AValue);
end;
// SetActiveColor
//
procedure TGLGameMenu.SetActiveColor(AValue: TGLColor);
begin
FActiveColor.Assign(AValue);
end;
// SetDisabledColor
//
procedure TGLGameMenu.SetDisabledColor(AValue: TGLColor);
begin
FDisabledColor.Assign(AValue);
end;
// GetEnabled
//
function TGLGameMenu.GetEnabled(AIndex: Integer): Boolean;
begin
Result := not Boolean(PtrUint(FItems.Objects[AIndex]));
end;
// SetEnabled
//
procedure TGLGameMenu.SetEnabled(AIndex: Integer; AValue: Boolean);
begin
FItems.Objects[AIndex] := TObject(pointer(PtrUInt(ord(not AValue))));
StructureChanged;
end;
// SetItems
//
procedure TGLGameMenu.SetItems(AValue: TStrings);
begin
FItems.Assign(AValue);
SetSelected(Selected);
end;
// SetSelected
//
procedure TGLGameMenu.SetSelected(AValue: Integer);
begin
if AValue < -1 then
AValue := -1;
if AValue >= FItems.Count then
AValue := FItems.Count - 1;
if AValue <> FSelected then
begin
FSelected := AValue;
StructureChanged;
if Assigned(FOnSelectedChanged) then
FOnSelectedChanged(Self);
end;
end;
// GetSelectedText
//
function TGLGameMenu.GetSelectedText: string;
begin
if Cardinal(Selected) < Cardinal(FItems.Count) then
Result := FItems[Selected]
else
Result := '';
end;
// SetMaterialLibrary
//
procedure TGLGameMenu.SetMaterialLibrary(AValue: TGLMaterialLibrary);
begin
if FMaterialLibrary <> nil then
FMaterialLibrary.RemoveFreeNotification(Self);
FMaterialLibrary := AValue;
if FMaterialLibrary <> nil then
FMaterialLibrary.FreeNotification(Self);
end;
// SetTitleMaterialName
//
procedure TGLGameMenu.SetTitleMaterialName(const AValue: string);
begin
if FTitleMaterialName <> AValue then
begin
FTitleMaterialName := AValue;
StructureChanged;
end;
end;
// SetTitleWidth
//
procedure TGLGameMenu.SetTitleWidth(AValue: Integer);
begin
if AValue < 0 then
AValue := 0;
if FTitleWidth <> AValue then
begin
FTitleWidth := AValue;
StructureChanged;
end;
end;
// SetTitleHeight
//
procedure TGLGameMenu.SetTitleHeight(AValue: Integer);
begin
if AValue < 0 then
AValue := 0;
if FTitleHeight <> AValue then
begin
FTitleHeight := AValue;
StructureChanged;
end;
end;
// ItemsChanged
//
procedure TGLGameMenu.ItemsChanged(Sender: TObject);
begin
SetSelected(FSelected);
StructureChanged;
end;
// MouseMenuSelect
//
procedure TGLGameMenu.MouseMenuSelect(const X, Y: integer);
begin
if (X >= BoxLeft) and (Y >= MenuTop) and
(X <= BoxRight) and (Y <= BoxBottom) then
begin
Selected := (Y - FMenuTop) div (Font.CharHeight + FSpacing);
end
else
Selected := -1;
end;
// GetMaterialLibrary
//
function TGLGameMenu.GetMaterialLibrary: TGLAbstractMaterialLibrary;
begin
Result := FMaterialLibrary;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterClass(TGLGameMenu);
end.
|
unit InternalTypes;
interface
uses Windows,
regexpr,
SysUtils;
type TUInt64 = class
private
FValue : UInt64;
function GetFromByteToHR : string;
function GetFromKByteToHR : string;
public
constructor Create(Val : UInt64);
property Value: UInt64 read FValue write FValue;
function Add(Val : UInt64) : UInt64;
property FromByteToHR : String Read GetFromByteToHR;
property FromKByteToHR : String Read GetFromKByteToHR;
end;
type TFileInfo = class
private
fnbfile : UInt64;
fminsize, fmaxsize, ftotalsize : UInt64;
fminCreateDT, fminAccessDT, fminModifyDT: TDateTime;
fmaxCreateDT, fmaxAccessDT, fmaxModifyDT: TDateTime;
// Procedure ExploitInfo(Info : TSearchRec; var CDT,ADT,MDT : TDateTime; var SZ : UInt64);
Procedure SetMinMaxDate(SDate : TDateTime; var Mindate, maxDate : TDateTime);
function SetNewSize(SZ : UInt64) : uInt64;
public
constructor Create;
function GetData : string;
function GetJSON : AnsiString;
property nbfile: uInt64 read Fnbfile write Fnbfile;
property minSize: UInt64 read FMinSize write FMinSize;
property MaxSize: UInt64 read FMaxSize write FMaxSize;
property TotalSize: UInt64 read FTotalSize write FTotalSize;
property MinCreateDT: TDateTime read FMinCreateDT write FMinCreateDT;
property MinAccessDT: TDateTime read FMinAccessDT write FMinAccessDT;
property MinModifyDT: TDateTime read FMinModifyDT write FMinModifyDT;
property MaxCreateDT: TDateTime read FMaxCreateDT write FMaxCreateDT;
property MaxAccessDT: TDateTime read FMaxAccessDT write FMaxAccessDT;
property MaxModifyDT: TDateTime read FMaxModifyDT write FMaxModifyDT;
end;
type TFileInfoArray = class
private
fArray : Array of Tfileinfo;
function GetFileInfo(Index : Integer) : TFileInfo;
Procedure SetFileInfo(Index : Integer; Fi : TFileInfo);
function GetCount : Integer;
public
constructor Create();
function TakeAccount(Info : TSearchRec; LimIndex : Integer) : uInt64;
function GetData : string;
function GetJSON : AnsiString;
property FileInfo[Index : Integer] : TFileInfo read GetFileInfo write SetFileInfo;
property Count : Integer read GetCount;
end;
function getTimeStampString : String;
function GetSizeHRb(fSize : uInt64): WideString;
function GetSizeHRk(fSize : uInt64): WideString;
function EvaluateUnity(Valyou : string): UInt64;
function NormalizePath(S : String) : String;
function GetComputerNetName: string;
function XMLDateTime2DateTime(const XMLDateTime: AnsiString): TDateTime;
function DateTime2XMLDateTime(const vDateTime: TDateTime): AnsiString;
function DateTime2XMLDateTimeNoTZ(const vDateTime: TDateTime): AnsiString;
function RegularExpression(ExtValue : AnsiString): Boolean;
function GetExtensionTypeFromRegExp(ExtValue : AnsiString; fName : AnsiString; GName : AnsiString) : Ansistring;
function GetDiskSize(drive: Char; var free_size, total_size: Int64): Boolean;
function ProcessOneFormula(Buffer : string; var currentDate : TDateTime) : Boolean;
Procedure ExploitInfo(Info : TSearchRec; var CDT,ADT,MDT : TDateTime; var SZ : UInt64);
Function IsFileNewer(Info : TSearchRec; TestDate : TDateTime) : boolean;
function FileTimeToDTime(FTime: TFileTime): TDateTime;
const virguleLast : array[Boolean] of string = ('',',');
const cTrueFalse : array[Boolean] of string = ('False','True');
var SizeLimit : integer = 0;
const cIntlDateTimeStor = 'yyyy-mm-dd hh:mm:ss'; // for storage
const cIntlDateTimeDisp = 'yyyy-mm-dd hh:mm:ss'; // for display
const cIntlDateDisp = 'yyyy-mm-dd'; // for display
const cIntlDateFile = 'yyyymmddhhnnss'; // for file
var Regex: TRegExpr;
implementation
uses DateUtils,
StrUtils;
type
// TYpe de base de calcul
baseType = (
btYesterday,
btToday,
btTomorow,
btWeekstart,
btWeekend,
btMonthstart,
btMonthend,
btYearstart,
btYearend
);
incType = (
itDay,
itWeek,
itMonth,
itYear
);
const
basetypelib : array[basetype] of string =
(
'yesterday',
'today',
'tomorrow',
'weekstart',
'weekend',
'monthstart',
'monthend',
'yearstart',
'yearend'
);
incTypeLib : array[incType] of string =
(
'day',
'week',
'month',
'year'
);
function GetDiskSize(drive: Char; var free_size, total_size: Int64): Boolean;
var
RootPath: array[0..4] of Char;
RootPtr: PChar;
current_dir: string;
begin
RootPath[0] := Drive;
RootPath[1] := ':';
RootPath[2] := '\';
RootPath[3] := #0;
RootPtr := RootPath;
current_dir := GetCurrentDir;
if SetCurrentDir(drive + ':\') then
begin
GetDiskFreeSpaceEx(RootPtr, Free_size, Total_size, nil);
// this to turn back to original dir
SetCurrentDir(current_dir);
Result := True;
end
else
begin
Result := False;
Free_size := -1;
Total_size := -1;
end;
end;
function RegularExpression(ExtValue : AnsiString): Boolean;
begin
Result := ((copy(ExtValue,1,1) = '/') or
(copy(ExtValue,1,2) = '~/')) and
(copy(ExtValue,Length(ExtValue),1)='/');
end;
function GetExtensionTypeFromRegExp(ExtValue : AnsiString; fName : AnsiString; GName : AnsiString) : Ansistring;
var match : boolean;
var ExpR : Ansistring;
begin
result := '';
if RegularExpression(ExtValue) then
begin
match := ExtValue[1]='~';
if match then
begin
ExpR := copy(ExtValue,3,Length(ExtValue)-3);
// writeln('On vient de trouver un Match avec '+ExpR);
Regex.Expression := ExpR;
regex.Exec(fname);
if regex.SubExprMatchCount = 1 then
begin
Result := GName+'_'+regex.Match[1];
// writeln('-> ', Result);
end;
end
else
begin
ExpR := copy(ExtValue,2,Length(ExtValue)-2);
// writeln('On vient de trouver un scan avec '+ExpR);
Regex.Expression := ExpR;
// writeln('RegEx sur ',fname,' avec ',ExpR);
if regex.Exec(fname) then
begin
Result := GName;
// writeln('->',Result);
end;
end;
end;
end;
function getTimeStampString : String;
begin
Result := FormatDateTime(cIntlDateFile,Now);
end;
function XMLDateTime2DateTime(const XMLDateTime: AnsiString): TDateTime;
var
DateOnly: String;
TimeOnly: String;
TPos: Integer;
begin
TPos := Pos(' ', XMLDateTime);
if TPos <> 0 then
begin
DateOnly := Copy(XMLDateTime, 1, TPos - 1);
TimeOnly := Copy(XMLDateTime, TPos + 1, Length(XMLDateTime));
TPos := Pos(' ', TimeOnly);
if TPos <> 0 then
TimeOnly := Copy(TimeOnly, 1, TPos - 1);
Result := ScanDateTime('yyyy-mm-dd hh:nn:ss', DateOnly+' '+TimeOnly);
end
else
begin
DateOnly := XMLDateTime;
Result := ScanDateTime('yyyy-mm-dd', DateOnly);
end;
end;
function DateTime2XMLDateTime(const vDateTime: TDateTime): AnsiString;
var offset : integer;
const Signs : array[-1..1] of char = ('+',' ','-');
begin
offset := GetLocalTimeOffset;
Result := FormatDateTime(cIntlDateTimeStor,vDateTime)+' '+Signs[Offset div abs(offset)]+Format('%.4d',[offset div 60*-100]);
end;
function DateTime2XMLDateTimeNoTZ(const vDateTime: TDateTime): AnsiString;
var offset : integer;
const Signs : array[-1..1] of char = ('+',' ','-');
begin
Result := FormatDateTime(cIntlDateTimeStor,vDateTime);
end;
function FileTimeToDTime(FTime: TFileTime): TDateTime;
var
LocalFTime: TFileTime;
STime: TSystemTime;
begin
FileTimeToLocalFileTime(FTime, LocalFTime);
FileTimeToSystemTime(LocalFTime, STime);
Result := SystemTimeToDateTime(STime);
end;
Procedure ExploitInfo(Info : TSearchRec; var CDT,ADT,MDT : TDateTime; var SZ : UInt64);
begin
with info do
begin
CDT := FileTimeToDTime(FindData.ftCreationTime);
ADT := FileTimeToDTime(FindData.ftLastAccessTime);
MDT := FileTimeToDTime(FindData.ftLastWriteTime);
SZ := Size;
end;
end;
Function IsFileNewer(Info : TSearchRec; TestDate : TDateTime) : boolean;
begin
with info do
begin
Result := FileTimeToDTime(FindData.ftLastWriteTime) >= TestDate;
end;
end;
function GetComputerNetName: string;
var
buffer: ShortString;
size: dword;
begin
size := 250;
buffer := StringOfChar(' ',sizeOf(buffer));
if GetComputerName(@Buffer[1], size) then
begin
Result := StrPas(@buffer[1]);
end
else
Result := ''
end;
constructor TFileInfoArray.Create();
begin
SetLength(fArray,SizeLimit);
end;
function TFileInfoArray.GetFileInfo(Index : Integer) : TFileInfo;
begin
Result := fArray[Index];
end;
Procedure TFileInfoArray.SetFileInfo(Index : Integer; Fi : TFileInfo);
begin
fArray[index] := Fi;
end;
function TFileInfoArray.GetCount : Integer;
begin
Result := SizeLimit;
end;
function TFileInfoArray.GetData : string;
var i : integer;
begin
Result := 'FileInfoArray : ';
for i := 0 to pred(Count) do
if Assigned(FileInfo[i]) then
Result := Result + IntToStr(i) + '-' +FileINfo[i].GetData;
end;
function TFileInfoArray.GetJSON : Ansistring;
var i : integer;
var virg : String = '';
begin
Result := '"FileInfoArray" : [';
for i := 0 to pred(Count) do
if Assigned(FileInfo[i]) then
begin
Result := Result + virg + '{ "Index": '+IntToStr(i)+', '+FileINfo[i].GetJSON+' }';
virg := ', ';
end;
Result := Result + ']';
end;
constructor Tfileinfo.Create;
begin
fMinCreateDT := maxDateTime;
fMinAccessDT := maxDateTime;
fMinModifyDT := maxDateTime;
fMaxCreateDT := minDateTime;
fMaxAccessDT := minDateTime;
fMaxModifyDT := minDateTime;
fmaxsize := 0;
fminsize := high(uInt64);
fnbfile := 0;
ftotalsize := 0;
end;
function Tfileinfo.GetData : string;
begin
if nbfile=0 then
Result := 'NbF:0'
else
Result := 'MinCD:'+DateTimeToStr(MinCreateDT)+', '+
'MaxCD:'+DateTimeToStr(MaxCreateDT)+', '+
'MinAD:'+DateTimeToStr(MinAccessDT)+', '+
'MaxAD:'+DateTimeToStr(MaxAccessDT)+', '+
'MinMD:'+DateTimeToStr(MinModifyDT)+', '+
'MaxMD:'+DateTimeToStr(MaxModifyDT)+', '+
'NbF:'+IntToStr(nbfile)+', '+
'minSize:'+GetSizeHRb(minSize)+', '+
'maxSize:'+GetSizeHRb(maxSize)+', '+
'TotalSize:'+GetSizeHRb(TotalSize);
end;
function Tfileinfo.GetJSON : AnsiString;
begin
Result := '"MinCreateDT" : "'+DateTime2XMLDateTime(MinCreateDT)+'", '+
'"MaxCreateDT" : "'+DateTime2XMLDateTime(MaxCreateDT)+'", '+
'"MinAccessDT" : "'+DateTime2XMLDateTime(MinAccessDT)+'", '+
'"MaxAccessDT" : "'+DateTime2XMLDateTime(MaxAccessDT)+'", '+
'"MinModifyDT" : "'+DateTime2XMLDateTime(MinModifyDT)+'", '+
'"MaxModifyDT" : "'+DateTime2XMLDateTime(MaxModifyDT)+'", '+
'"NbFile" : '+IntToStr(nbfile)+', '+
'"MinSize" : '+IntToStr(minSize)+', '+
'"MaxSize" : '+IntToStr(maxSize)+', '+
'"TotalSize" : '+IntToStr(TotalSize);
end;
function TFileInfo.SetNewSize(SZ : UInt64) : uInt64;
begin
TotalSize := TotalSize + SZ;
if SZ<minSize then
minSize := SZ;
if SZ>MaxSize then
MaxSize := SZ;
result := TotalSize;
end;
Procedure TFileInfo.SetMinMaxDate(SDate : TDateTime; var Mindate, maxDate : TDateTime);
begin
if SDate>maxDate then
maxDate := SDate;
if SDate<Mindate then
Mindate := SDate;
end;
function TFileInfoArray.TakeAccount(Info : TSearchRec; LimIndex : Integer) : uInt64;
var CDT,ADT,MDT : TDateTime;
var SZ : UInt64;
begin
ExploitInfo(info, CDT,ADT,MDT,SZ);
if not Assigned(FileInfo[LimIndex]) then
FileInfo[LimIndex] := TFileInfo.Create;
with FileInfo[LimIndex] do
begin
nbfile := nbfile + 1;
SetMinMaxDate(CDT,fMinCreateDT,fMaxCreateDT);
SetMinMaxDate(ADT, fMinAccessDT,fmaxAccessDT);
SetMinMaxDate(MDT,fminModifyDT,fmaxModifyDT);
Result := SetNewSize(SZ);
end;
end;
function StrToUInt64(const S: String): UInt64;
var c: cardinal;
P: PChar;
begin
P := @S[1];
if P=nil then begin
result := 0;
exit;
end;
if ord(P^) in [1..32] then repeat inc(P) until not(ord(P^) in [1..32]);
c := ord(P^)-48;
if c>9 then
result := 0 else begin
result := c;
inc(P);
repeat
c := ord(P^)-48;
if c>9 then
break else
result := result*10+c;
inc(P);
until false;
end;
end;
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Procedure interne utilitaire
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
function EvaluateUnity(Valyou : String): UInt64;
var Valeur : UInt64;
Unite : UInt64;
Pos : Word;
begin
Result := 0;
Pos := 1;
while Pos<=Length(Valyou) do
begin
if not (Valyou[Pos] in ['0'..'9']) then
Break;
Inc(Pos);
end;
try
if Pos<=Length(Valyou) then
begin
// write('on va tester '+lowercase(Valyou[Pos]));
case lowercase(Valyou[Pos]) of
'b': Unite := 1;
'k': Unite := 1 << 10;
'm': Unite := 1 << 20;
'g': Unite := 1 << 30;
't': Unite := 1 << 40;
'p': Unite := 1 << 50;
else
Unite := 0;
end;
Valeur := StrToUInt64(LeftStr(Valyou,Pos-1));
end
else
begin
unite := 1;
Valeur := StrToUInt64(Valyou);
end;
Result := Unite * Valeur;
except on e: EConvertError do
writeln('Exception ConvertError on ('+ValYou+') : Pos=',Pos,', "',e.message,'"');
end;
end;
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Procedure interne utilitaire
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
function GetSizeHRAny(fSize : uInt64; IndexV : Integer): WideString;
const Units : array[1..6] of string = ('','Kib','Mib','Gib','Tib','Pib');
var index : Integer;
isize : UInt64;
divider : UInt64;
begin
divider := 1;
index := IndexV;
isize := fsize;
while (index<=6) and (isize>1024) do
begin
index := index + 1;
isize := isize div 1024;
divider := divider << 10;
end;
result := IntToStr(isize);
if (isize>0) and (fSize mod (isize*divider) > 0) then
begin
Result := Result + ',' + LeftStr(IntToStr(fSize mod (isize*divider))+'00',3);
end;
Result := Result + ' ' + Units[index]
end;
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Expression en forme Humaine
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
function GetSizeHRb(fSize : uInt64): WideString;
begin
Result := GetSizeHRAny(fSize,1);
end;
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Expression en forme Humaine
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
function GetSizeHRk(fSize : uInt64): WideString;
begin
Result := GetSizeHRAny(fSize,2);
end;
constructor TUInt64.Create(Val : UInt64);
begin
fValue := Val;
end;
function TUInt64.Add(Val : UInt64): UInt64;
begin
FValue := FValue + Val;
Result := FValue;
end;
function TUInt64.GetFromByteToHR : string;
begin
Result := GetSizeHRb(fValue);
end;
function TUInt64.GetFromKByteToHR : string;
begin
Result := GetSizeHRk(fValue);
end;
function NormalizePath(S : String) : String;
begin
Result := LowerCase(S);
if Result[Length((Result))]<>'\' then Result := Result + '\';
end;
function ProcessOneFormula(Buffer : string; var currentDate : TDateTime) : Boolean;
var
btIter : baseType;
itIter : incType;
Year, Month, Day, dow : word;
wMonth : Integer;
DoIt : Boolean;
Signe : Integer;
Value : Integer;
Code,Code2 : Integer;
begin
DoIt := False;
currentDate := Now;
for btIter := Low(baseType) to High(baseType) do
begin
// writeln('Item ' + IntToStr(Ord(btIter)) + ' - ' + baseTypeLib[btIter] + '.');
if (not DoIt) and
(copy(lowercase(Buffer),1,length(baseTypeLib[btIter]))=baseTypeLib[btIter]) and
(
(length(Buffer) = length(baseTypeLib[btIter])) or
(Buffer[Succ(length(baseTypeLib[btIter]))] in ['+','-'])
) then
begin
Delete(Buffer,1,length(baseTypeLib[btIter]));
// writeln('found: ' + IntToStr(Ord(btIter)) + ' - ' + baseTypeLib[btIter] + '.');
DoIt := True;
case btIter of
btYesterday:
CurrentDate := Now - 1;
btToday:
CurrentDate := Now;
btTomorow:
CurrentDate := Now + 1;
btWeekstart:
begin
dow := DayOfWeek(Now)-1;
if dow=0 then
dow := 7;
CurrentDate := Now - dow + 1;
end;
btWeekend:
begin
dow := DayOfWeek(Now)-1;
if dow=0 then
dow := 7;
CurrentDate := Now + 7- dow;
end;
btMonthstart:
begin
DecodeDate(Now, Year, Month, Day);
CurrentDate := EncodeDate(Year, Month, 1);
end;
btMonthend:
begin
DecodeDate(Now, Year, Month, Day);
CurrentDate := EncodeDate(Year, Month, 28) + 4;
DecodeDate(CurrentDate, Year, Month, Day);
CurrentDate := EncodeDate(Year, Month, 1)-1;
end;
btYearstart:
begin
DecodeDate(Now, Year, Month, Day);
CurrentDate := EncodeDate(Year, 01, 01);
end;
btYearend:
begin
DecodeDate(Now, Year, Month, Day);
CurrentDate := EncodeDate(Year, 12, 31);
end;
end;
end;
end;
if DoIt then
begin
// WriteLn('Date en cours : ' + FormatDateTime('dd/mm/yyyy', CurrentDate));
if Length(Buffer)>0 then
begin
Signe := 0;
case Buffer[1] of
'-' : Signe := -1;
'+' : Signe := 1;
else DoIt := False;
end;
if DoIt then
begin
Delete(Buffer,1,1);
Val(Buffer,Value,Code);
if Code=0 then
begin
Buffer:=incTypeLib[itDay];
end
else
begin
val(copy(Buffer,1,Pred(Code)),Value,Code2);
Delete(Buffer,1,Pred(Code));
end;
DoIt := False;
for itIter := Low(incType) to High(incType) do
begin
if (not DoIt) and
(
(copy(lowercase(Buffer),1,length(incTypeLib[itIter]))=incTypeLib[itIter]) or
(
(length(Buffer) = 1) and
(LowerCase(Buffer[1]) = incTypeLib[itIter][1])
)
) then
begin
DoIt := True;
case itIter of
itDay:
begin
CurrentDate := currentDate + (Signe*Value);
end;
itMonth :
begin
DecodeDate(currentDate, Year, Month, Day);
writeln('on a decode la date ', Year, Month, Day);
while (Value>=12) do
begin
Year := Year + Signe;
Value := Value - 12;
writeln('on a soustrait 12 mois ', Year, Month, Day);
end;
wMonth := Month;
wMonth := wMonth + Signe*Value;
case Signe of
1 :
begin
if wMonth>12 then
begin
wMonth := wMonth - 12;
Year := Year + 1;
end;
end;
-1 :
begin
if wMonth<1 then
begin
wMonth := wMonth + 12;
Year := Year - 1;
end;
end;
end;
Month := wMonth;
CurrentDate := EncodeDate(Year, Month, Day);
writeln('on a encode la date ', Year, Month, Day);
end;
itWeek :
begin
CurrentDate := currentDate + (Signe*Value*7);;
end;
itYear :
begin
DecodeDate(currentDate, Year, Month, Day);
CurrentDate := EncodeDate(Year + (Signe*Value), Month, Day);
end;
end;
end;
end;
end
else
begin
writeLn('Operateur non reconnu.');
end;
end;
Result := DoIt;
if not DoIt then
begin
writeLn('Increment non reconnu.');
end;
end
else
begin
writeLn('Base date non reconnue.');
Result := False;
end;
end;
end.
|
namespace MetalExample;
interface
uses
rtl,
Foundation,
RemObjects.Elements.RTL;
type
Asset = public class
public
// Loads the Content from aFilename as String
class method loadFile(const aFilename : String) : String;
class method loadFileBytes(const aFilename : String) : Array of Byte;
class method getFullname(const aFilename : String) : String; inline;
class method getUrlfor(const aFilename : String) : Foundation.URL;
end;
implementation
class method Asset.getFullname(const aFilename: String): String;
begin
exit Path.Combine(Bundle.mainBundle.resourcePath, aFilename);
end;
class method Asset.loadFile(const aFilename: String): String;
begin
var
{$IF TEST}
var lname : string = "";
{$ELSE}
lname := getFullname(aFilename);
{$ENDIF}
if lname.FileExists then
exit File.ReadText(lname) else exit nil;
end;
class method Asset.loadFileBytes(const aFilename: String): Array of Byte;
begin
var lname := getFullname(aFilename);
if lname.FileExists then
exit File.ReadBytes(lname) else exit nil;
end;
class method Asset.getUrlfor(const aFilename: String): Foundation.Url;
begin
exit Foundation.URL.fileURLWithPath(getFullname(aFilename));
end;
end. |
unit Test_FIToolkit.Logger.Types;
{
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,
FIToolkit.Logger.Types;
type
// Test methods for class TLogMsgTypeDescriptions
TestTLogMsgTypeDescriptions = class(TGenericTestCase)
strict private
FLogMsgTypeDescriptions: TLogMsgTypeDescriptions;
published
procedure TestCreate;
procedure TestItems;
procedure TestMaxItemLength;
procedure TestUninitialized;
end;
implementation
uses
System.SysUtils,
TestUtils;
{ TestTLogMsgTypeDescriptions }
procedure TestTLogMsgTypeDescriptions.TestCreate;
const
STR_INFO_DESC = 'INFO';
STR_WARNING_DESC = 'WARNING';
STR_ERROR_DESC = 'ERROR';
INT_DUPLICATE_FACTOR = 3;
var
arrDescs : TArray<TLogMsgTypeDescription>;
LMT : TLogMsgType;
iDupCycleCount, i : Integer;
begin
{ Check regular creation }
FLogMsgTypeDescriptions := TLogMsgTypeDescriptions.Create([
TLogMsgTypeDescription.Create(lmInfo, STR_INFO_DESC),
TLogMsgTypeDescription.Create(lmWarning, STR_WARNING_DESC),
TLogMsgTypeDescription.Create(lmError, STR_ERROR_DESC)
]);
CheckEquals(STR_INFO_DESC, FLogMsgTypeDescriptions[lmInfo], 'Items[lmInfo] = STR_INFO_DESC');
CheckEquals(STR_WARNING_DESC, FLogMsgTypeDescriptions[lmWarning], 'Items[lmWarning] = STR_WARNING_DESC');
CheckEquals(STR_ERROR_DESC, FLogMsgTypeDescriptions[lmError], 'Items[lmError] = STR_ERROR_DESC');
CheckTrue(FLogMsgTypeDescriptions[lmFatal].IsEmpty, 'CheckTrue::Items[lmFatal].IsEmpty');
{ Check creation via oversized array with duplicates }
SetLength(arrDescs, (Ord(High(TLogMsgType)) - Ord(Low(TLogMsgType)) + 1) * INT_DUPLICATE_FACTOR);
LMT := Low(TLogMsgType);
iDupCycleCount := 1;
for i := 0 to High(arrDescs) do
begin
arrDescs[i] := TLogMsgTypeDescription.Create(LMT, Format('ITEM_%d_DUP_%d', [Ord(LMT), iDupCycleCount]));
if LMT <> High(TLogMsgType) then
LMT := Succ(LMT)
else
begin
Inc(iDupCycleCount);
LMT := Low(TLogMsgType);
end;
end;
FLogMsgTypeDescriptions := TLogMsgTypeDescriptions.Create(arrDescs);
for LMT := Low(TLogMsgType) to High(TLogMsgType) do
CheckTrue(FLogMsgTypeDescriptions[LMT].EndsWith('_DUP_' + INT_DUPLICATE_FACTOR.ToString),
'CheckTrue::Items[LMT].EndsWith("_DUP_%d")', [INT_DUPLICATE_FACTOR]);
end;
procedure TestTLogMsgTypeDescriptions.TestItems;
var
LMT : TLogMsgType;
sDesc : String;
begin
for LMT := Low(TLogMsgType) to High(TLogMsgType) do
begin
sDesc := 'TEST_' + Ord(LMT).ToString;
FLogMsgTypeDescriptions[LMT] := sDesc;
CheckEquals(sDesc, FLogMsgTypeDescriptions[LMT], 'Items[LMT] = sDesc');
end;
end;
procedure TestTLogMsgTypeDescriptions.TestMaxItemLength;
const
STR_SHORT_DESC = '123';
STR_MEDIUM_DESC = '12345';
STR_LONG_DESC = '1234567';
begin
FLogMsgTypeDescriptions := TLogMsgTypeDescriptions.Create([
TLogMsgTypeDescription.Create(lmDebug, STR_SHORT_DESC),
TLogMsgTypeDescription.Create(lmError, STR_LONG_DESC),
TLogMsgTypeDescription.Create(lmInfo, STR_MEDIUM_DESC)
]);
CheckEquals(STR_LONG_DESC.Length, FLogMsgTypeDescriptions.MaxItemLength, 'MaxItemLength = STR_LONG_DESC.Length');
end;
procedure TestTLogMsgTypeDescriptions.TestUninitialized;
var
LMT : TLogMsgType;
begin
CheckEquals(0, FLogMsgTypeDescriptions.MaxItemLength, 'MaxItemLength = 0');
for LMT := Low(TLogMsgType) to High(TLogMsgType) do
CheckTrue(FLogMsgTypeDescriptions[LMT].IsEmpty, 'CheckTrue::Items[LMT].IsEmpty');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTLogMsgTypeDescriptions.Suite);
end.
|
unit gozfunc;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
function StrInt(s: string): integer;
function StrFloat(s: string): extended;
var
ConfigFilename : string;
implementation
function StrInt(s: string): integer;
begin
try
result:=StrToInt(s);
except
result:=0;
end;
end;
function StrFloat(s: string): extended;
begin
try
DecimalSeparator:=',';
result:=StrToFloat(s);
except
result:=0.0;
end;
end;
end.
|
{*******************************************************}
{ }
{ Copyright (C) 1999-2000 Inprise Corporation }
{ }
{*******************************************************}
unit ClientMain;
{ This illustrates two ways to use MIDAS with CORBA. The first takes a MIDAS data
packet on the server side and converts it to a CORBA Any. The Any is sent across
the wire and the client populates the database grid.
The second method gets the MIDAS data packet on the server side as XML, then
loads it in a string variable that is marshalled across the wire via CORBA.
Look at the DMPooler module. This shows a thread safe technieque for pooling
database connections. Instead of getting a new connection for every database
request, this module creates a pool of connections and reuses them. That way
BDE resourse errors are avoided.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Grids, Corba, Employee_i, Employee_c, Db, DBClient, ExtCtrls,
DBCtrls, DBGrids;
type
TForm1 = class(TForm)
Button1: TButton;
DBGrid1: TDBGrid;
cdsEmployee: TClientDataSet;
DataSource1: TDataSource;
edtEmployeeName: TEdit;
Button2: TButton;
Memo1: TMemo;
Label1: TLabel;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
myEmployee : Employee;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
myEmployee := TEmployeeHelper.bind;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
cdsEmployee.Data := myEmployee.getEmployeesByName(edtEmployeeName.Text);
cdsEmployee.Open;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
rtn: WideString;
str: TStringStream;
begin
rtn := myEmployee.getEmployeesByNameXML(edtEmployeeName.Text);
Memo1.Lines.Text:=rtn;
//Get XML data from server and load it into stream
str := TStringStream.Create(rtn);
try
cdsEmployee.Close;
cdsEmployee.LoadFromStream(str);
cdsEmployee.Open;
finally
str.Free;
end;
end;
end.
|
{$mode objfpc}
unit Tokenizer;
interface
uses List, SysUtils;
type TCharList = specialize List.TList<char>;
type TCharListIterator = specialize List.TConstIterator<char>;
type TStringList = specialize List.TList<string>;
type TStringListIterator = specialize List.TConstIterator<string>;
type TType = (
identifier, literal,
parenthesis_l, parenthesis_r,
op_plus, op_minus,
op_div, op_mult,
op_pow
);
type TToken = class
public
Priority : integer;
TokenType : TType;
Position : integer;
Original : string;
constructor CreateFromAttributes( p: integer ; t: TType; s: string );
end;
type TTokenList = specialize List.TList<TToken>;
type TTokenListIterator = specialize List.TConstIterator<TToken>;
type TTokenizer = class
private
_tokens : TTokenList;
function CharsFromArgs : TCharList;
function ProcessChars( chars : TCharList ) : TTokenList;
procedure ProcessNumericLiteral( chIt : TCharListIterator; toks : TTokenList );
procedure ProcessIdentifier( chIt : TCharListIterator; toks : TTokenList );
function IsDigit( ch : char ) : boolean;
function IsAlpha( ch : char ) : boolean;
public
constructor CreateFromArgs;
function GetTokens : TTokenList;
end;
implementation
constructor TToken.CreateFromAttributes( p: integer ; t: TType; s: string );
begin
Original := s;
TokenType := t;
Position := p;
case t of
TType.literal, TType.identifier:
Priority := 0;
TType.op_plus, TType.op_minus:
Priority := 1;
TType.op_mult, TType.op_div:
Priority := 2;
TType.op_pow:
Priority := 3;
else
Priority := -1;
end;
end;
constructor TTokenizer.CreateFromArgs;
var chars: TCharList;
begin
chars := CharsFromArgs;
_tokens := ProcessChars( chars );
end;
function TTokenizer.CharsFromArgs : TCharList;
var argi: integer;
var ci: integer;
var arg: string;
var argl: integer;
var chars: TCharList;
begin
chars := TCharList.Create;
for argi := 1 to ParamCount do begin
arg := ParamStr(argi);
argl := length(arg);
for ci := 1 to argl do begin
chars.PushBack( arg[ci] );
end;
chars.PushBack( ' ' );
end;
Result := chars;
end;
function TTokenizer.IsAlpha( ch : char ) : boolean;
begin
case ch of
'A'..'Z','a'..'z','_': begin
Result := true;
end;
else begin
Result := false;
end
end;
end;
function TTokenizer.IsDigit( ch : char ) : boolean;
begin
case ch of
'0','1'..'9': begin
Result := true;
end;
else begin
Result := false;
end
end;
end;
procedure TTokenizer.ProcessIdentifier( chIt : TCharListIterator; toks : TTokenList );
var token : TToken;
begin
//WriteLn('Processing identifier at ', chIt.GetPosition);
token := TToken.Create;
token.TokenType := TType.identifier;
token.Position := chIt.GetPosition;
token.Original := chIt.GetNext;
while chIt.HasNext and ( IsDigit( chIt.Peek ) or IsAlpha( chIt.Peek ) ) do begin
token.Original := token.Original + chIt.GetNext;
end;
toks.PushBack( TToken.CreateFromAttributes( token.Position, token.TokenType, token.Original ) );
token.Free;
end;
procedure TTokenizer.ProcessNumericLiteral( chIt : TCharListIterator; toks : TTokenList );
var token : TToken;
begin
//WriteLn('Processing numeric literal at ', chIt.GetPosition);
token := TToken.Create;
token.TokenType := TType.literal;
token.Position := chIt.GetPosition;
token.Original := '';
while chIt.HasNext and IsDigit( chIt.Peek ) do begin
token.Original := token.Original + chIt.GetNext;
end;
toks.PushBack( TToken.CreateFromAttributes( token.Position, token.TokenType, token.Original ) );
token.Free;
end;
function TTokenizer.ProcessChars( chars : TCharList ) : TTokenList;
var toks: TTokenList;
var chIt: TCharListIterator;
var currentChar: char;
begin
toks := TTokenList.Create;
chIt := chars.GetConstIterator;
while chIt.HasNext do begin
currentChar := chIt.Peek;
case currentChar of
'1'..'9','0': ProcessNumericLiteral( chIt, toks );
'a'..'z','A'..'Z': ProcessIdentifier( chIt, toks );
'(',')': begin
//WriteLn('Processing parenthesis token at ', chIt.GetPosition);
case chIt.GetNext of
'(': toks.PushBack( TToken.CreateFromAttributes( chIt.GetPosition, TType.parenthesis_l, '(' ) );
')': toks.PushBack( TToken.CreateFromAttributes( chIt.GetPosition, TType.parenthesis_r, ')' ) );
end;
end;
'*','/','+','-','^': begin
//WriteLn('Processing operation token at ', chIt.GetPosition);
case chIt.GetNext of
'*': begin
toks.PushBack( TToken.CreateFromAttributes( chIt.GetPosition, TType.op_mult, '*' ) );
end;
'/': begin
toks.PushBack( TToken.CreateFromAttributes( chIt.GetPosition, TType.op_div, '/' ) );
end;
'-': begin
toks.PushBack( TToken.CreateFromAttributes( chIt.GetPosition, TType.op_minus, '-' ) );
end;
'+': begin
toks.PushBack( TToken.CreateFromAttributes( chIt.GetPosition, TType.op_plus, '+' ) );
end;
'^': begin
toks.PushBack( TToken.CreateFromAttributes( chIt.GetPosition, TType.op_pow, '^' ) );
end;
end
end;
' ': chIt.GetNext;
else begin
WriteLn('Unexpected char ''', currentChar, ''' at position ', chIt.GetPosition);
Result := nil;
break;
end;
end;
end;
Result := toks;
end;
function TTokenizer.GetTokens : TTokenList;
begin
Result := _tokens;
end;
end.
|
{:
UUrl
Модуль cодержить методы для работы со строкой запроса.
}
unit UUrl;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
UHash;
type
Url = class(TObject)
public
class function build(const aURL: string; aNameValueParams: array of
variant; unionParams: Boolean = false; enc: Boolean = false;
noCache: boolean = true): string; overload; static;
//1 Строим строку запроса из входного hash
class function build(const cHash: THash; enc: Boolean = false; noCache:
boolean = true): string; overload; static;
class function build(const cHash: THash; const cNameValueParams: array
of variant; unionParams: Boolean = false; enc: Boolean = false;
noCache: boolean = true): string; overload; static;
class function build(cHash, cParams: THash; unionParams: Boolean =
false; enc: Boolean = false; noCache: boolean = true): string;
overload; static;
//1 Парсинг строки параметров
class function params(params: string; toHash: THash = nil; dec: Boolean
= false): THash; static;
{:
Парсинг строки url.
Возвращает hash след струкутуры;
hash['uri'] - входная строка
hash['addr'] - строка без параметров
hash['protocol'] - тип протокола http или https
hash['path'] - путь
hash['hpath'] - путь с протоколом и доменом
hash['document'] - имя конечного файл скрипта
hash['param'] - строка параметров
hash.hash['params'] - hash параметров
Examples:
uri = "https://www.windeco.su/dev/test/index.php?h=10&t=89"
addr = "https://www.windeco.su/dev/test/index.php"
protocol = "https"
host = "www.windeco.su"
path = "/dev/test/"
hpath = "https://www.windeco.su/dev/test/"
document = "index.php"
param = "h=10&t=89"
params = [
h = "10"
t = "89"
]
}
class function parse(const aURL: string; toHash: THash = nil; dec:
Boolean = false): THash; static;
end;
implementation
uses IdURI, UUtils;
{
************************************* Url **************************************
}
class function Url.build(const aURL: string; aNameValueParams: array of variant;
unionParams: Boolean = false; enc: Boolean = false; noCache: boolean =
true): string;
var
cHash: THash;
cParams: THash;
begin
cHash:=parse(aUrl);
cParams:=Hash(aNameValueParams);
result:=build(cHash,cParams,unionParams,enc,noCache);
FreeHash(cParams);
FreeHash(cHash);
end;
class function Url.build(const cHash: THash; enc: Boolean = false; noCache:
boolean = true): string;
var
cParam: string;
cParams: string;
i: Integer;
begin
cParams:='';
for i:=0 to cHash.Hash['params'].Count-1 do begin
if (i=0) then
cParams:='?'
else
cParams:=cParams+'&';
cParams:=cParams+cHash.Hash['params'].Name[i];
if (cHash.Hash['params'][i]<>'') then begin
cParam:=cHash.Hash['params'][i];
if (enc) then begin
cParam:=Utils.rusCod(cParam);
cParam:=Utils.urlEncode(cParam);
end;
cParams:=cParams+'='+cParam;
end;
end;
if (noCache) then begin
if (cParams='') then
cParams:=cParams+'?'
else
cParams:=cParams+'&';
cParams:=cParams+'noCache='+Utils.randomStr(5);
end;
result:=cHash['addr']+cParams;
end;
class function Url.build(const cHash: THash; const cNameValueParams: array of
variant; unionParams: Boolean = false; enc: Boolean = false; noCache:
boolean = true): string;
var
cParams: THash;
begin
cParams :=Hash(cNameValueParams);
result :=build(cHash,cParams,unionParams,enc,noCache);
FreeHash(cParams);
end;
class function Url.build(cHash, cParams: THash; unionParams: Boolean = false;
enc: Boolean = false; noCache: boolean = true): string;
begin
if (unionParams) then
cHash.Hash['params'].union(cParams)
else
cHash.Hash['params'].assign(cParams);
result:=build(cHash,enc,noCache);
end;
class function Url.params(params: string; toHash: THash = nil; dec: Boolean =
false): THash;
var
cHash: THash;
cNameValue: THash;
cParam: string;
i: Integer;
begin
if (toHash = nil) then
result:=Hash()
else
result:=toHash;
params:=trim(params);
if (pos('?',params) = 1) then
params:=copy(params,2);
cHash:=Utils.explode(params,'&');
for i:=0 to cHash.Count-1 do
begin
cNameValue:=Utils.explode(cHash[i],'=');
if (cNameValue.Count>1) then begin
cParam:= cNameValue[1];
if(dec) then begin
cParam:=Utils.urlDecode(cParam);
cParam:=Utils.rusEnCod(cParam);
end;
result[cNameValue[0]] := cParam;
end else
result[cNameValue[0]] := '';
FreeHash(cNameValue);
end;
FreeHash(cHash);
end;
class function Url.parse(const aURL: string; toHash: THash = nil; dec: Boolean
= false): THash;
var
cUri: TIdURI;
cHash: THash;
cNameValue: THash;
i: Integer;
begin
if (toHash = nil) then
result:=Hash()
else
result:=toHash;
cUri := TIdURI.Create(aUrl);
try try
result.clear;
result['uri'] := cUri.URI;
result['addr'] := cUri.Protocol+'://'+cUri.Host+cUri.path+cUri.Document;
result['protocol'] := cUri.Protocol;
result['host'] := cUri.Host;
result['path'] := cUri.path;
result['hpath'] := cUri.Protocol+'://'+cUri.Host+cUri.path;
result['document'] := cUri.Document;
result['param'] := cUri.Params;
cHash:=params(cUri.Params,nil,dec);
result.Hash['params'].assign(cHash);
FreeHash(cHash);
except on e:Exception do begin
end;end;
finally
if cUri<>nil then
cUri.Free;
end;
end;
end.
|
{$I-}
unit SFU_cmd;
interface
uses
linkclient;
type
tSFUcmd_EventWrite=procedure(data:pbyte; size:integer) of object;
tSFUcmd_EventCommand=procedure(code:byte; body:pbyte; count:word) of object;
tSFUcmd_EventInfoString=procedure(sender:tobject; msg:string) of object;
tSFUcmd_EventLog=procedure(sender:tobject; msg:string) of object;
tSFUcmd_internalParser = procedure(data:byte) of object;
tSFUcmd = class
private
info_string : ansistring;
recive_seq : cardinal;
recive_buf : array[0..4095] of byte;
recive_cnt : cardinal;
recive_code : byte;
recive_code_n : byte;
recive_size : word;
recive_body : pbyte;
recive_crc : cardinal;
recive_timelimit : cardinal;
recive_block_cnt : cardinal;
onParse : tSFUcmd_internalParser;
raw_log : file;
function error_check(error_flag:boolean; msg:string; var stat:cardinal):boolean;
function recive_block_add(data:byte; need:cardinal):boolean;
procedure parse_start(data:byte);
procedure parse_info(data:byte);
procedure parse_body(data:byte);
procedure parse_crc(data:byte);
protected
procedure log(msg:string);
public
stat_send : cardinal;
stat_normals : cardinal;
stat_errors : cardinal;
stat_error_timeout : cardinal;
stat_error_overfull : cardinal;
stat_error_start : cardinal;
stat_error_code : cardinal;
stat_error_size : cardinal;
stat_error_crc : cardinal;
send_buf : array[0..4095] of byte;
send_cnt : integer;
onWrite : tSFUcmd_EventWrite;
onCommand : tSFUcmd_EventCommand;
onInfoString : tSFUcmd_EventInfoString;
onLog : tSFUcmd_EventLog;
constructor create(write:tSFUcmd_EventWrite = nil; command:tSFUcmd_EventCommand = nil; infostring:tSFUcmd_EventInfoString = nil; log:tSFUcmd_EventLog = nil);
function send_command(code:byte; cmd_body:pointer = nil; size:word = 0):cardinal;
procedure process_recive(sender:tLinkClient; data:pbyte; size:integer);
procedure recive_reset;
end;
implementation
uses
SysUtils, Windows, CRCunit;
Const
PACKET_SIGN_TX:cardinal = $817EA345;
PACKET_SIGN_RX:cardinal = $45A37E81;
RECIVE_TIMEOUT_mS = 200;
constructor tSFUcmd.create(write:tSFUcmd_EventWrite = nil; command:tSFUcmd_EventCommand = nil; infostring:tSFUcmd_EventInfoString = nil; log:tSFUcmd_EventLog = nil);
begin
onParse := self.parse_start;
onWrite := write;
onCommand := command;
onInfoString := infostring;
onLog := log;
AssignFile(raw_log, 'raw_log.dat');
rewrite(raw_log, 1);
end;
procedure tSFUcmd.log(msg:string);
begin
if @onlog<>nil then
onLog(self, msg);
end;
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
function tSFUcmd.send_command(code:byte; cmd_body:pointer = nil; size:word = 0):cardinal;
var
crc : cardinal;
pos : integer;
body : array of byte absolute cmd_body;
begin
if (size mod 4) <> 0 then
begin
log('tSFUcmd.send_command ERROR: size mod 4 <> 0');
result := 0;
exit;
end;
send_buf[0] := (PACKET_SIGN_TX shr 24) and $FF;
send_buf[1] := (PACKET_SIGN_TX shr 16) and $FF;
send_buf[2] := (PACKET_SIGN_TX shr 8) and $FF;
send_buf[3] := (PACKET_SIGN_TX shr 0) and $FF;
send_buf[4] := code xor $00;
send_buf[5] := code xor $FF;
if cmd_body = nil then
size := 0;
send_buf[6] := (size shr (8*0)) and 255;
send_buf[7] := (size shr (8*1)) and 255;
for pos := 0 to size - 1 do
send_buf[8 + pos] := body[pos];
crc := crc_stm32(@send_buf[4], (size + 4) div 4); //+4: code + ncode + size
send_buf[8 + size + 0] := (crc shr (8*0)) and 255;
send_buf[8 + size + 1] := (crc shr (8*1)) and 255;
send_buf[8 + size + 2] := (crc shr (8*2)) and 255;
send_buf[8 + size + 3] := (crc shr (8*3)) and 255;
send_cnt := 8 + size + 4;
if @onWrite <> nil then
onWrite(@send_buf[0], send_cnt);
inc(stat_send);
result := send_cnt;
end;
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
function tSFUcmd.recive_block_add(data:byte; need:cardinal):boolean;
begin
result := false;
if error_check(recive_cnt >= length(recive_buf), 'recive_cnt >= length(recive_buf)', stat_error_overfull) then
exit;
recive_buf[recive_cnt] := data;
inc(recive_cnt);
inc(recive_block_cnt);
result := (recive_block_cnt >= need);
if result then
recive_block_cnt := 0;
end;
procedure tSFUcmd.recive_reset;
begin
onParse := self.parse_start;
recive_block_cnt := 0;
recive_cnt := 0;
end;
function tSFUcmd.error_check(error_flag:boolean; msg:string; var stat:cardinal):boolean;
begin
result := error_flag;
if not error_flag then exit;
log('SFUcmd ERROR: ' + msg);
recive_reset;
inc(stat_errors);
inc(stat);
end;
////////////////////////////////////////////////////////////////////////////////////
procedure tSFUcmd.parse_start(data:byte);
var
pos : integer;
begin
if data in [9, 32..255] then
info_string := info_string + ansichar(data);
// else
// if not (data in [13, 10]) then
// info_string := info_string + '<' + inttohex(data, 2) + '>';
recive_seq := (recive_seq shl 8) or data;
if recive_seq = PACKET_SIGN_RX then
begin
delete(info_string, length(info_string) - 3, 4);
dec(stat_error_start, 3);
recive_timelimit := gettickcount + RECIVE_TIMEOUT_mS;
onParse := parse_info;
recive_block_cnt := 0;
recive_cnt := 0;
end
else
begin
inc(stat_error_start);
if (data = 13) or (length(info_string) > 128) then
begin
if @onInfoString <> nil then
onInfoString(self, info_string);
info_string := '';
end;
end;
end;
procedure tSFUcmd.parse_info(data:byte);
begin
if not recive_block_add(data, 4) then exit;
recive_code := recive_buf[0] xor $00;
recive_code_n := recive_buf[1] xor $FF;
if error_check(recive_code <> recive_code_n, 'recive_code <> recive_code_n', stat_error_code) then
exit;
recive_size := (word(recive_buf[2]) shl 0) or
(word(recive_buf[3]) shl 8);
if error_check(recive_size >= (Length(recive_buf) - 8), 'recive_size >= (Length() - 8)', stat_error_size) then
exit;
recive_body := @(recive_buf[4]);
if recive_size = 0 then
onParse := parse_crc
else
onParse := parse_body;
end;
procedure tSFUcmd.parse_body(data:byte);
begin
if not recive_block_add(data, recive_size) then
exit;
onParse := parse_crc;
end;
procedure tSFUcmd.parse_crc(data:byte);
var
need_crc : cardinal;
begin
if not recive_block_add(data, 4) then exit;
need_crc := crc_stm32(pcardinal(@recive_buf[0]), (recive_cnt - 4) div 4);
recive_crc := (cardinal(recive_buf[recive_cnt - 4]) shl 0) or
(cardinal(recive_buf[recive_cnt - 3]) shl 8) or
(cardinal(recive_buf[recive_cnt - 2]) shl 16) or
(cardinal(recive_buf[recive_cnt - 1]) shl 24);
if error_check(need_crc <> recive_crc, 'need_crc <> recive_crc', stat_error_crc) then
exit;
inc(stat_normals);
if @onCommand <> nil then
onCommand(recive_code, recive_body, recive_size);
recive_reset;
end;
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
procedure tSFUcmd.process_recive(sender:tLinkClient; data:pbyte; size:integer);
var
p : pointer;
begin
BlockWrite(raw_log, data^, size);
if (TMethod(onParse).Code <> @tSFUcmd.parse_start) then
error_check(GetTickCount > recive_timelimit, 'tSFUcmd:RECIVE_TIMEOUT', stat_error_timeout);
if data <> nil then
while size > 0 do
begin
onParse(data^);
inc(data);
dec(size);
end;
end;
end.
|
unit MyTreeView;
//{$MODE Delphi}
//# BEGIN TODO Completed by: author name, id.nr., date
{ Replace this line by your text }
//# END TODO
//------------------------------------------------------------------------------
// This unit defines class TMyTreeView, which is a descendant of the standard
// TTreeView component from the Delphi VCL (Vusial Component Library).
// See the Delphi Help for information on TTreeView !!
//
interface
uses
ComCtrls,
Nodes;
type
TMyTreeView =
class(TTreeView)
private
public
procedure SelectNode(ANode: TNode);
procedure Show(ANode: TNode);
end;
implementation
{ TMyTreeView }
procedure TMyTreeView.SelectNode(ANode: TNode);
var
I: integer;
begin
with Items do
for I := 0 to Count - 1 do
if Item[I].Data = ANode
then Selected := Item[I];
end;
procedure TMyTreeView.Show(ANode: TNode);
//# BEGIN TODO
// Add declarations of local variables and/or functions, if necessary
//# END TODO
procedure RecAddSons(AFather: TTreeNode; ANode: TNode);
begin
//# BEGIN TODO
// Recursively build a tree of TTreeNode with root AFather corresponding to
// the formula tree with root ANode
//# END TODO
end;
begin
//# BEGIN TODO
{ Add code corresponding to the following steps:}
// Clear Items
// Add a new root object corresponding to ANode
// Recursively add sons by means of procedure RecAddSons
// Show the tree in expanded form
//# END TODO
end;
end.
|
unit FIToolkit.Logger.Impl;
interface
uses
System.SysUtils, System.Rtti, System.TypInfo, System.Generics.Collections,
FIToolkit.Logger.Intf, FIToolkit.Logger.Types;
type
TLogOutputList = class (TThreadList<ILogOutput>);
TAbstractLogger = class abstract (TInterfacedObject, ILogger)
strict private
FAllowedItems : TLogItems;
FOutputs : TLogOutputList;
FSeverityThreshold : TLogMsgSeverity;
private
function GetAllowedItems : TLogItems;
function GetEnabled : Boolean;
function GetSeverityThreshold : TLogMsgSeverity;
procedure SetAllowedItems(Value : TLogItems);
procedure SetSeverityThreshold(Value : TLogMsgSeverity);
strict protected
property Outputs : TLogOutputList read FOutputs;
protected
function GetDefaultAllowedItems : TLogItems; virtual;
function GetDefaultSeverityThreshold : TLogMsgSeverity; virtual;
function IsAllowedItem(Item : TLogItem) : Boolean; virtual;
public
constructor Create; virtual;
destructor Destroy; override;
function AddOutput(const LogOutput : ILogOutput) : ILogOutput;
procedure EnterSection(const Msg : String = String.Empty); overload; virtual; abstract;
procedure EnterSection(const Vals : array of const); overload; virtual; abstract;
procedure EnterSectionFmt(const Msg : String; const Args : array of const); virtual; abstract;
procedure EnterSectionVal(const Vals : array of TValue); virtual; abstract;
procedure LeaveSection(const Msg : String = String.Empty); overload; virtual; abstract;
procedure LeaveSection(const Vals : array of const); overload; virtual; abstract;
procedure LeaveSectionFmt(const Msg : String; const Args : array of const); virtual; abstract;
procedure LeaveSectionVal(const Vals : array of TValue); virtual; abstract;
procedure EnterMethod(AClass : TClass; MethodAddress : Pointer; const Params : array of TValue); overload; virtual; abstract;
procedure EnterMethod(ARecord : PTypeInfo; MethodAddress : Pointer; const Params : array of TValue); overload; virtual; abstract;
procedure LeaveMethod(AClass : TClass; MethodAddress : Pointer); overload;
procedure LeaveMethod(AClass : TClass; MethodAddress : Pointer; AResult : TValue); overload; virtual; abstract;
procedure LeaveMethod(ARecord : PTypeInfo; MethodAddress : Pointer); overload;
procedure LeaveMethod(ARecord : PTypeInfo; MethodAddress : Pointer; AResult : TValue); overload; virtual; abstract;
procedure Log(Severity : TLogMsgSeverity; const Msg : String); overload; virtual; abstract;
procedure Log(Severity : TLogMsgSeverity; const Vals : array of const); overload; virtual; abstract;
procedure LogFmt(Severity : TLogMsgSeverity; const Msg : String; const Args : array of const); virtual; abstract;
procedure LogVal(Severity : TLogMsgSeverity; const Vals : array of TValue); virtual; abstract;
procedure Debug(const Msg : String); overload;
procedure Debug(const Vals : array of const); overload;
procedure DebugFmt(const Msg : String; const Args : array of const);
procedure DebugVal(const Vals : array of TValue);
procedure Info(const Msg : String); overload;
procedure Info(const Vals : array of const); overload;
procedure InfoFmt(const Msg : String; const Args : array of const);
procedure InfoVal(const Vals : array of TValue);
procedure Warning(const Msg : String); overload;
procedure Warning(const Vals : array of const); overload;
procedure WarningFmt(const Msg : String; const Args : array of const);
procedure WarningVal(const Vals : array of TValue);
procedure Error(const Msg : String); overload;
procedure Error(const Vals : array of const); overload;
procedure ErrorFmt(const Msg : String; const Args : array of const);
procedure ErrorVal(const Vals : array of TValue);
procedure Fatal(const Msg : String); overload;
procedure Fatal(const Vals : array of const); overload;
procedure FatalFmt(const Msg : String; const Args : array of const);
procedure FatalVal(const Vals : array of TValue);
property AllowedItems : TLogItems read GetAllowedItems write SetAllowedItems;
property Enabled : Boolean read GetEnabled;
property SeverityThreshold : TLogMsgSeverity read GetSeverityThreshold write SetSeverityThreshold;
end;
TBaseLogger = class abstract (TAbstractLogger, ILogger)
strict private
class var
FRttiCtx : TRttiContext;
strict protected
procedure IterateOutputs(const Action : TProc<ILogOutput>; CheckEnabled : Boolean); overload;
procedure IterateOutputs(const Action : TProc<ILogOutput>; ForItem : TLogItem); overload;
protected
procedure DoEnterSection(const Msg : String);
procedure DoLeaveSection(const Msg : String);
procedure DoEnterMethod(AType : TRttiType; AMethod : TRttiMethod; const Params : array of TValue);
procedure DoLeaveMethod(AType : TRttiType; AMethod : TRttiMethod; AResult : TValue);
procedure DoLog(Severity : TLogMsgSeverity; const Msg : String);
function FormatEnterMethod(AType : TRttiType; AMethod : TRttiMethod;
const Params : array of TValue) : String; virtual; abstract;
function FormatLeaveMethod(AType : TRttiType; AMethod : TRttiMethod;
AResult : TValue) : String; virtual; abstract;
function GetInstant : TLogTimestamp; virtual;
public
procedure EnterSection(const Msg : String = String.Empty); override;
procedure EnterSectionFmt(const Msg : String; const Args : array of const); override;
procedure LeaveSection(const Msg : String = String.Empty); override;
procedure LeaveSectionFmt(const Msg : String; const Args : array of const); override;
procedure EnterMethod(AClass : TClass; MethodAddress : Pointer; const Params : array of TValue); override;
procedure EnterMethod(ARecord : PTypeInfo; MethodAddress : Pointer; const Params : array of TValue); override;
procedure LeaveMethod(AClass : TClass; MethodAddress : Pointer; AResult : TValue); override;
procedure LeaveMethod(ARecord : PTypeInfo; MethodAddress : Pointer; AResult : TValue); override;
procedure Log(Severity : TLogMsgSeverity; const Msg : String); override;
procedure LogFmt(Severity : TLogMsgSeverity; const Msg : String; const Args : array of const); override;
end;
TLogger = class (TBaseLogger, ILogger)
private
function FormatMethod(AType : TRttiType; AMethod : TRttiMethod) : String;
protected
function FormatEnterMethod(AType : TRttiType; AMethod : TRttiMethod; const Params : array of TValue) : String; override;
function FormatLeaveMethod(AType : TRttiType; AMethod : TRttiMethod; AResult : TValue) : String; override;
public
procedure EnterSection(const Vals : array of const); override;
procedure EnterSectionVal(const Vals : array of TValue); override;
procedure LeaveSection(const Vals : array of const); override;
procedure LeaveSectionVal(const Vals : array of TValue); override;
procedure Log(Severity : TLogMsgSeverity; const Vals : array of const); override;
procedure LogVal(Severity : TLogMsgSeverity; const Vals : array of TValue); override;
end;
TLoggerList = class (TThreadList<ILogger>);
TMetaLogger = class (TInterfacedObject, IMetaLogger)
strict private
FLoggers : TLoggerList;
private
function GetEnabled : Boolean;
strict protected
procedure IterateLoggers(const Action : TProc<ILogger>);
procedure UnsafeCopyOpenArray<T>(const Source : array of T; var Dest : TArray<T>);
property Loggers : TLoggerList read FLoggers;
public
constructor Create; virtual;
destructor Destroy; override;
function AddLogger(const Logger : ILogger) : ILogger;
procedure EnterSection(const Msg : String = String.Empty); overload;
procedure EnterSection(const Vals : array of const); overload;
procedure EnterSectionFmt(const Msg : String; const Args : array of const);
procedure EnterSectionVal(const Vals : array of TValue);
procedure LeaveSection(const Msg : String = String.Empty); overload;
procedure LeaveSection(const Vals : array of const); overload;
procedure LeaveSectionFmt(const Msg : String; const Args : array of const);
procedure LeaveSectionVal(const Vals : array of TValue);
procedure EnterMethod(AClass : TClass; MethodAddress : Pointer; const Params : array of TValue); overload;
procedure EnterMethod(ARecord : PTypeInfo; MethodAddress : Pointer; const Params : array of TValue); overload;
procedure LeaveMethod(AClass : TClass; MethodAddress : Pointer); overload;
procedure LeaveMethod(AClass : TClass; MethodAddress : Pointer; AResult : TValue); overload;
procedure LeaveMethod(ARecord : PTypeInfo; MethodAddress : Pointer); overload;
procedure LeaveMethod(ARecord : PTypeInfo; MethodAddress : Pointer; AResult : TValue); overload;
procedure Log(Severity : TLogMsgSeverity; const Msg : String); overload;
procedure Log(Severity : TLogMsgSeverity; const Vals : array of const); overload;
procedure LogFmt(Severity : TLogMsgSeverity; const Msg : String; const Args : array of const);
procedure LogVal(Severity : TLogMsgSeverity; const Vals : array of TValue);
procedure Debug(const Msg : String); overload;
procedure Debug(const Vals : array of const); overload;
procedure DebugFmt(const Msg : String; const Args : array of const);
procedure DebugVal(const Vals : array of TValue);
procedure Info(const Msg : String); overload;
procedure Info(const Vals : array of const); overload;
procedure InfoFmt(const Msg : String; const Args : array of const);
procedure InfoVal(const Vals : array of TValue);
procedure Warning(const Msg : String); overload;
procedure Warning(const Vals : array of const); overload;
procedure WarningFmt(const Msg : String; const Args : array of const);
procedure WarningVal(const Vals : array of TValue);
procedure Error(const Msg : String); overload;
procedure Error(const Vals : array of const); overload;
procedure ErrorFmt(const Msg : String; const Args : array of const);
procedure ErrorVal(const Vals : array of TValue);
procedure Fatal(const Msg : String); overload;
procedure Fatal(const Vals : array of const); overload;
procedure FatalFmt(const Msg : String; const Args : array of const);
procedure FatalVal(const Vals : array of TValue);
property Enabled : Boolean read GetEnabled;
end;
TAbstractLogOutput = class abstract (TInterfacedObject, ILogOutput)
strict private
FSectionLevel : Integer;
FSeverityThreshold : TLogMsgSeverity;
private
function GetSeverityThreshold : TLogMsgSeverity;
procedure SetSeverityThreshold(Value : TLogMsgSeverity);
strict protected
procedure DoBeginSection(Instant : TLogTimestamp; const Msg : String); virtual; abstract;
procedure DoEndSection(Instant : TLogTimestamp; const Msg : String); virtual; abstract;
procedure DoWriteMessage(Instant : TLogTimestamp; Severity : TLogMsgSeverity; const Msg : String); virtual; abstract;
protected
function GetDefaultSeverityThreshold : TLogMsgSeverity; virtual;
property SectionLevel : Integer read FSectionLevel;
public
constructor Create; virtual;
procedure BeginSection(Instant : TLogTimestamp; const Msg : String);
procedure EndSection(Instant : TLogTimestamp; const Msg : String);
procedure WriteMessage(Instant : TLogTimestamp; Severity : TLogMsgSeverity; const Msg : String);
property SeverityThreshold : TLogMsgSeverity read GetSeverityThreshold write SetSeverityThreshold;
end;
TPlainTextOutput = class abstract (TAbstractLogOutput, ILogOutput)
strict private
FStringBuilder : TStringBuilder;
strict protected
procedure DoBeginSection(Instant : TLogTimestamp; const Msg : String); override;
procedure DoEndSection(Instant : TLogTimestamp; const Msg : String); override;
procedure DoWriteMessage(Instant : TLogTimestamp; Severity : TLogMsgSeverity; const Msg : String); override;
function AcquireBuilder(Capacity : Integer = 0) : TStringBuilder;
procedure ReleaseBuilder;
procedure WriteLine(const S : String); virtual; abstract;
protected
function FormatLogMessage(PreambleLength : Word; Severity : TLogMsgSeverity; const Msg : String) : String; virtual;
function FormatLogSectionBeginning(PreambleLength : Word; const Msg : String) : String; virtual;
function FormatLogSectionEnding(PreambleLength : Word; const Msg : String) : String; virtual;
function FormatCurrentThread : String; virtual;
function FormatPreamble(Instant : TLogTimestamp) : String; virtual;
function FormatSeverity(Severity : TLogMsgSeverity) : String; virtual;
function FormatTimestamp(Timestamp : TLogTimestamp) : String; virtual;
function GetPreambleCompensatorFiller : Char; virtual;
function GetSectionBeginningPrefix : String; virtual;
function GetSectionEndingPrefix : String; virtual;
function GetSectionIndentStr : String; virtual;
function GetSeverityDescriptions : TLogMsgTypeDescriptions; virtual;
function IndentText(const Text : String) : String; overload;
function IndentText(const Text, PaddingStr : String; LeftPadding : Word; ExceptFirstLine : Boolean) : String; overload;
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses
System.Classes, System.Math, System.DateUtils, System.StrUtils, System.Character,
FIToolkit.Commons.Utils,
FIToolkit.Logger.Utils, FIToolkit.Logger.Consts;
{ TAbstractLogger }
function TAbstractLogger.AddOutput(const LogOutput : ILogOutput) : ILogOutput;
begin
FOutputs.Add(LogOutput);
Result := LogOutput;
end;
constructor TAbstractLogger.Create;
begin
inherited Create;
FOutputs := TLogOutputList.Create;
FOutputs.Duplicates := dupIgnore;
FAllowedItems := GetDefaultAllowedItems;
FSeverityThreshold := GetDefaultSeverityThreshold;
end;
procedure TAbstractLogger.Debug(const Vals : array of const);
begin
Log(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmDebug], Vals);
end;
procedure TAbstractLogger.Debug(const Msg : String);
begin
Log(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmDebug], Msg);
end;
procedure TAbstractLogger.DebugFmt(const Msg : String; const Args : array of const);
begin
LogFmt(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmDebug], Msg, Args);
end;
procedure TAbstractLogger.DebugVal(const Vals : array of TValue);
begin
LogVal(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmDebug], Vals);
end;
destructor TAbstractLogger.Destroy;
begin
FreeAndNil(FOutputs);
inherited Destroy;
end;
procedure TAbstractLogger.Error(const Vals : array of const);
begin
Log(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmError], Vals);
end;
procedure TAbstractLogger.Error(const Msg : String);
begin
Log(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmError], Msg);
end;
procedure TAbstractLogger.ErrorFmt(const Msg : String; const Args : array of const);
begin
LogFmt(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmError], Msg, Args);
end;
procedure TAbstractLogger.ErrorVal(const Vals : array of TValue);
begin
LogVal(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmError], Vals);
end;
procedure TAbstractLogger.Fatal(const Msg : String);
begin
Log(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmFatal], Msg);
end;
procedure TAbstractLogger.Fatal(const Vals : array of const);
begin
Log(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmFatal], Vals);
end;
procedure TAbstractLogger.FatalFmt(const Msg : String; const Args : array of const);
begin
LogFmt(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmFatal], Msg, Args);
end;
procedure TAbstractLogger.FatalVal(const Vals : array of TValue);
begin
LogVal(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmFatal], Vals);
end;
function TAbstractLogger.GetAllowedItems : TLogItems;
begin
Result := FAllowedItems;
end;
function TAbstractLogger.GetDefaultAllowedItems : TLogItems;
begin
Result := [liMessage, liSection];
end;
function TAbstractLogger.GetDefaultSeverityThreshold : TLogMsgSeverity;
begin
Result := SEVERITY_MIN;
end;
function TAbstractLogger.GetEnabled : Boolean;
begin
Result := FSeverityThreshold <> SEVERITY_NONE;
end;
function TAbstractLogger.GetSeverityThreshold : TLogMsgSeverity;
begin
Result := FSeverityThreshold;
end;
procedure TAbstractLogger.Info(const Vals : array of const);
begin
Log(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmInfo], Vals);
end;
procedure TAbstractLogger.Info(const Msg : String);
begin
Log(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmInfo], Msg);
end;
procedure TAbstractLogger.InfoFmt(const Msg : String; const Args : array of const);
begin
LogFmt(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmInfo], Msg, Args);
end;
procedure TAbstractLogger.InfoVal(const Vals : array of TValue);
begin
LogVal(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmInfo], Vals);
end;
function TAbstractLogger.IsAllowedItem(Item : TLogItem) : Boolean;
begin
Result := Item in FAllowedItems;
end;
procedure TAbstractLogger.LeaveMethod(AClass : TClass; MethodAddress : Pointer);
begin
LeaveMethod(AClass, MethodAddress, TValue.Empty);
end;
procedure TAbstractLogger.LeaveMethod(ARecord : PTypeInfo; MethodAddress : Pointer);
begin
LeaveMethod(ARecord, MethodAddress, TValue.Empty);
end;
procedure TAbstractLogger.SetAllowedItems(Value : TLogItems);
begin
FAllowedItems := Value;
end;
procedure TAbstractLogger.SetSeverityThreshold(Value : TLogMsgSeverity);
begin
FSeverityThreshold := Value;
end;
procedure TAbstractLogger.Warning(const Vals : array of const);
begin
Log(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmWarning], Vals);
end;
procedure TAbstractLogger.Warning(const Msg : String);
begin
Log(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmWarning], Msg);
end;
procedure TAbstractLogger.WarningFmt(const Msg : String; const Args : array of const);
begin
LogFmt(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmWarning], Msg, Args);
end;
procedure TAbstractLogger.WarningVal(const Vals : array of TValue);
begin
LogVal(ARR_MSGTYPE_TO_MSGSEVERITY_MAPPING[lmWarning], Vals);
end;
{ TBaseLogger }
procedure TBaseLogger.DoEnterMethod(AType : TRttiType; AMethod : TRttiMethod; const Params : array of TValue);
var
tsInstant : TLogTimestamp;
sMsg : String;
begin
tsInstant := GetInstant;
sMsg := FormatEnterMethod(AType, AMethod, Params);
IterateOutputs(
procedure (Output : ILogOutput)
begin
Output.BeginSection(tsInstant, sMsg);
end,
liMethod
);
end;
procedure TBaseLogger.DoEnterSection(const Msg : String);
var
tsInstant : TLogTimestamp;
begin
tsInstant := GetInstant;
IterateOutputs(
procedure (Output : ILogOutput)
begin
Output.BeginSection(tsInstant, Msg);
end,
liSection
);
end;
procedure TBaseLogger.DoLeaveMethod(AType : TRttiType; AMethod : TRttiMethod; AResult : TValue);
var
tsInstant : TLogTimestamp;
sMsg : String;
begin
tsInstant := GetInstant;
sMsg := FormatLeaveMethod(AType, AMethod, AResult);
IterateOutputs(
procedure (Output : ILogOutput)
begin
Output.EndSection(tsInstant, sMsg);
end,
liMethod
);
end;
procedure TBaseLogger.DoLeaveSection(const Msg : String);
var
tsInstant : TLogTimestamp;
begin
tsInstant := GetInstant;
IterateOutputs(
procedure (Output : ILogOutput)
begin
Output.EndSection(tsInstant, Msg);
end,
liSection
);
end;
procedure TBaseLogger.DoLog(Severity : TLogMsgSeverity; const Msg : String);
var
tsInstant : TLogTimestamp;
begin
if Severity >= SeverityThreshold then
begin
tsInstant := GetInstant;
IterateOutputs(
procedure (Output : ILogOutput)
begin
if Severity >= Output.SeverityThreshold then
Output.WriteMessage(tsInstant, Severity, Msg);
end,
liMessage
);
end;
end;
procedure TBaseLogger.EnterMethod(AClass : TClass; MethodAddress : Pointer; const Params : array of TValue);
var
LType : TRttiType;
begin
LType := FRttiCtx.GetType(AClass);
DoEnterMethod(LType, LType.GetMethod(MethodAddress), Params);
end;
procedure TBaseLogger.EnterMethod(ARecord : PTypeInfo; MethodAddress : Pointer; const Params : array of TValue);
var
LType : TRttiType;
begin
LType := FRttiCtx.GetType(ARecord);
DoEnterMethod(LType, LType.GetMethod(MethodAddress), Params);
end;
procedure TBaseLogger.EnterSection(const Msg : String);
begin
DoEnterSection(Msg);
end;
procedure TBaseLogger.EnterSectionFmt(const Msg : String; const Args : array of const);
begin
EnterSection(Format(Msg, Args));
end;
function TBaseLogger.GetInstant : TLogTimestamp;
begin
Result := Now;
end;
procedure TBaseLogger.IterateOutputs(const Action : TProc<ILogOutput>; CheckEnabled : Boolean);
var
Output : ILogOutput;
begin
if not CheckEnabled or Enabled then
try
for Output in Outputs.LockList do
Action(Output);
finally
Outputs.UnlockList;
end;
end;
procedure TBaseLogger.IterateOutputs(const Action : TProc<ILogOutput>; ForItem : TLogItem);
begin
if IsAllowedItem(ForItem) then
IterateOutputs(Action, True);
end;
procedure TBaseLogger.LeaveMethod(AClass : TClass; MethodAddress : Pointer; AResult : TValue);
var
LType : TRttiType;
begin
LType := FRttiCtx.GetType(AClass);
DoLeaveMethod(LType, LType.GetMethod(MethodAddress), AResult);
end;
procedure TBaseLogger.LeaveMethod(ARecord : PTypeInfo; MethodAddress : Pointer; AResult : TValue);
var
LType : TRttiType;
begin
LType := FRttiCtx.GetType(ARecord);
DoLeaveMethod(LType, LType.GetMethod(MethodAddress), AResult);
end;
procedure TBaseLogger.LeaveSection(const Msg : String);
begin
DoLeaveSection(Msg);
end;
procedure TBaseLogger.LeaveSectionFmt(const Msg : String; const Args : array of const);
begin
LeaveSection(Format(Msg, Args));
end;
procedure TBaseLogger.Log(Severity : TLogMsgSeverity; const Msg : String);
begin
DoLog(Severity, Msg);
end;
procedure TBaseLogger.LogFmt(Severity : TLogMsgSeverity; const Msg : String; const Args : array of const);
begin
Log(Severity, Format(Msg, Args));
end;
{ TLogger }
procedure TLogger.EnterSection(const Vals : array of const);
begin
EnterSection(String.Join(String.Empty, ArrayOfConstToStringArray(Vals)));
end;
procedure TLogger.EnterSectionVal(const Vals : array of TValue);
begin
EnterSection(String.Join(String.Empty, TValueArrayToStringArray(Vals)));
end;
function TLogger.FormatEnterMethod(AType : TRttiType; AMethod : TRttiMethod; const Params : array of TValue) : String;
var
i : Integer;
P : TRttiParameter;
begin
Result := String.Empty;
if Assigned(AType) and Assigned(AMethod) then
begin
Result := FormatMethod(AType, AMethod);
if Length(Params) > 0 then
begin
i := 0;
for P in AMethod.GetParameters do
begin
if i > High(Params) then
Break
else
Result := Result + sLineBreak + P.Name + ' = ' + Params[i].ToString;
Inc(i);
end;
end;
end;
end;
function TLogger.FormatLeaveMethod(AType : TRttiType; AMethod : TRttiMethod; AResult : TValue) : String;
begin
Result := String.Empty;
if Assigned(AType) and Assigned(AMethod) then
begin
if Assigned(AMethod.ReturnType) then
Result := 'Result = ' + AResult.ToString + sLineBreak;
Result := Result + FormatMethod(AType, AMethod);
end;
end;
function TLogger.FormatMethod(AType : TRttiType; AMethod : TRttiMethod) : String;
begin
Result := AType.GetFullName + ' :: ' + AMethod.ToString;
end;
procedure TLogger.LeaveSection(const Vals : array of const);
begin
LeaveSection(String.Join(String.Empty, ArrayOfConstToStringArray(Vals)));
end;
procedure TLogger.LeaveSectionVal(const Vals : array of TValue);
begin
LeaveSection(String.Join(String.Empty, TValueArrayToStringArray(Vals)));
end;
procedure TLogger.Log(Severity : TLogMsgSeverity; const Vals : array of const);
begin
Log(Severity, String.Join(String.Empty, ArrayOfConstToStringArray(Vals)));
end;
procedure TLogger.LogVal(Severity : TLogMsgSeverity; const Vals : array of TValue);
begin
Log(Severity, String.Join(String.Empty, TValueArrayToStringArray(Vals)));
end;
{ TMetaLogger }
function TMetaLogger.AddLogger(const Logger : ILogger) : ILogger;
begin
FLoggers.Add(Logger);
Result := Logger;
end;
constructor TMetaLogger.Create;
begin
inherited Create;
FLoggers := TLoggerList.Create;
FLoggers.Duplicates := dupIgnore;
end;
procedure TMetaLogger.Debug(const Vals : array of const);
var
LVals : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Debug(LVals);
end
);
end;
procedure TMetaLogger.Debug(const Msg : String);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Debug(Msg);
end
);
end;
procedure TMetaLogger.DebugFmt(const Msg : String; const Args : array of const);
var
LArgs : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Args, LArgs);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.DebugFmt(Msg, LArgs);
end
);
end;
procedure TMetaLogger.DebugVal(const Vals : array of TValue);
var
LVals : TArray<TValue>;
begin
UnsafeCopyOpenArray<TValue>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.DebugVal(LVals);
end
);
end;
destructor TMetaLogger.Destroy;
begin
FreeAndNil(FLoggers);
inherited Destroy;
end;
procedure TMetaLogger.EnterMethod(AClass : TClass; MethodAddress : Pointer; const Params : array of TValue);
var
LParams : TArray<TValue>;
begin
UnsafeCopyOpenArray<TValue>(Params, LParams);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.EnterMethod(AClass, MethodAddress, LParams);
end
);
end;
procedure TMetaLogger.EnterMethod(ARecord : PTypeInfo; MethodAddress : Pointer; const Params : array of TValue);
var
LParams : TArray<TValue>;
begin
UnsafeCopyOpenArray<TValue>(Params, LParams);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.EnterMethod(ARecord, MethodAddress, LParams);
end
);
end;
procedure TMetaLogger.EnterSection(const Msg : String);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.EnterSection(Msg);
end
);
end;
procedure TMetaLogger.EnterSection(const Vals : array of const);
var
LVals : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.EnterSection(LVals);
end
);
end;
procedure TMetaLogger.EnterSectionFmt(const Msg : String; const Args : array of const);
var
LArgs : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Args, LArgs);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.EnterSectionFmt(Msg, LArgs);
end
);
end;
procedure TMetaLogger.EnterSectionVal(const Vals : array of TValue);
var
LVals : TArray<TValue>;
begin
UnsafeCopyOpenArray<TValue>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.EnterSectionVal(LVals);
end
);
end;
procedure TMetaLogger.Error(const Msg : String);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Error(Msg);
end
);
end;
procedure TMetaLogger.Error(const Vals : array of const);
var
LVals : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Error(LVals);
end
);
end;
procedure TMetaLogger.ErrorFmt(const Msg : String; const Args : array of const);
var
LArgs : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Args, LArgs);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.ErrorFmt(Msg, LArgs);
end
);
end;
procedure TMetaLogger.ErrorVal(const Vals : array of TValue);
var
LVals : TArray<TValue>;
begin
UnsafeCopyOpenArray<TValue>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.ErrorVal(LVals);
end
);
end;
procedure TMetaLogger.Fatal(const Vals : array of const);
var
LVals : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Fatal(LVals);
end
);
end;
procedure TMetaLogger.Fatal(const Msg : String);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Fatal(Msg);
end
);
end;
procedure TMetaLogger.FatalFmt(const Msg : String; const Args : array of const);
var
LArgs : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Args, LArgs);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.FatalFmt(Msg, LArgs);
end
);
end;
procedure TMetaLogger.FatalVal(const Vals : array of TValue);
var
LVals : TArray<TValue>;
begin
UnsafeCopyOpenArray<TValue>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.FatalVal(LVals);
end
);
end;
function TMetaLogger.GetEnabled : Boolean;
var
Logger : ILogger;
begin
Result := False;
try
for Logger in Loggers.LockList do
if Logger.Enabled then
Exit(True);
finally
Loggers.UnlockList;
end;
end;
procedure TMetaLogger.Info(const Msg : String);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Info(Msg);
end
);
end;
procedure TMetaLogger.Info(const Vals : array of const);
var
LVals : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Info(LVals);
end
);
end;
procedure TMetaLogger.InfoFmt(const Msg : String; const Args : array of const);
var
LArgs : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Args, LArgs);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.InfoFmt(Msg, LArgs);
end
);
end;
procedure TMetaLogger.InfoVal(const Vals : array of TValue);
var
LVals : TArray<TValue>;
begin
UnsafeCopyOpenArray<TValue>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.InfoVal(LVals);
end
);
end;
procedure TMetaLogger.IterateLoggers(const Action : TProc<ILogger>);
var
Logger : ILogger;
begin
try
for Logger in Loggers.LockList do
Action(Logger);
finally
Loggers.UnlockList;
end;
end;
procedure TMetaLogger.LeaveMethod(AClass : TClass; MethodAddress : Pointer);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.LeaveMethod(AClass, MethodAddress);
end
);
end;
procedure TMetaLogger.LeaveMethod(AClass : TClass; MethodAddress : Pointer; AResult : TValue);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.LeaveMethod(AClass, MethodAddress, AResult);
end
);
end;
procedure TMetaLogger.LeaveMethod(ARecord : PTypeInfo; MethodAddress : Pointer);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.LeaveMethod(ARecord, MethodAddress);
end
);
end;
procedure TMetaLogger.LeaveMethod(ARecord : PTypeInfo; MethodAddress : Pointer; AResult : TValue);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.LeaveMethod(ARecord, MethodAddress, AResult);
end
);
end;
procedure TMetaLogger.LeaveSection(const Vals : array of const);
var
LVals : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.LeaveSection(LVals);
end
);
end;
procedure TMetaLogger.LeaveSection(const Msg : String);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.LeaveSection(Msg);
end
);
end;
procedure TMetaLogger.LeaveSectionFmt(const Msg : String; const Args : array of const);
var
LArgs : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Args, LArgs);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.LeaveSectionFmt(Msg, LArgs);
end
);
end;
procedure TMetaLogger.LeaveSectionVal(const Vals : array of TValue);
var
LVals : TArray<TValue>;
begin
UnsafeCopyOpenArray<TValue>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.LeaveSectionVal(LVals);
end
);
end;
procedure TMetaLogger.Log(Severity : TLogMsgSeverity; const Msg : String);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Log(Severity, Msg);
end
);
end;
procedure TMetaLogger.Log(Severity : TLogMsgSeverity; const Vals : array of const);
var
LVals : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Log(Severity, LVals);
end
);
end;
procedure TMetaLogger.LogFmt(Severity : TLogMsgSeverity; const Msg : String; const Args : array of const);
var
LArgs : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Args, LArgs);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.LogFmt(Severity, Msg, LArgs);
end
);
end;
procedure TMetaLogger.LogVal(Severity : TLogMsgSeverity; const Vals : array of TValue);
var
LVals : TArray<TValue>;
begin
UnsafeCopyOpenArray<TValue>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.LogVal(Severity, LVals);
end
);
end;
procedure TMetaLogger.UnsafeCopyOpenArray<T>(const Source : array of T; var Dest : TArray<T>);
var
i : Integer;
begin
SetLength(Dest, Length(Source));
for i := 0 to High(Source) do
Dest[i] := Source[i];
end;
procedure TMetaLogger.Warning(const Vals : array of const);
var
LVals : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Warning(LVals);
end
);
end;
procedure TMetaLogger.Warning(const Msg : String);
begin
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.Warning(Msg);
end
);
end;
procedure TMetaLogger.WarningFmt(const Msg : String; const Args : array of const);
var
LArgs : TArray<TVarRec>;
begin
UnsafeCopyOpenArray<TVarRec>(Args, LArgs);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.WarningFmt(Msg, LArgs);
end
);
end;
procedure TMetaLogger.WarningVal(const Vals : array of TValue);
var
LVals : TArray<TValue>;
begin
UnsafeCopyOpenArray<TValue>(Vals, LVals);
IterateLoggers(
procedure (Logger : ILogger)
begin
Logger.WarningVal(LVals);
end
);
end;
{ TAbstractLogOutput }
procedure TAbstractLogOutput.BeginSection(Instant : TLogTimestamp; const Msg : String);
begin
if FSectionLevel >= 0 then
begin
DoBeginSection(Instant, Msg);
Inc(FSectionLevel);
end;
end;
constructor TAbstractLogOutput.Create;
begin
inherited Create;
FSeverityThreshold := GetDefaultSeverityThreshold;
end;
procedure TAbstractLogOutput.EndSection(Instant : TLogTimestamp; const Msg : String);
begin
if FSectionLevel > 0 then
begin
Dec(FSectionLevel);
DoEndSection(Instant, Msg);
end;
end;
function TAbstractLogOutput.GetDefaultSeverityThreshold : TLogMsgSeverity;
begin
Result := SEVERITY_MIN;
end;
function TAbstractLogOutput.GetSeverityThreshold : TLogMsgSeverity;
begin
Result := FSeverityThreshold;
end;
procedure TAbstractLogOutput.SetSeverityThreshold(Value : TLogMsgSeverity);
begin
FSeverityThreshold := Value;
end;
procedure TAbstractLogOutput.WriteMessage(Instant : TLogTimestamp; Severity : TLogMsgSeverity; const Msg : String);
begin
if (FSeverityThreshold <> SEVERITY_NONE) and (Severity >= FSeverityThreshold) then
DoWriteMessage(Instant, Severity, Msg);
end;
{ TPlainTextOutput }
function TPlainTextOutput.AcquireBuilder(Capacity : Integer) : TStringBuilder;
begin
TMonitor.Enter(FStringBuilder);
FStringBuilder.Clear;
if Capacity > 0 then
FStringBuilder.Capacity := Capacity;
Result := FStringBuilder;
end;
constructor TPlainTextOutput.Create;
begin
inherited Create;
FStringBuilder := TStringBuilder.Create;
end;
destructor TPlainTextOutput.Destroy;
begin
FreeAndNil(FStringBuilder);
inherited Destroy;
end;
procedure TPlainTextOutput.DoBeginSection(Instant : TLogTimestamp; const Msg : String);
var
sPreamble : String;
begin
sPreamble := FormatPreamble(Instant);
WriteLine(sPreamble + FormatLogSectionBeginning(sPreamble.Length, Msg));
end;
procedure TPlainTextOutput.DoEndSection(Instant : TLogTimestamp; const Msg : String);
var
sPreamble : String;
begin
sPreamble := FormatPreamble(Instant);
WriteLine(sPreamble + FormatLogSectionEnding(sPreamble.Length, Msg));
end;
procedure TPlainTextOutput.DoWriteMessage(Instant : TLogTimestamp; Severity : TLogMsgSeverity; const Msg : String);
var
sPreamble : String;
begin
sPreamble := FormatPreamble(Instant);
WriteLine(sPreamble + FormatLogMessage(sPreamble.Length, Severity, Msg));
end;
function TPlainTextOutput.FormatCurrentThread : String;
var
iResultWidth : Integer;
begin
if TThread.Current.ThreadID = MainThreadID then
Result := RSPTOMainThreadName
else
Result := TThread.Current.ThreadID.ToString;
iResultWidth := Max(RSPTOMainThreadName.Length, High(TThreadID).ToString.Length);
Result := Result.PadLeft(iResultWidth div 2 + Result.Length div 2).PadRight(iResultWidth);
end;
function TPlainTextOutput.FormatLogMessage(PreambleLength : Word; Severity : TLogMsgSeverity; const Msg : String) : String;
var
sSeverity : String;
cFiller : Char;
begin
sSeverity := FormatSeverity(Severity);
Result := sSeverity + IndentText(Msg);
cFiller := GetPreambleCompensatorFiller;
if not cFiller.IsControl then
Result := IndentText(Result, cFiller, PreambleLength + sSeverity.Length, True);
end;
function TPlainTextOutput.FormatLogSectionBeginning(PreambleLength : Word; const Msg : String) : String;
var
sPrefix : String;
cFiller : Char;
begin
sPrefix := GetSectionBeginningPrefix;
Result := sPrefix + IndentText(Msg);
cFiller := GetPreambleCompensatorFiller;
if not cFiller.IsControl then
Result := IndentText(Result, cFiller, PreambleLength + sPrefix.Length, True);
end;
function TPlainTextOutput.FormatLogSectionEnding(PreambleLength : Word; const Msg : String) : String;
var
sPrefix : String;
cFiller : Char;
begin
sPrefix := GetSectionEndingPrefix;
Result := sPrefix + IndentText(Msg);
cFiller := GetPreambleCompensatorFiller;
if not cFiller.IsControl then
Result := IndentText(Result, cFiller, PreambleLength + sPrefix.Length, True);
end;
function TPlainTextOutput.FormatPreamble(Instant : TLogTimestamp) : String;
begin
Result := Format('[%s] {%s} ', [FormatTimestamp(Instant), FormatCurrentThread]);
end;
function TPlainTextOutput.FormatSeverity(Severity : TLogMsgSeverity) : String;
begin
Result := GetSeverityDescriptions[InferLogMsgType(Severity)];
end;
function TPlainTextOutput.FormatTimestamp(Timestamp : TLogTimestamp) : String;
begin
Result := Format('%s.%.3d', [DateTimeToStr(Timestamp), MilliSecondOfTheSecond(Timestamp)]);
end;
function TPlainTextOutput.GetPreambleCompensatorFiller : Char;
begin
Result := CHR_PTO_PREAMBLE_COMPENSATOR_FILLER;
end;
function TPlainTextOutput.GetSectionBeginningPrefix : String;
begin
Result := RSPTOSectionBeginningPrefix.PadRight(GetSeverityDescriptions.MaxItemLength);
end;
function TPlainTextOutput.GetSectionEndingPrefix : String;
begin
Result := RSPTOSectionEndingPrefix.PadRight(GetSeverityDescriptions.MaxItemLength);
end;
function TPlainTextOutput.GetSectionIndentStr : String;
begin
Result := RSPTOSectionIndentStr;
end;
function TPlainTextOutput.GetSeverityDescriptions : TLogMsgTypeDescriptions;
begin
Result := TLogMsgTypeDescriptions.Create([
TLogMsgTypeDescription.Create(lmDebug, RSPTOMsgTypeDescDebug),
TLogMsgTypeDescription.Create(lmInfo, RSPTOMsgTypeDescInfo),
TLogMsgTypeDescription.Create(lmWarning, RSPTOMsgTypeDescWarning),
TLogMsgTypeDescription.Create(lmError, RSPTOMsgTypeDescError),
TLogMsgTypeDescription.Create(lmFatal, RSPTOMsgTypeDescFatal),
TLogMsgTypeDescription.Create(lmExtreme, RSPTOMsgTypeDescExtreme)
]);
end;
function TPlainTextOutput.IndentText(const Text : String) : String;
begin
Result := IndentText(Text, GetSectionIndentStr, SectionLevel, False);
end;
function TPlainTextOutput.IndentText(const Text, PaddingStr : String; LeftPadding : Word;
ExceptFirstLine : Boolean) : String;
var
arrText : TArray<String>;
i : Integer;
begin
arrText := Text.Split([sLineBreak], TStringSplitOptions.None);
{$IF CompilerVersion < 33.0} // RSP-11302
if Text.EndsWith(sLineBreak) then
arrText := arrText + [String.Empty];
{$ENDIF}
with AcquireBuilder(Length(Text) + Length(PaddingStr) * LeftPadding * Max(Length(arrText), 1)) do
try
for i := 0 to High(arrText) do
begin
if (i = 0) and ExceptFirstLine then
Append(arrText[i])
else
Append(DupeString(PaddingStr, LeftPadding)).Append(arrText[i]);
if i < High(arrText) then
AppendLine;
end;
Result := ToString;
finally
ReleaseBuilder;
end;
end;
procedure TPlainTextOutput.ReleaseBuilder;
begin
FStringBuilder.Clear;
TMonitor.Exit(FStringBuilder);
end;
end.
|
unit xVectorLine;
interface
uses Classes, SysUtils, Math, System.Types, System.UITypes, FMX.Controls,
FMX.StdCtrls, FMX.Objects, FMX.Graphics, xVectorType, FMX.Types;
type
/// <summary>
/// 向量信息
/// </summary>
TVectorLineInfo = class
private
FVAngle: Double;
FVID: Integer;
FVValue: Double;
FVType: tTVectorType;
FIsSelected: Boolean;
FVColor: TAlphaColor;
FOnChange: TNotifyEvent;
FCenterPoint: TPointF;
FScale: Double;
FVName: string;
FCanvas: TControl;
FIsDrawPoint: Boolean;
FIsMainSelect: Boolean;
FIsOver: Boolean;
FVMaxWidth: Single;
FLine, FLineCapTop, FLineCapBottom : TLine;
FText: TText;
FCircle : TCircle;
FOnDblClick: TNotifyEvent;
FIsCanSelect: Boolean;
FVDash: TStrokeDash;
FVMaxValue: Single;
FOnMouseDown: TMouseEvent;
procedure SetIsSelected(const Value: Boolean);
function GetVTypeStr: string;
procedure SetVTypeStr(const Value: string);
procedure SetVAngle(const Value: Double);
procedure MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
procedure MouseLeave(Sender: TObject);
procedure DblClick(Sender: TObject);
procedure MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
/// <summary>
/// 基本定压电流值
/// </summary>
function GetBaseValue : Single;
/// <summary>
/// 获取向量图颜色
/// </summary>
function GetVectorColor: TAlphaColor;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TVectorLineInfo);
/// <summary>
/// 向量最大值
/// </summary>
property VMaxValue : Single read FVMaxValue write FVMaxValue;
/// <summary>
/// 向量ID
/// </summary>
property VID : Integer read FVID write FVID;
/// <summary>
/// 向量名称
/// </summary>
property VName : string read FVName write FVName;
/// <summary>
/// 向量类型
/// </summary>
property VType : tTVectorType read FVType write FVType;
/// <summary>
/// 向量类型 字符串形式
/// </summary>
property VTypeStr : string read GetVTypeStr write SetVTypeStr;
/// <summary>
/// 向量颜色
/// </summary>
property VColor : TAlphaColor read FVColor write FVColor;
/// <summary>
/// 画笔类型
/// </summary>
property VDash: TStrokeDash read FVDash write FVDash;
/// <summary>
/// 向量值 填写电压电流值
/// </summary>
property VValue : Double read FVValue write FVValue;
/// <summary>
/// 向量满量程长度
/// </summary>
property VMaxWidth : Single read FVMaxWidth write FVMaxWidth;
/// <summary>
/// 角度 原点水平向右为零度,上移为正角度
/// </summary>
property VAngle : Double read FVAngle write SetVAngle;
/// <summary>
/// 是否被选中
/// </summary>
property IsSelected : Boolean read FIsSelected write SetIsSelected;
/// <summary>
/// 是否选择的是主向量
/// </summary>
property IsMainSelect : Boolean read FIsMainSelect write FIsMainSelect;
/// <summary>
/// 鼠标是否在上面
/// </summary>
property IsOver : Boolean read FIsOver write FIsOver;
/// <summary>
/// 改变事件
/// </summary>
property OnChange : TNotifyEvent read FOnChange write FOnChange;
/// <summary>
/// 原点
/// </summary>
property CenterPoint : TPointF read FCenterPoint write FCenterPoint;
/// <summary>
/// 画布
/// </summary>
property Canvas : TControl read FCanvas write FCanvas;
/// <summary>
/// 是否画点
/// </summary>
property IsDrawPoint : Boolean read FIsDrawPoint write FIsDrawPoint;
/// <summary>
/// 画图
/// </summary>
procedure Draw;
/// <summary>
/// 双击事件
/// </summary>
property OnDblClick : TNotifyEvent read FOnDblClick write FOnDblClick;
/// <summary>
/// 鼠标按下事件
/// </summary>
property OnMouseDown : TMouseEvent read FOnMouseDown write FOnMouseDown;
/// <summary>
/// 是否允许选择 默认 允许
/// </summary>
property IsCanSelect : Boolean read FIsCanSelect write FIsCanSelect;
end;
implementation
{ TVectorLineInfo }
procedure TVectorLineInfo.Assign(Source: TVectorLineInfo);
begin
if Assigned(Source) then
begin
FVName := Source.VName ;
FVType := Source.VType ;
FVColor := Source.VColor ;
FVValue := Source.VValue ;
FVAngle := Source.VAngle ;
FIsDrawPoint := Source.IsDrawPoint;
end;
end;
constructor TVectorLineInfo.Create;
begin
FCenterPoint := Point(0, 0);
FVColor := TAlphaColorRec.Red;
FVValue := 220;
FVAngle := 90;
FVName := '未命名';
FVType := vtVol;
FScale := 1;
FIsDrawPoint := True;
FIsSelected := False;
FIsMainSelect := False;
FIsOver := False;
FVMaxWidth := 200;
FIsCanSelect := True;
FVDash := TStrokeDash.Solid;
FVMaxValue := 220;
end;
procedure TVectorLineInfo.DblClick(Sender: TObject);
begin
if Assigned(FOnDblClick) then
begin
FOnDblClick(Self);
end;
end;
destructor TVectorLineInfo.Destroy;
begin
if Assigned(FLineCapTop) then
FLineCapTop.Free;
if Assigned(FLineCapBottom) then
FLineCapBottom.Free;
if Assigned(FCircle) then
FCircle.Free;
if Assigned(FText) then
FText.Free;
if Assigned(FLine) then
FLine.Free;
inherited;
end;
procedure TVectorLineInfo.Draw;
var
dWidth : Single;
procedure CreatLine(AParent : TControl; var ALine : TLine);
begin
if not Assigned(ALine) then
ALine := TLine.Create(AParent);
ALine.Parent := AParent;
ALine.LineType := TLineType.Top;
ALine.OnMouseMove := MouseMove;
ALine.OnMouseLeave := MouseLeave;
ALine.OnDblClick := DblClick;
ALine.OnMouseDown := MouseDown;
ALine.Height := dWidth+3;
ALine.Stroke.Thickness := dWidth;
ALine.Stroke.Color := GetVectorColor;
if FIsCanSelect then
ALine.Cursor := crHandPoint
else
ALine.Cursor := crDefault;
ALine.Stroke.Dash := FVDash;
end;
begin
dWidth := 2;
// 向量线
CreatLine(FCanvas, FLine);
FLine.Position.X := FCenterPoint.X;
FLine.Position.Y := FCenterPoint.Y;
FLine.Width := FVMaxWidth * FVValue/GetBaseValue;
FLine.RotationCenter.X := 0;
FLine.RotationCenter.Y := 0;
FLine.RotationAngle := - FVAngle;
FLine.BringToFront;
// 上箭头
CreatLine(FLine, FLineCapTop);
FLineCapTop.Position.X := FLine.Width-1;
FLineCapTop.Position.Y := 1;
FLineCapTop.Width := FVMaxWidth/20+1;
FLineCapTop.RotationCenter.X := 0;
FLineCapTop.RotationCenter.Y := 0;
FLineCapTop.RotationAngle := -140;
// 下箭头
CreatLine(FLine, FLineCapBottom);
FLineCapBottom.Position.X := FLine.Width-1;
FLineCapBottom.Position.Y := 1;
FLineCapBottom.Width := FVMaxWidth/20;
FLineCapBottom.RotationCenter.X := 0;
FLineCapBottom.RotationCenter.Y := 0;
FLineCapBottom.RotationAngle := 140;
FLineCapBottom.Stroke.Thickness := dWidth;
// 向量描述
if not Assigned(FText) then
FText:= TText.Create(FLine);
FText.Parent := FLine;
FText.Text := FVName;
FText.Width := Length(FVName) * FText.Font.Size;
FText.Height := 15;
FText.Position.X := FLine.Width;
FText.Position.Y := 1- FText.Width/2;
FText.Color := GetVectorColor;
FText.Font.Family := 'Times New Roman';
FText.Font.Style := [TFontStyle.fsItalic];
FText.RotationAngle := -FLine.RotationAngle;
if FIsDrawPoint then
begin
if not Assigned(FCircle) then
FCircle := TCircle.Create(FText);
FCircle.Parent := FText;
FCircle.Width := 2;
FCircle.Height := 2;
FCircle.Position.X := 5.5*Length(FVName);
FCircle.Position.y := -3;
FCircle.Stroke.Color := GetVectorColor;
end;
end;
function TVectorLineInfo.GetBaseValue: Single;
begin
Result := FVMaxValue;
end;
function TVectorLineInfo.GetVectorColor: TAlphaColor;
begin
if FIsSelected then
begin
if FIsMainSelect then
begin
Result := C_COLOR_SELECT_MAIN;
end
else
begin
Result := C_COLOR_SELECT;
end;
end
else
begin
Result := FVColor;
end;
end;
function TVectorLineInfo.GetVTypeStr: string;
begin
Result := GetVTStr(FVType);
end;
procedure TVectorLineInfo.MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
if Assigned(FOnMouseDown) then
begin
FOnMouseDown(Self, Button, Shift, X, Y);
end;
end;
procedure TVectorLineInfo.MouseLeave(Sender: TObject);
begin
if FIsCanSelect then
begin
FLine.Stroke.Color := GetVectorColor;
FLineCapTop.Stroke.Color := GetVectorColor;
FLineCapBottom.Stroke.Color := GetVectorColor;
FText.Color := GetVectorColor;
if FIsDrawPoint then
FCircle.Stroke.Color := GetVectorColor;
end;
end;
procedure TVectorLineInfo.MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
//var
// dX, dY : Single;
// dValue : Double;
var
AColor : TAlphaColor;
begin
if FIsCanSelect then
begin
if FIsMainSelect then
begin
AColor := C_COLOR_SELECT_MAIN;
end
else
begin
AColor := C_COLOR_SELECT;
end;
FLine.Stroke.Color := AColor;
FLineCapTop.Stroke.Color := AColor;
FLineCapBottom.Stroke.Color := AColor;
FText.Color := AColor;
if FIsDrawPoint then
FCircle.Stroke.Color := AColor;
// if (ssLeft in Shift) and FIsMainSelect then
// begin
//
// dX := X;
// dY := Y-3;
// if Abs(dY) >=0.3 then
// begin
// if dX = 0 then
// dValue := 0
// else
// dValue := dY/dX;
//
// FVAngle := FVAngle - RadToDeg(ArcTan(dValue));
//
// FLine.RotationAngle := - FVAngle;
// sTemp := FormatFloat('0',x) + ',' + FormatFloat('0',y);
// end;
// end;
end;
end;
procedure TVectorLineInfo.SetIsSelected(const Value: Boolean);
begin
FIsSelected := Value;
end;
procedure TVectorLineInfo.SetVAngle(const Value: Double);
function SetValue(dValue : Double) : Double;
begin
if dValue < 0 then
begin
Result := dValue + 360;
if Result < 0 then
Result := SetValue(Result);
end
else
Result := dValue;
end;
function SetValue1(dValue : Double) : Double;
begin
if dValue > 360 then
begin
Result := dValue - 360;
if Result > 360 then
Result := SetValue1(Result)
end
else
Result := dValue;
end;
begin
if Value < 0 then
begin
FVAngle := SetValue(Value);
end
else if Value > 360 then
begin
FVAngle := SetValue1(Value);
end
else
begin
FVAngle := Value;
end;
end;
procedure TVectorLineInfo.SetVTypeStr(const Value: string);
begin
FVType := SetVTType(Value);
end;
end.
|
unit rhlRadioGatun64;
interface
uses
rhlCore;
type
{ TrhlRadioGatun64 }
TrhlRadioGatun64 = class(TrhlHash)
private
const
MILL_SIZE = 19;
BELT_WIDTH = 3;
BELT_LENGTH = 13;
NUMBER_OF_BLANK_ITERATIONS = 16;
var
m_mill: array[0..MILL_SIZE - 1] of QWord;
m_belt: array[0..BELT_LENGTH - 1, 0..BELT_WIDTH - 1] of QWord;
procedure RoundFunction;
protected
procedure UpdateBlock(const AData); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlRadioGatun64 }
procedure TrhlRadioGatun64.RoundFunction;
var
i: Integer;
q: array[0..BELT_WIDTH - 1] of QWord;
a: array[0..MILL_SIZE - 1] of QWord;
begin
Move(m_belt[BELT_LENGTH - 1], q, SizeOf(q));
for i := BELT_LENGTH - 1 downto 0 do
Move(m_belt[i - 1], m_belt[i], SizeOf(q));
Move(q, m_belt[0], SizeOf(q));
for i := 0 to 11 do
m_belt[i + 1][i mod BELT_WIDTH] := m_belt[i + 1][i mod BELT_WIDTH] xor m_mill[i + 1];
for i := 0 to MILL_SIZE - 1 do
a[i] := m_mill[i] xor (m_mill[(i + 1) mod MILL_SIZE] or not m_mill[(i + 2) mod MILL_SIZE]);
for i := 0 to MILL_SIZE - 1 do
m_mill[i] := RorQWord(a[(7 * i) mod MILL_SIZE], i * (i + 1) div 2);
for i := 0 to MILL_SIZE - 1 do
a[i] := m_mill[i] xor m_mill[(i + 1) mod MILL_SIZE] xor m_mill[(i + 4) mod MILL_SIZE];
a[0] := a[0] xor 1;
for i := 0 to MILL_SIZE - 1 do
m_mill[i] := a[i];
for i := 0 to BELT_WIDTH - 1 do
m_mill[i + 13] := m_mill[i + 13] xor q[i];
end;
procedure TrhlRadioGatun64.UpdateBlock(const AData);
var
data: array[0..0] of QWord absolute AData;
i: Integer;
begin
for i := 0 to BELT_WIDTH - 1 do
begin
m_mill[i + 16] := m_mill[i + 16] xor data[i];
m_belt[0][i] := m_belt[0][i] xor data[i];
end;
RoundFunction();
end;
constructor TrhlRadioGatun64.Create;
begin
HashSize := 32;
BlockSize := 8 * BELT_WIDTH;
end;
procedure TrhlRadioGatun64.Init;
begin
inherited Init;
FillChar(m_mill, SizeOf(m_mill), 0);
FillChar(m_belt, SizeOf(m_belt), 0);
end;
procedure TrhlRadioGatun64.Final(var ADigest);
var
padding_size: DWord;
pad: TBytes;
i: Integer;
begin
padding_size := BlockSize - (FProcessedBytes mod BlockSize);
SetLength(pad, padding_size);
pad[0] := $01;
UpdateBytes(pad[0], padding_size);
for i := 0 to NUMBER_OF_BLANK_ITERATIONS - 1 do
RoundFunction;
SetLength(pad, HashSize);
for i := 0 to (HashSize div 16) - 1 do
begin
RoundFunction();
Move(m_mill[1], pad[i * 16], 16);
end;
Move(pad[0], ADigest, HashSize);
end;
end.
|
unit UTXTCliente;
interface
uses Classes, Contnrs, SysUtils, StrUtils;
type
TClienteModel = class
private
fVersao : String;
fTpDoc : String;
fNumDoc : String;
fxNome : String;
fIE : String;
fISUF : String;
fxLogr : String;
fNro : String;
fxCpl : String;
fxBairro: String;
fcMun : String;
fxMun : String;
fUF : String;
fCEP : String;
fcPais : String;
fxPais : String;
fFone : String;
published
property versao : String read fVersao write fVersao;
property TpDoc : String read fTpDoc write fTpDoc;
property NumDoc : String read fNumDoc write fNumDoc;
property xNome : String read fxNome write fxNome;
property IE : String read fIE write fIE;
property ISUF : String read fISUF write fISUF;
property xLogr : String read fxLogr write fxLogr;
property Nro : String read fNro write fNro;
property xCpl : String read fxCpl write fxCpl;
property xBairro: String read fxBairro write fxBairro;
property cMun : String read fcMun write fcMun;
property xMun : String read fxMun write fxMun;
property UF : String read fUF write fUF;
property CEP : String read fCEP write fCEP;
property cPais : String read fcPais write fcPais;
property xPais : String read fxPais write fxPais;
property Fone : String read fFone write fFone;
end;
TListadeClientes = class(TObjectList)
protected
procedure SetObject (Index: Integer; Item: TClienteModel);
function GetObject (Index: Integer): TClienteModel;
procedure Insert (Index: Integer; Obj: TClienteModel);
public
function Add (Obj: TClienteModel): Integer;
property Objects [Index: Integer]: TClienteModel
read GetObject write SetObject; default;
end;
TImportaCliente = class
private
fArquivo : String;
fErros : TStringList;
fClientes : TListadeClientes;
fQtReg : Integer;
fQtImp : Integer;
procedure StringToArray(St: string; Separador: char; Lista: TStringList);
public
constructor create;
destructor destroy;override;
procedure importa;
published
property Arquivo : String read fArquivo write fArquivo;
property Erros : TStringList read fErros write fErros;
property Clientes: TListadeClientes read fClientes write fClientes;
property qtReg : Integer read fQtReg;
property qtImp : Integer read fQtImp;
end;
implementation
{ TImportaCliente }
constructor TImportaCliente.create;
begin
fErros := TStringList.Create;
fClientes := TListadeClientes.Create(True);
end;
destructor TImportaCliente.destroy;
begin
FreeAndNil(fErros);
FreeAndNil(fClientes);
inherited;
end;
procedure TImportaCliente.importa;
var
conteudoArquivo : TStringList;
linha : TStringList;
cliente : TClienteModel;
i : Integer;
begin
if not FileExists(Arquivo) then
begin
Erros.Add('Arquivo '+Arquivo+' não encontrado.');
exit;
end;
conteudoArquivo := TStringList.Create;
conteudoArquivo.LoadFromFile(Arquivo);
if LeftStr(conteudoArquivo[0],8) <> 'CLIENTE|' then
begin
Erros.Add('Layout do arquivo '+Arquivo+' inválido');
exit;
end;
linha := TStringList.Create;
StringToArray(conteudoArquivo[0],'|',linha);
fQtReg := StrToIntDef(linha[1],0);
if fQtReg=0 then
begin
Erros.Add('Nenhum registro para importar.');
exit;
end;
fQtImp := 0;
for i := 1 to Pred(conteudoArquivo.Count) do
begin
linha.Clear;
StringToArray( conteudoArquivo[i],'|',linha);
if linha[0]='A' then
Continue
else if linha[0]='E' then
begin
if linha.Count<17 then
begin
Erros.Add('Linha inválida.('+IntToStr(i)+')');
Continue;
end;
cliente := TClienteModel.Create;
cliente.TpDoc := linha[1];
cliente.NumDoc := linha[2];
cliente.xNome := linha[3];
cliente.IE := linha[4];
cliente.ISUF := linha[5];
cliente.xLogr := linha[6];
cliente.Nro := linha[7];
cliente.xCpl := linha[8];
cliente.xBairro := linha[9];
cliente.cMun := linha[10];
cliente.xMun := linha[11];
cliente.UF := linha[12];
cliente.CEP := linha[13];
cliente.cPais := linha[14];
cliente.xPais := linha[15];
cliente.Fone := linha[16];
Clientes.Add(cliente);
Inc(fQtImp);
end;
end;
FreeAndNil(conteudoArquivo);
FreeAndNil(linha);
end;
procedure TImportaCliente.StringToArray(St: string; Separador: char;
Lista: TStringList);
var
I: Integer;
begin
Lista.Clear;
if St <> '' then
begin
St := St + Separador;
I := Pos(Separador, St);
while I > 0 do
begin
Lista.Add(Copy(St, 1, I - 1));
Delete(St, 1, I);
I := Pos(Separador, St);
end;
end;
end;
{ TListadeClientes }
function TListadeClientes.Add(Obj: TClienteModel): Integer;
begin
Result := inherited Add(Obj) ;
end;
function TListadeClientes.GetObject(Index: Integer): TClienteModel;
begin
Result := inherited GetItem(Index) as TClienteModel;
end;
procedure TListadeClientes.Insert(Index: Integer; Obj: TClienteModel);
begin
inherited Insert(Index, Obj);
end;
procedure TListadeClientes.SetObject(Index: Integer; Item: TClienteModel);
begin
inherited SetItem (Index, Item) ;
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000, 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QComCtrls;
{$R-,T-,H+,X+}
interface
uses
Types, SysUtils, Classes, Qt, QTypes, QControls, QStdCtrls, QGraphics,
Contnrs, QStdActns, QImgList, QMenus, QDialogs, QExtCtrls, QButtons;
type
{ Exception Classes }
EListViewException = class(Exception);
EListColumnException = class(Exception);
EStatusBarException = class(Exception);
EHeaderException = class(Exception);
ERangeException = class(Exception);
{ TTab }
TCustomTabControl = class;
TTabButtons = (tbLeft, tbRight);
TTabStyle = (tsTabs, tsButtons, tsFlatButtons, tsNoTabs);
TTabChangedEvent = procedure(Sender: TObject; TabID: Integer) of object;
TTabGetImageEvent = procedure(Sender: TObject; TabIndex: Integer;
var ImageIndex: Integer) of object;
TTabChangingEvent = procedure(Sender: TObject;
var AllowChange: Boolean) of object;
TDrawTabEvent = procedure(Control: TCustomTabControl; TabIndex: Integer;
const Rect: TRect; Active: Boolean; var DefaultDraw: Boolean ) of object;
TTabs = class;
TTabControl = class;
TTab = class(TCollectionItem)
private
FEnabled: Boolean;
FCaption: TCaption;
FTabRect: TRect;
FRow: Integer;
FImageIndex: Integer;
FVisible: Boolean;
FSelected: Boolean;
FHighlighted: Boolean;
function GetTabs: TTabs;
function CalculateWidth: Integer;
function CalculateHeight: Integer;
procedure SetCaption(const Value: TCaption);
procedure SetEnabled(const Value: Boolean);
function GetHeight: Integer;
function GetWidth: Integer;
procedure SetHeight(const Value: Integer);
procedure SetWidth(const Value: Integer);
function GetLeft: Integer;
function GetTop: Integer;
procedure SetLeft(const Value: Integer);
procedure SetTop(const Value: Integer);
procedure SetVisible(const Value: Boolean);
function GetImageIndex: Integer;
procedure SetImageIndex(const Value: Integer);
procedure SetSelected(const Value: Boolean);
procedure SetHighlighted(const Value: Boolean);
protected
function GetDisplayName: string; override;
property Left: Integer read GetLeft write SetLeft;
property Top: Integer read GetTop write SetTop;
property Height: Integer read GetHeight write SetHeight;
property Width: Integer read GetWidth write SetWidth;
public
constructor Create(Collection: TCollection); override;
procedure Assign(Source: TPersistent); override;
property Tabs: TTabs read GetTabs;
property Row: Integer read FRow;
property TabRect: TRect read FTabRect;
published
property Caption: TCaption read FCaption write SetCaption;
property Enabled: Boolean read FEnabled write SetEnabled default True;
property Highlighted: Boolean read FHighlighted write SetHighlighted default False;
property ImageIndex: Integer read GetImageIndex write SetImageIndex;
property Selected: Boolean read FSelected write SetSelected default False;
property Visible: Boolean read FVisible write SetVisible default True;
end;
{ TTabs }
TTabs = class(TCollection)
private
FTabControl: TCustomTabControl;
FUpdating: Boolean;
function GetItem(Index: Integer): TTab;
procedure SetItem(Index: Integer; const Value: TTab);
function CalculateTabHeight(const S: WideString): Integer;
protected
function GetOwner: TPersistent; override;
procedure Update(Item: TCollectionItem); override;
property TabControl: TCustomTabControl read FTabControl;
public
constructor Create(TabControl: TCustomTabControl);
function Add(const ACaption: WideString): TTab;
property Items[Index: Integer]: TTab read GetItem write SetItem; default;
end;
{ TCustomTabControl }
TTabSide = (tsLeft, tsTop, tsRight, tsBottom);
TCustomTabControl = class(TCustomControl)
private
FBitmap: TBitmap;
FButtons: array [TTabButtons] of TSpeedButton;
FErase: Boolean;
FDblBuffer: TBitmap;
FFirstVisibleTab: Integer;
FHotImages: TCustomImageList;
FHotTrack: Boolean;
FHotTrackColor: TColor;
FImageBorder: Integer;
FImageChangeLink: TChangeLink;
FImages: TCustomImageList;
FLastVisibleTab: Integer;
FLayoutCount: Integer;
FMouseOver: Integer;
FMultiLine: Boolean;
FMultiSelect: Boolean;
FOwnerDraw: Boolean;
FRaggedRight: Boolean;
FRowCount: Integer;
FShowFrame: Boolean;
FStyle: TTabStyle;
FTabIndex: Integer;
FTabs: TTabs;
FTabSize: TSmallPoint;
FTracking: Integer;
FOnChange: TNotifyEvent;
FOnChanged: TTabChangedEvent;
FOnChanging: TTabChangingEvent;
FOnDrawTab: TDrawTabEvent;
FOnGetImageIndex: TTabGetImageEvent;
FUpdating: Boolean;
function RightSide: Integer;
procedure ButtonClick(Sender: TObject);
procedure EraseControlFlag(const Value: Boolean = True);
procedure DisplayScrollButtons;
procedure DrawFocus;
function GetTabHeight: Integer;
procedure CalcImageTextOffset(const ARect: TRect; const S: WideString;
Image: TCustomImageList; var ImagePos, TextPos: TPoint);
procedure CalculateRows(SelectedRow: Integer);
procedure CalculateTabPositions;
procedure EnableScrollButtons;
function FindNextVisibleTab(Index: Integer): Integer;
function FindPrevVisibleTab(Index: Integer): Integer;
procedure BeginDblBuffer;
procedure EndDblBuffer;
procedure StretchTabs(ARow: Integer);
procedure CreateButtons;
function GetDisplayRect: TRect;
function GetImageRef: TCustomImageList;
function GetTabIndex: Integer;
function GetTotalTabHeight: Integer;
function HasImages(ATab: TTab): Boolean;
procedure InternalDrawTabFrame(ACanvas: TCanvas; const ARect: TRect; Tab: TTab; HotTracking: Boolean = False);
procedure InternalDrawTabContents(ACanvas: TCanvas; const ARect: TRect; Tab: TTab; HotTracking: Boolean = False);
procedure InternalDrawFrame(ACanvas: TCanvas; ARect: TRect; AShowFrame: Boolean = True;
Sunken: Boolean = False; Fill : Boolean = True);
function GetTabs: TTabs;
procedure PositionButtons;
function RightSideAdjustment: Integer;
procedure SetTabs(const Value: TTabs);
procedure SetHotTrack(const Value: Boolean);
procedure SetHotTrackColor(const Value: TColor);
procedure SetImages(const Value: TCustomImageList);
procedure SetMultiLine(const Value: Boolean);
procedure SetMultiSelect(const Value: Boolean);
procedure DoHotTrack(const Value: Integer);
procedure SetOwnerDraw(const Value: Boolean);
procedure SetRaggedRight(const Value: Boolean);
procedure SetStyle(Value: TTabStyle);
procedure SetTabHeight(const Value: Smallint);
procedure SetTabIndex(const Value: Integer);
procedure SetTabWidth(const Value: Smallint);
procedure TabsChanged;
procedure SetShowFrame(const Value: Boolean);
procedure DrawHighlight(Canvas: TCanvas; const Rect: TRect; ASelected, AHighlight,
AEnabled: Boolean);
procedure SetHotImages(const Value: TCustomImageList);
procedure UnselectTabs;
protected
procedure AdjustClientRect(var Rect: TRect); override;
procedure AdjustTabClientRect(var Rect: TRect); virtual;
procedure AdjustTabRect(var Rect: TRect); virtual;
function CanChange: Boolean; dynamic;
function CanShowTab(TabIndex: Integer): Boolean; virtual;
procedure Change; dynamic;
procedure Changed(Value: Integer); dynamic;
function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer;
const MousePos: TPoint): Boolean; override;
function DoMouseWheelDown(Shift: TShiftState; const MousePos: TPoint): Boolean; override;
function DoMouseWheelUp(Shift: TShiftState; const MousePos: TPoint): Boolean; override;
function DrawTab(TabIndex: Integer; const Rect: TRect; Active: Boolean): Boolean; virtual;
procedure EnabledChanged; override;
procedure FontChanged; override;
function GetImageIndex(ATabIndex: Integer): Integer; virtual;
procedure ImageListChange(Sender: TObject); virtual;
procedure KeyUp(var Key: Word; Shift: TShiftState); override;
procedure Loaded; override;
procedure LayoutTabs; virtual;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseLeave(AControl: TControl); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure Paint; override;
procedure Resize; override;
procedure RequestAlign; override;
procedure RequestLayout; dynamic;
procedure UpdateTabImages;
function WantKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; override;
function WidgetFlags: Integer; override;
property DisplayRect: TRect read GetDisplayRect;
property HotImages: TCustomImageList read FHotImages write SetHotImages;
property HotTrack: Boolean read FHotTrack write SetHotTrack default False;
property HotTrackColor: TColor read FHotTrackColor write SetHotTrackColor default clBlue;
property ImageBorder: Integer read FImageBorder write FImageBorder default 4;
property Images: TCustomImageList read FImages write SetImages;
property MultiLine: Boolean read FMultiLine write SetMultiLine default False;
property MultiSelect: Boolean read FMultiSelect write SetMultiSelect default False;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
property OwnerDraw: Boolean read FOwnerDraw write SetOwnerDraw default False;
property RaggedRight: Boolean read FRaggedRight write SetRaggedRight default False;
property ShowFrame: Boolean read FShowFrame write SetShowFrame default False;
property Style: TTabStyle read FStyle write SetStyle default tsTabs;
property TabHeight: Smallint read FTabSize.Y write SetTabHeight default 0;
property TabIndex: Integer read GetTabIndex write SetTabIndex default 0;
property Tabs: TTabs read GetTabs write SetTabs;
property TabWidth: Smallint read FTabSize.X write SetTabWidth default 0;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnChanged: TTabChangedEvent read FOnChanged write FOnChanged;
property OnChanging: TTabChangingEvent read FOnChanging write FOnChanging;
property OnDrawTab: TDrawTabEvent read FOnDrawTab write FOnDrawTab;
property OnGetImageIndex: TTabGetImageEvent read FOnGetImageIndex write FOnGetImageIndex;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BeginUpdate;
procedure EndUpdate;
function IndexOfTabAt(X, Y: Integer): Integer;
procedure ScrollTabs(Delta: Integer);
function TabRect(Index: Integer): TRect; //depricated;
property Canvas;
property RowCount: Integer read FRowCount;
property TabStop default True;
end;
{ TTabControl }
TTabControl = class(TCustomTabControl)
published
property Anchors;
property Align;
property Constraints;
property DragMode;
property Enabled;
property Font;
property HotImages;
property HotTrack;
property HotTrackColor;
property Images;
property MultiLine;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property RaggedRight;
property ShowFrame;
property ShowHint;
property Style;
property MultiSelect; { must be after Style due to streaming order }
property TabHeight;
property TabOrder;
property TabStop;
property Tabs;
property TabIndex; { must be after Tabs due to streaming order }
property TabWidth;
property Visible;
property OnChange;
property OnChanged;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetImageIndex;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDrag;
end;
{ TTabSheet }
TPageControl = class;
TTabSheet = class(TCustomControl)
private
FBorderWidth: TBorderWidth;
FImageIndex: TImageIndex;
FHighlighted: Boolean;
FPageControl: TPageControl;
FTabVisible: Boolean;
FOnHide: TNotifyEvent;
FOnShow: TNotifyEvent;
FTab: TTab;
function GetPageIndex: Integer;
function GetTabIndex: Integer;
procedure SetBorderWidth(const Value : TBorderWidth);
procedure SetHighlighted(const Value: Boolean);
procedure SetImageIndex(const Value: TImageIndex);
procedure SetPageControl(const Value: TPageControl);
procedure SetPageIndex(const Value: Integer);
procedure SetTabVisible(const Value: Boolean);
protected
procedure AdjustClientRect(var Rect: TRect); override;
procedure DoHide; dynamic;
procedure DoShow; dynamic;
procedure EnabledChanged; override;
procedure ReadState(Reader: TReader); override;
procedure ShowingChanged; override;
procedure TextChanged; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure InitWidget; override;
property PageControl: TPageControl read FPageControl write SetPageControl;
property TabIndex: Integer read GetTabIndex;
published
property BorderWidth: TBorderWidth read FBorderWidth write SetBorderWidth default 0;
property Caption;
property Color;
property DragMode;
property Enabled;
property Font;
property Height stored False;
property Highlighted: Boolean read FHighlighted write SetHighlighted default False;
property ImageIndex: TImageIndex read FImageIndex write SetImageIndex default 0;
property Left stored False;
property PageIndex: Integer read GetPageIndex write SetPageIndex stored False;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabVisible: Boolean read FTabVisible write SetTabVisible default True;
property Top stored False;
property Visible stored False;
property Width stored False;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnHide: TNotifyEvent read FOnHide write FOnHide;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnShow: TNotifyEvent read FOnShow write FOnShow;
property OnStartDrag;
end;
{ TPageControl }
TPageChangingEvent = procedure(Sender: TObject; NewPage: TTabSheet; var AllowChange: Boolean) of object;
TPageControl = class(TCustomTabControl)
private
FPages: TList;
FActivePage: TTabSheet;
FOnPageChange: TNotifyEvent;
FOnPageChanging: TPageChangingEvent;
procedure DeleteTab(Page: TTabSheet; Index: Integer);
function GetActivePageIndex: Integer;
function GetPage(Index: Integer): TTabSheet;
function GetPageCount: Integer;
procedure SetActivePage(aPage: TTabSheet);
procedure SetActivePageIndex(const Value: Integer);
procedure ChangeActivePage(Page: TTabSheet);
procedure MoveTab(CurIndex, NewIndex: Integer);
procedure InsertPage(const APage: TTabSheet);
procedure InsertTab(Page: TTabSheet);
procedure RemovePage(const APage: TTabSheet);
procedure UpdateTab(Page: TTabSheet);
protected
procedure DoContextPopup(const MousePos: TPoint; var Handled: Boolean); override;
function CanShowTab(TabIndex: Integer): Boolean; override;
procedure Changed(Value: Integer); override;
procedure Change; override;
function DesignEventQuery(Sender: QObjectH; Event: QEventH): Boolean; override;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
procedure PageChange; dynamic;
procedure PageChanging(NewPage: TTabSheet; var AllowChange: Boolean); dynamic;
procedure SetChildOrder(Child: TComponent; Order: Integer); override;
procedure ShowControl(AControl: TControl); override;
procedure UpdateActivePage; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function FindNextPage(CurPage: TTabSheet;
GoForward, CheckTabVisible: Boolean): TTabSheet;
procedure SelectNextPage(GoForward: Boolean);
procedure Update; override;
property ActivePageIndex: Integer read GetActivePageIndex
write SetActivePageIndex;
property PageCount: Integer read GetPageCount;
property Pages[Index: Integer]: TTabSheet read GetPage;
published
property ActivePage: TTabSheet read FActivePage write SetActivePage;
property Align;
property Anchors;
property Constraints;
property DragMode;
property Enabled;
property Font;
property HotTrack;
property HotTrackColor;
property HotImages;
property Images;
property MultiLine;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property RaggedRight;
property ShowFrame;
property ShowHint;
property Style;
property TabHeight;
property TabOrder;
property TabStop;
property TabWidth;
property Visible;
property OnChange: TNotifyEvent read FOnPageChange write FOnPageChange;
property OnChanging;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetImageIndex;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnPageChanging: TPageChangingEvent read FOnPageChanging write FOnPageChanging;
property OnResize;
property OnStartDrag;
end;
{ TStatusBar }
TStatusBar = class;
TStatusPanel = class;
TPanelPosition = (ppLeft, ppRight);
TStatusPanelStyle = (psText, psOwnerDraw);
TStatusPanelBevel = (pbNone, pbLowered, pbRaised);
TStatusPanels = class;
TStatusPanel = class(TCollectionItem)
private
FAlignment: TAlignment;
FBevel: TStatusPanelBevel;
FBounds: TRect;
FHidden: Boolean;
FPanelPosition: TPanelPosition;
FStyle: TStatusPanelStyle;
FText: WideString;
FVisible: Boolean;
FWidth: Integer;
procedure SetAlignment(const Value: TAlignment);
procedure SetBevel(const Value: TStatusPanelBevel);
procedure SetStyle(Value: TStatusPanelStyle);
procedure SetText(const Value: WideString);
procedure SetWidth(const Value: Integer);
procedure SetPanelPosition(const Value: TPanelPosition);
procedure SetVisible(const Value: Boolean);
function GetStatusPanels: TStatusPanels;
protected
function GetDisplayName: string; override;
property StatusPanels: TStatusPanels read GetStatusPanels;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify;
property Bevel: TStatusPanelBevel read FBevel write SetBevel default pbLowered;
property PanelPosition: TPanelPosition read FPanelPosition write SetPanelPosition default ppLeft;
property Style: TStatusPanelStyle read FStyle write SetStyle default psText;
property Text: WideString read FText write SetText;
property Visible: Boolean read FVisible write SetVisible default True;
property Width: Integer read FWidth write SetWidth default 50;
end;
{ TStatusPanels }
TStatusPanels = class(TCollection)
private
FFixedPanelCount: Integer;
FStatusBar: TStatusBar;
function GetItem(Index: Integer): TStatusPanel;
procedure SetItem(Index: Integer; const Value: TStatusPanel);
protected
function GetOwner: TPersistent; override;
procedure Update(Item: TCollectionItem); override;
property StatusBar: TStatusBar read FStatusBar;
public
constructor Create(StatusBar: TStatusBar);
function Add: TStatusPanel;
property Items[Index: Integer]: TStatusPanel read GetItem write SetItem; default;
end;
{ TStatusBar }
TPanelClick = procedure(Sender: TObject; Panel: TStatusPanel) of object;
TDrawPanelEvent = procedure(StatusBar: TStatusBar; Panel: TStatusPanel;
const Rect: TRect) of object;
TStatusBar = class(TCustomPanel)
private
FAutoHint: Boolean;
FUpdateCount: Integer;
FSimplePanel: Boolean;
FSimpleText: WideString;
FPanels: TStatusPanels;
FOnDrawPanel: TDrawPanelEvent;
FOnHint: TNotifyEvent;
FSizeGrip: Boolean;
FSizeGripHandle: QSizeGripH;
FOnPanelClick: TPanelClick;
function IsFontStored: Boolean;
procedure SetPanels(const Value: TStatusPanels);
procedure SetSimplePanel(const Value: Boolean);
procedure SetSimpleText(const Value: WideString);
procedure UpdatePanels;
procedure SetSizeGrip(const Value: Boolean);
procedure PositionSizeGrip;
procedure ValidateSizeGrip;
function GetPanel(PanelPosition: TPanelPosition;
Index: Integer): TStatusPanel;
function GetBorderWidth: TBorderWidth;
procedure SetBorderWidth(const Value: TBorderWidth);
procedure CMRecreateWindow(var Message: TMessage); message CM_RECREATEWINDOW;
protected
procedure ControlsAligned; override;
procedure CursorChanged; override;
function DoHint: Boolean; virtual;
procedure DoPanelClick(Panel: TStatusPanel); dynamic;
procedure DrawPanel(Panel: TStatusPanel; const Rect: TRect); dynamic;
procedure EnabledChanged; override;
procedure InitWidget; override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure Paint; override;
procedure PaletteCreated; override;
procedure RequestAlign; override;
procedure Resize; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BeginUpdate;
procedure EndUpdate;
function ExecuteAction(Action: TBasicAction): Boolean; override;
function FindPanel(PanelPosition: TPanelPosition;
Index: Integer): TStatusPanel;
procedure FlipChildren(AllLevels: Boolean); override;
procedure Invalidate; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure Update; override;
property Canvas;
property Panel[PanelPosition: TPanelPosition; Index: Integer]: TStatusPanel
read GetPanel;
published
property Action;
property Align default alBottom;
property Anchors;
property AutoHint: Boolean read FAutoHint write FAutoHint default False;
property BorderWidth: TBorderWidth read GetBorderWidth write SetBorderWidth default 0;
property Color default clBackground;
property Constraints;
property DragMode;
property Enabled;
property Font stored IsFontStored;
property Panels: TStatusPanels read FPanels write SetPanels;
property ParentColor default False;
property ParentFont default True;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property SimplePanel: Boolean read FSimplePanel write SetSimplePanel default False;
property SimpleText: WideString read FSimpleText write SetSimpleText;
property SizeGrip: Boolean read FSizeGrip write SetSizeGrip default True;
property Visible;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnDrawPanel: TDrawPanelEvent read FOnDrawPanel write FOnDrawPanel;
property OnEndDrag;
property OnHint: TNotifyEvent read FOnHint write FOnHint;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnPanelClick: TPanelClick read FOnPanelClick write FOnPanelClick;
property OnResize;
property OnStartDrag;
end;
{ TTrackBar }
TTrackBarOrientation = (trHorizontal, trVertical);
TTickMark = (tmBottomRight, tmTopLeft, tmBoth);
TTickStyle = (tsNone, tsAuto);
QTickSetting = (qtsNoMarks, qtsAbove, qtsLeft, qtsBelow, qtsRight, qtsBoth);
TTrackBar = class(TWidgetControl)
private
FMin: Integer;
FMax: Integer;
FOnChange: TNotifyEvent;
FTickMarks: TTickMark;
FTickStyle: TTickStyle;
FOrientation: TTrackBarOrientation;
procedure ChangeAspectRatio;
function GetHandle: QClxSliderH;
procedure SetFrequency(const Value: Integer);
procedure SetLineSize(const Value: Integer);
procedure SetMax(const Value: Integer);
procedure SetMin(const Value: Integer);
procedure SetOrientation(const Value: TTrackBarOrientation);
procedure SetPageSize(const Value: Integer);
procedure SetPosition(const Value: Integer);
procedure SetRange(const AMin, AMax: Integer);
procedure SetTickMarks(const Value: TTickMark);
procedure SetTickStyle(const Value: TTickStyle);
function GetOrientation: TTrackBarOrientation;
function GetFrequency: Integer;
function GetRangeControl: QRangeControlH;
function GetLineSize: Integer;
function GetPageSize: Integer;
function GetMax: Integer;
function GetMin: Integer;
function GetPosition: Integer;
function GetTickMarks: TTickMark;
function GetTickStyle: TTickStyle;
procedure UpdateSettings;
procedure ValueChangedHook(Value: Integer); cdecl;
protected
procedure Changed; dynamic;
procedure CreateWidget; override;
procedure HookEvents; override;
procedure InitWidget; override;
procedure Loaded; override;
property RangeControl: QRangeControlH read GetRangeControl;
public
constructor Create(AOwner: TComponent); override;
property Handle: QClxSliderH read GetHandle;
published
property Align;
property Anchors;
property Bitmap;
property Constraints;
property DragMode;
property Enabled;
property Frequency: Integer read GetFrequency write SetFrequency default 1;
property Hint;
property LineSize: Integer read GetLineSize write SetLineSize default 1;
property Masked default False;
property Max: Integer read GetMax write SetMax default 10;
property Min: Integer read GetMin write SetMin default 0;
property Orientation: TTrackBarOrientation read GetOrientation write SetOrientation default trHorizontal;
property PageSize: Integer read GetPageSize write SetPageSize default 2;
property ParentShowHint;
property PopupMenu;
property Position: Integer read GetPosition write SetPosition default 0;
property ShowHint;
property TabOrder;
property TabStop default True;
property TickMarks: TTickMark read GetTickMarks write SetTickMarks default tmBottomRight;
property TickStyle: TTickStyle read GetTickStyle write SetTickStyle default tsAuto;
property Visible;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyString;
property OnKeyUp;
property OnStartDrag;
end;
{ TProgressBar }
TProgressBarChangeEvent = procedure(Sender: TObject; var Text: WideString; NewPosition: Integer) of object;
TProgressBarOrientation = (pbHorizontal, pbVertical);
TProgressBar = class(TGraphicControl)
private
FBorderWidth: TBorderWidth;
FFillColor: TColor;
FFillArea: TRect;
FSections: Integer;
FStep: Integer;
FMin: Integer;
FMax: Integer;
FOrientation: TProgressBarOrientation;
FPosition: Integer;
FPrevText: WideString;
FShowCaption: Boolean;
FSmooth: Boolean;
FTransparent: Boolean;
FText: TCaption;
FTextColor: TColor;
FTotalSteps: Integer;
FWrapRange: Boolean;
FOnChanging: TProgressBarChangeEvent;
function AdjustToParent(const Rect: TRect): TRect;
function CalcTextRect(Rect: TRect; const BoundingRect: TRect; const AText: WideString): TRect;
procedure EraseText(const AText: WideString; BackgroundColor : TColor);
procedure InternalPaint;
procedure InternalDrawFrame;
function ScalePosition(Value: Integer): Integer;
procedure SetBorderWidth(const Value: TBorderWidth);
procedure SetFillColor(const Value: TColor);
procedure SetMax(const Value: Integer);
procedure SetMin(const Value: Integer);
procedure SetOrientation(const Value: TProgressBarOrientation);
procedure SetPosition(Value: Integer);
procedure SetRange(const AMin, AMax: Integer);
procedure SetShowCaption(const Value: Boolean);
procedure SetSmooth(const Value: Boolean);
procedure SetStep(const Value: Integer);
procedure SetTransparent(const Value: Boolean);
protected
procedure Changing(var Text: WideString; NewPosition: Integer); dynamic;
procedure FontChanged; override;
function GetText: TCaption; override;
procedure Paint; override;
procedure SetText(const Value: TCaption); override;
property WrapRange: Boolean read FWrapRange write FWrapRange;
public
constructor Create(AOwner: TComponent); override;
procedure StepBy(Delta: Integer);
procedure StepIt; virtual;
published
property Align;
property Anchors;
property BorderWidth: TBorderWidth read FBorderWidth write SetBorderWidth default 0;
property Caption;
property Color;
property Constraints;
property DragMode;
property Enabled;
property FillColor: TColor read FFillColor write SetFillColor default clHighlight;
property Font;
property Hint;
property Max: Integer read FMax write SetMax default 100;
property Min: Integer read FMin write SetMin default 0;
property Orientation: TProgressBarOrientation read FOrientation write SetOrientation default pbHorizontal;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property Position: Integer read FPosition write SetPosition default 0;
property ShowCaption: Boolean read FShowCaption write SetShowCaption default False;
property ShowHint;
property Smooth: Boolean read FSmooth write SetSmooth default False;
property Step: Integer read FStep write SetStep default 10;
property Transparent: Boolean read FTransparent write SetTransparent default False;
property Visible;
property OnChanging: TProgressBarChangeEvent read FOnChanging write FOnChanging;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
TMimeSourceFactory = class(TPersistent)
private
FFilePath: TStrings;
procedure SetFilePath(const Value: TStrings);
protected
FHandle: QMimeSourceFactoryH;
procedure CreateHandle; virtual;
procedure DestroyWidget; virtual;
function GetHandle: QMimeSourceFactoryH;
function HandleAllocated: Boolean;
procedure HandleNeeded;
procedure DoGetDataHook(AbsoluteName: PWideString;
var ResolvedData: QMimeSourceH); cdecl;
procedure GetData(const AbsoluteName: string;
var ResolvedData: QMimeSourceH); virtual;
public
constructor Create;
destructor Destroy; override;
procedure AddDataToFactory(const Name: WideString; Data: QMimeSourceH);
procedure AddImageToFactory(const Name: WideString; Data: QImageH);
procedure AddPixmapToFactory(const Name: WideString; Data: QPixmapH);
procedure AddTextToFactory(const Name: WideString; const Data: string);
function GetMimeSource(const MimeType: WideString): QMimeSourceH;
procedure RegisterMimeType(const FileExt: WideString; const MimeType: string);
property Handle: QMimeSourceFactoryH read GetHandle;
published
property FilePath: TStrings read FFilePath write SetFilePath;
end;
{ TCustomTextViewer }
TTextFormat = (tfPlainText, tfText, tfAutoText);
TCustomTextViewer = class(TFrameControl)
private
FBrush: TBrush;
FFactory: TMimeSourceFactory;
FUseDefaultFactory: Boolean;
FViewportHandle: QWidgetH;
FViewportHook: QWidget_hookH;
FTextColor: TColor;
FFileName: TFileName;
FUnderlineLink: Boolean;
FLinkColor: TColor;
FTextFormat: TTextFormat;
FVScrollHandle: QScrollBarH;
FHScrollHandle: QScrollBarH;
FVScrollHook: QScrollBar_hookH;
FHScrollHook: QScrollBar_hookH;
procedure SubmitTextColor;
procedure SetTextFormat(const Value: TTextFormat);
procedure SetUnderlineLink(const Value: Boolean);
function GetDocumentTitle: WideString;
function GetIsTextSelected: Boolean;
function GetSelectedText: WideString;
function GetBrush: TBrush;
procedure SetBrush(const Value: TBrush);
procedure SetTextColor(const Value: TColor);
function GetDocumentText: WideString;
procedure SetLinkColor(const Value: TColor);
procedure SetDocumentText(const Value: WideString); virtual;
function GetFactory: TMimeSourceFactory;
procedure SetFactory(const Value: TMimeSourceFactory);
procedure SetDefaultFactory(const Value: Boolean);
procedure SetFileName(const Value: TFileName);
procedure UpdateViewableContents;
protected
procedure CreateWidget; override;
function GetChildHandle: QWidgetH; override;
function GetHandle: QTextViewH;
procedure InitWidget; override;
procedure PaperChanged(Sender: TObject);
function ViewportHandle: QWidgetH;
procedure WidgetDestroyed; override;
property DocumentTitle: WideString read GetDocumentTitle;
property Handle: QTextViewH read GetHandle;
property BorderStyle default bsSunken3d;
property Factory: TMimeSourceFactory read GetFactory write SetFactory;
property FileName: TFileName read FFileName write SetFileName;
property Height default 150;
property IsTextSelected: Boolean read GetIsTextSelected;
property LinkColor: TColor read FLinkColor write SetLinkColor
default clBlue;
property Paper: TBrush read GetBrush write SetBrush;
property SelectedText: WideString read GetSelectedText;
property Text: WideString read GetDocumentText write SetDocumentText;
property TextColor: TColor read FTextColor write SetTextColor
default clBlack;
property TextFormat: TTextFormat read FTextFormat write SetTextFormat
default tfAutoText;
property UnderlineLink: Boolean read FUnderlineLink write SetUnderlineLink
default True;
property UseDefaultFactory: Boolean read FUseDefaultFactory
write SetDefaultFactory;
property Width default 200;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SelectAll;
procedure CopyToClipboard;
procedure LoadFromFile(const AFileName: string); virtual;
procedure LoadFromStream(Stream: TStream);
end;
{ TTextViewer }
TTextViewer = class(TCustomTextViewer)
public
property DocumentTitle;
property Factory;
property Handle;
property IsTextSelected;
property Paper;
property SelectedText;
property Text;
published
property Align;
property Anchors;
property BorderStyle;
property Constraints;
property DragMode;
property Height;
property FileName;
property LinkColor;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property TextColor;
property TextFormat;
property UnderlineLink;
property Width;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
{ TCustomTextBrowser }
TRTBHighlightTextEvent = procedure (Sender: TObject;
const HighlightedText: WideString) of object;
TCustomTextBrowser = class(TCustomTextViewer)
private
FBackwardAvailable: Boolean;
FForwardAvailable: Boolean;
FRTBHighlightText: TRTBHighlightTextEvent;
FTextChanged: TNotifyEvent;
procedure SetDocumentText(const Value: WideString); override;
procedure HookBackwardAvailable(p1: Boolean); cdecl;
procedure HookForwardAvailable(p1: Boolean); cdecl;
procedure HookHighlightText(p1: PWideString); cdecl;
procedure HookTextChanged; cdecl;
procedure SetHighlightText(const Value: TRTBHighlightTextEvent);
procedure SetTextChanged(const Value: TNotifyEvent);
protected
procedure CreateWidget; override;
procedure WidgetDestroyed; override;
procedure HookEvents; override;
function GetHandle: QTextBrowserH;
property Handle: QTextBrowserH read GetHandle;
property OnHighlightText: TRTBHighlightTextEvent read FRTBHighlightText write SetHighlightText;
property OnTextChanged: TNotifyEvent read FTextChanged write SetTextChanged;
public
procedure LoadFromFile(const AFileName: string); override;
procedure ScrollToAnchor(const AnchorName: WideString);
function CanGoBackward: Boolean;
procedure Backward;
function CanGoForward: Boolean;
procedure Forward;
procedure Home;
end;
{ TTextBrowser }
TTextBrowser = class(TCustomTextBrowser)
public
property DocumentTitle;
property Handle;
property IsTextSelected;
property Paper;
property SelectedText;
property Text;
published
property Align;
property Anchors;
property BorderStyle;
property Constraints;
property DragMode;
property Factory;
property FileName;
property Height;
property LinkColor;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property TextColor;
property TextFormat;
property UnderlineLink;
property Width;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnHighlightText;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
property OnTextChanged;
end;
{ TSpinEdit }
TSEButtonType = (btNext, btPrev);
TSEButtonStyle = (bsArrows, bsPlusMinus);
TSEDownDirection = (sedNone, sedUp, sedDown);
TSEChangedEvent = procedure (Sender: TObject; NewValue: Integer) of object;
TCustomSpinEdit = class(TWidgetControl)
private
FButtonUpHook: QWidget_HookH;
FButtonDownHook: QWidget_HookH;
FEditHandle: QWidgetH;
FEditHook: QWidget_HookH;
FDownButtonHandle: QWidgetH;
FMin: Integer;
FMax: Integer;
FUpButtonHandle: QWidgetH;
FOnChanged: TSEChangedEvent;
function GetButtonStyle: TSEButtonStyle;
function GetCleanText: WideString;
function GetIncrement: Integer;
function GetMax: Integer;
function GetMin: Integer;
function GetPrefix: WideString;
function GetRangeControl: QRangeControlH;
function GetSuffix: WideString;
function GetSpecialText: WideString;
function GetValue: Integer;
function GetWrap: Boolean;
procedure ValueChangedHook(AValue: Integer); cdecl;
procedure SetButtonStyle(AValue: TSEButtonStyle);
procedure SetIncrement(AValue: Integer);
procedure SetMax(AValue: Integer);
procedure SetMin(AValue: Integer);
procedure SetPrefix(const AValue: WideString);
procedure SetRange(const AMin, AMax: Integer);
procedure SetSuffix(const AValue: WideString);
procedure SetSpecialText(const AValue: WideString);
procedure SetWrap(AValue: Boolean);
function GetHandle: QClxSpinBoxH;
procedure SetValue(const AValue: Integer);
protected
procedure CreateWidget; override;
procedure WidgetDestroyed; override;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
procedure HookEvents; override;
procedure Change(AValue: Integer); dynamic;
function GetText: TCaption; override;
procedure InitWidget; override;
procedure Loaded; override;
procedure PaletteChanged(Sender: TObject); override;
property ButtonStyle: TSEButtonStyle read GetButtonStyle write SetButtonStyle default bsArrows;
property CleanText: WideString read GetCleanText;
property Handle: QClxSpinBoxH read GetHandle;
property Max: Integer read GetMax write SetMax default 100;
property Min: Integer read GetMin write SetMin default 0;
property Increment: Integer read GetIncrement write SetIncrement default 1;
property Prefix: WideString read GetPrefix write SetPrefix;
property RangeControl: QRangeControlH read GetRangeControl;
property SpecialText: WideString read GetSpecialText write SetSpecialText;
property Suffix: WideString read GetSuffix write SetSuffix;
property TabStop default True;
property Text: TCaption read GetText;
property Value: Integer read GetValue write SetValue default 0;
property Wrap: Boolean read GetWrap write SetWrap default False;
property OnChanged: TSEChangedEvent read FOnChanged write FOnChanged;
public
constructor Create(AOwner: TComponent); override;
procedure StepUp;
procedure StepDown;
end;
TSpinEdit = class(TCustomSpinEdit)
public
property CleanText;
property Text;
published
property Align;
property Anchors;
property ButtonStyle;
property Constraints;
property Color;
property DragMode;
property Enabled;
property Hint;
property Max;
property Min;
property Increment;
property PopupMenu;
property TabOrder;
property TabStop;
property Value;
property Visible;
property ParentShowHint;
property Prefix;
property ShowHint;
property SpecialText;
property Suffix;
property Wrap;
property OnChanged;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
{ forward class declarations }
THeaderControl = class;
TCustomHeaderControl = class;
TCustomViewControl = class;
TCustomViewItem = class;
TCustomListView = class;
TListItem = class;
TListView = class;
TCustomTreeView = class;
TTreeNode = class;
{ TCustomHeaderSection }
TCustomHeaderSection = class(TCollectionItem)
private
FAllowResize: Boolean;
FAllowClick: Boolean;
FMaxWidth: Integer;
FWidth: Integer;
FMinWidth: Integer;
FHeader: TCustomHeaderControl;
FImageIndex: TImageIndex;
FAutoSize: Boolean;
FText: WideString;
procedure UpdateWidth;
function Header: TCustomHeaderControl;
procedure SetAllowClick(const Value: Boolean);
procedure SetAllowResize(const Value: Boolean);
procedure SetMaxWidth(const Value: Integer);
procedure SetMinWidth(const Value: Integer);
procedure SetWidth(Value: Integer);
function GetLeft: Integer;
function GetRight: Integer;
procedure SetImageIndex(const Value: TImageIndex);
procedure UpdateImage;
procedure SetAutoSize(const Value: Boolean);
function CalcSize: Integer;
protected
procedure AddSection; virtual;
procedure AssignTo(Dest: TPersistent); override;
function GetDisplayName: string; override;
function GetWidth: Integer; virtual;
procedure Resubmit; virtual;
procedure SetWidthVal(const Value: Integer); virtual;
property AllowClick: Boolean read FAllowClick write SetAllowClick;
property AllowResize: Boolean read FAllowResize write SetAllowResize;
property AutoSize: Boolean read FAutoSize write SetAutoSize;
property ImageIndex: TImageIndex read FImageIndex write SetImageIndex;
property Left: Integer read GetLeft;
property MaxWidth: Integer read FMaxWidth write SetMaxWidth;
property MinWidth: Integer read FMinWidth write SetMinWidth;
property Right: Integer read GetRight;
property Width: Integer read GetWidth write SetWidth;
public
constructor Create(Collection: TCollection); override;
end;
{ THeaderSection }
THeaderSection = class(TCustomHeaderSection)
private
procedure SetText(const Value: WideString);
protected
procedure AssignTo(Dest: TPersistent); override;
procedure SetWidthVal(const Value: Integer); override;
{$IF not (defined(LINUX) and defined(VER140))}
function GetText: WideString;
{$IFEND}
public
destructor Destroy; override;
property Index;
property Left;
property Right;
published
property AllowClick default True;
property AllowResize default True;
property AutoSize default False;
property ImageIndex default -1;
property MaxWidth default 1000;
property MinWidth;
{$IF defined(LINUX) and defined(VER140)}
property Text: WideString read FText write SetText;
{$ELSE}
property Text: WideString read GetText write SetText;
{$IFEND}
property Width default 50;
end;
THeaderSectionClass = class of TCustomHeaderSection;
{ TCustomHeaderSections }
TCustomHeaderSections = class(TCollection)
private
FHeaderControl: TCustomHeaderControl;
procedure UpdateImages;
protected
function GetOwner: TPersistent; override;
procedure Update(Item: TCollectionItem); override;
function GetItem(Index: Integer): TCustomHeaderSection;
procedure SetItem(Index: Integer; Value: TCustomHeaderSection);
public
constructor Create(HeaderControl: TCustomHeaderControl; SectionClass: THeaderSectionClass);
property Items[Index: Integer]: TCustomHeaderSection read GetItem write SetItem; default;
end;
{ THeaderSections }
THeaderSections = class(TCustomHeaderSections)
protected
function GetItem(Index: Integer): THeaderSection;
procedure SetItem(Index: Integer; Value: THeaderSection);
public
function Add: THeaderSection;
property Items[Index: Integer]: THeaderSection read GetItem write SetItem; default;
end;
{ THeaderOrientation }
THeaderOrientation = (hoHorizontal, hoVertical);
TSectionNotifyEvent = procedure(HeaderControl: TCustomHeaderControl;
Section: TCustomHeaderSection) of object;
{ Resize event is the same as HotTracking if Tracking = True }
TCustomHeaderControl = class(TWidgetControl)
private
FClickable: Boolean;
FDragReorder: Boolean;
FResizable: Boolean;
FTracking: Boolean;
FOrientation: THeaderOrientation;
FSections: TCustomHeaderSections;
FMemStream: TMemoryStream;
FOnSectionResize: TSectionNotifyEvent;
FOnSectionClick: TSectionNotifyEvent;
FOnSectionMoved: TSectionNotifyEvent;
FCanvas: TCanvas;
FImages: TCustomImageList;
FImageChanges: TChangeLink;
FDontResubmit: Boolean;
procedure OnImageChanges(Sender: TObject);
procedure SectionClicked(SectionIndex: Integer); cdecl;
procedure SectionSizeChanged(SectionIndex: Integer; OldSize, NewSize: Integer); cdecl;
procedure SectionMoved(FromIndex, ToIndex: Integer); cdecl;
procedure SetClickable(const Value: Boolean);
procedure SetDragReorder(const Value: Boolean);
procedure SetOrientation(const Value: THeaderOrientation);
procedure SetResizable(const Value: Boolean);
procedure SetTracking(const Value: Boolean);
procedure SetSections(const Value: TCustomHeaderSections);
function GetSections: TCustomHeaderSections;
procedure SetImages(const Value: TCustomImageList);
protected
procedure AssignTo(Dest: TPersistent); override;
function GetHandle: QHeaderH; virtual;
procedure CreateWidget; override;
procedure HookEvents; override;
procedure ChangeBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure ColumnClicked(Section: TCustomHeaderSection); dynamic;
procedure ColumnMoved(Section: TCustomHeaderSection); dynamic;
procedure ColumnResized(Section: TCustomHeaderSection); dynamic;
procedure ImageListChanged; dynamic;
procedure InitWidget; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure RestoreWidgetState; override;
procedure SaveWidgetState; override;
property Align default alTop;
property Canvas: TCanvas read FCanvas;
property Clickable: Boolean read FClickable write SetClickable default False;
property Handle: QHeaderH read GetHandle;
property Height default 19;
property DragReorder: Boolean read FDragReorder write SetDragReorder default False;
property Images: TCustomImageList read FImages write SetImages;
property Resizable: Boolean read FResizable write SetResizable default False;
property Sections: TCustomHeaderSections read GetSections write SetSections;
property Tracking: Boolean read FTracking write SetTracking default False;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnSectionClick: TSectionNotifyEvent read FOnSectionClick
write FOnSectionClick;
property OnSectionResize: TSectionNotifyEvent read FOnSectionResize
write FOnSectionResize;
property OnSectionMoved: TSectionNotifyEvent read FOnSectionMoved
write FOnSectionMoved;
property Orientation: THeaderOrientation read FOrientation
write SetOrientation default hoHorizontal;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
{ THeaderControl }
THeaderControl = class(TCustomHeaderControl)
private
procedure SetSections(const Value: THeaderSections);
function GetSections: THeaderSections;
procedure Init(AHeaderSectionClass: THeaderSectionClass);
protected
procedure CreateWidget; override;
procedure InitWidget; override;
public
constructor Create(AOwner: TComponent); overload; override;
constructor Create(AOwner: TComponent; AHeaderSectionClass: THeaderSectionClass); reintroduce; overload;
public
destructor Destroy; override;
property Canvas;
published
property Align;
property Anchors;
property Clickable;
property Constraints;
property DragMode;
property DragReorder;
property Height;
property Hint;
property Images;
property Orientation;
property ParentShowHint;
property PopupMenu;
property Resizable;
property Sections: THeaderSections read GetSections write SetSections;
property ShowHint;
property Tracking;
property OnConstrainedResize;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnSectionClick;
property OnSectionResize;
property OnSectionMoved;
property OnStartDrag;
end;
{ TListColumn }
TListColumn = class(TCustomHeaderSection)
private
FAlignment: TAlignment;
FAutoSize: Boolean;
procedure SetCaption(const Value: WideString);
procedure SetAutoSize(const Value: Boolean);
procedure SetAlignment(const Value: TAlignment);
function HeaderIsListHeader: Boolean;
{$IF not (defined(LINUX) and defined(VER140))}
function GetCaption: WideString;
{$IFEND}
protected
procedure AddSection; override;
procedure AssignTo(Dest: TPersistent); override;
function GetWidth: Integer; override;
procedure Resubmit; override;
procedure SetWidthVal(const Value: Integer); override;
function ViewControl: TCustomViewControl;
public
destructor Destroy; override;
property Index;
published
property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify;
property AllowClick default True;
property AllowResize default True;
property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
{$IF defined(LINUX) and defined(VER140)}
property Caption: WideString read FText write SetCaption;
{$ELSE}
property Caption: WideString read GetCaption write SetCaption;
{$IFEND}
property MaxWidth default 1000;
property MinWidth default 0;
property Width;
end;
{ TListColumns }
TListColumns = class(TCustomHeaderSections)
private
function GetItem(Index: Integer): TListColumn;
procedure SetItem(Index: Integer; Value: TListColumn);
function GetViewControl: TCustomViewControl;
protected
procedure Added(var Item: TCollectionItem); override;
procedure Update(Item: TCollectionItem); override;
property ViewControl: TCustomViewControl read GetViewControl;
public
function Add: TListColumn;
property Items[Index: Integer]: TListColumn read GetItem write SetItem; default;
end;
{ TViewItemsList }
TListViewItemType = (itDefault, itCheckBox, itRadioButton, itController);
TViewItemsList = class(TObjectList)
protected
function GetItem(Index: Integer): TCustomViewItem;
procedure SetItem(Index: Integer; AObject: TCustomViewItem);
property Items[Index: Integer]: TCustomViewItem read GetItem write SetItem; default;
end;
{ TCustomViewItems }
TCustomViewItems = class(TPersistent)
private
FUpdateCount: Cardinal;
FOwner: TCustomViewControl;
FItems: TViewItemsList;
function GetItem(Index: Integer): TCustomViewItem;
procedure SetItem(Index: Integer; const Value: TCustomViewItem);
function GetCount: Integer;
protected
function GetHandle: QListViewH;
function FindViewItem(ItemH: QListViewItemH): TCustomViewItem;
procedure SetUpdateState(Updating: Boolean);
property Owner: TCustomViewControl read FOwner;
property Handle: QListViewH read GetHandle;
public
constructor Create(AOwner: TCustomViewControl); virtual;
destructor Destroy; override;
procedure BeginUpdate;
procedure Clear;
procedure EndUpdate;
procedure ChangeItemTypes(NewType: TListViewItemType);
function IndexOf(Value: TCustomViewItem): Integer;
procedure Delete(Index: Integer);
property Count: Integer read GetCount;
property Item[Index: Integer]: TCustomViewItem read GetItem write SetItem; default;
end;
{ TListItems }
TListItemClass = class of TListItem;
TListItems = class(TCustomViewItems)
private
FListItemClass: TListItemClass;
function GetItem(Index: Integer): TListItem;
procedure SetItem(Index: Integer; const Value: TListItem);
function GetItemsOwner: TCustomListView;
protected
procedure DefineProperties(Filer: TFiler); override;
function FindItem(ItemH: QListViewItemH): TListItem;
procedure ReadData(Stream: TStream);
procedure WriteData(Stream: TStream);
public
constructor Create(AOwner: TCustomViewControl); overload; override;
constructor Create(AOwner: TCustomViewControl; AItemClass: TListItemClass); reintroduce; overload;
function Add: TListItem;
function AddItem(Item: TListItem; Index: Integer = -1): TListItem;
function Insert(Index: Integer): TListItem;
procedure SetItemClass(AListItemClass: TListItemClass);
property Item[Index: Integer]: TListItem read GetItem write SetItem; default;
property Owner: TCustomListView read GetItemsOwner;
end;
TItemState = (isNone, isFocused, isSelected, isActivating);
TItemStates = set of TItemState;
{ TCustomViewItem }
TCustomViewItem = class(TPersistent)
private
FSubItems: TStrings;
FOwner: TCustomViewItems;
FItemType: TListViewItemType;
FParent: TCustomViewItem;
FNextItem: TCustomViewItem;
FPrevItem: TCustomViewItem;
FLastChild: TCustomViewItem;
FData: Pointer;
FChecked: Boolean;
FExpandable: Boolean;
FSelectable: Boolean;
FText: WideString;
FStates: TItemStates;
FImageIndex: TImageIndex;
FDestroying: Boolean;
function ViewControlValid: Boolean;
procedure DetermineCreationType;
procedure SetCaption(const Value: WideString);
function GetChildCount: Integer;
function GetTotalHeight: Integer;
function GetExpanded: Boolean;
procedure SetExpanded(const Value: Boolean);
function GetHeight: Integer;
function GetSelected: Boolean;
procedure SetExpandable(const Value: Boolean);
procedure SetSelectable(const Value: Boolean);
procedure SetSelected(const Value: Boolean);
procedure SetChecked(const Value: Boolean);
procedure SetItemType(const Value: TListViewItemType);
procedure SetParent(const Value: TCustomViewItem);
function GetIndex: Integer;
procedure SetImageIndex(const Value: TImageIndex);
function GetSubItemImages(Column: Integer): Integer;
procedure SetSubItemImages(Column: Integer; const Value: Integer);
function ItemHook: QClxListViewHooksH;
function GetWidth: Integer;
procedure SetSubItems(const Value: TStrings);
function GetSubItems: TStrings;
procedure UpdateImages;
function GetFocused: Boolean;
procedure SetFocused(const Value: Boolean);
protected
FHandle: QListViewItemH;
procedure Collapse;
procedure CreateWidget(AParent, After: TCustomViewItem);
procedure DestroyWidget;
procedure Expand;
function GetHandle: QListViewItemH;
function HandleAllocated: Boolean;
procedure ImageIndexChange(ColIndex: Integer; NewIndex: Integer); virtual;
procedure InsertItem(AItem: TCustomViewItem);
function ParentCount: Integer;
procedure ReCreateItem;
procedure RemoveItem(AItem: TCustomViewItem);
procedure Repaint;
procedure ResetFields; virtual;
function ViewControl: TCustomViewControl;
property Caption: WideString read FText write SetCaption;
property Checked: Boolean read FChecked write SetChecked;
property ChildCount: Integer read GetChildCount;
property Data: Pointer read FData write FData;
property Expandable: Boolean read FExpandable write SetExpandable;
property Expanded: Boolean read GetExpanded write SetExpanded;
property Focused: Boolean read GetFocused write SetFocused;
property Handle: QListViewItemH read GetHandle;
property Height: Integer read GetHeight;
property ImageIndex: TImageIndex read FImageIndex write SetImageIndex;
property Index: Integer read GetIndex;
property ItemType: TListViewItemType read FItemType write SetItemType;
property Owner: TCustomViewItems read FOwner;
property Parent: TCustomViewItem read FParent write SetParent;
property Selectable: Boolean read FSelectable write SetSelectable;
property Selected: Boolean read GetSelected write SetSelected;
property States: TItemStates read FStates;
property SubItemImages[Column: Integer]: Integer read GetSubItemImages write SetSubItemImages;
property SubItems: TStrings read GetSubItems write SetSubItems;
property TotalHeight: Integer read GetTotalHeight;
property Width: Integer read GetWidth;
public
constructor Create(AOwner: TCustomViewItems; AParent: TCustomViewItem = nil; After: TCustomViewItem = nil); virtual;
destructor Destroy; override;
procedure AssignTo(Dest: TPersistent); override;
procedure Delete;
function DisplayRect: TRect;
procedure MakeVisible(PartialOK: Boolean);
end;
{ TListItem }
TListItem = class(TCustomViewItem)
private
function GetListView: TCustomListView;
function GetOwnerlist: TListItems;
function IsEqual(Item: TListItem): Boolean;
{$IF not (defined(LINUX) and defined(VER140))}
function GetCaption: WideString;
procedure SetCaption(Value: WideString);
{$IFEND}
public
destructor Destroy; override;
{$IF defined(LINUX) and defined(VER140)}
property Caption read FText write SetCaption;
{$ELSE}
property Caption read GetCaption write SetCaption;
{$IFEND}
property Checked;
property Data;
property Focused;
property Handle;
property ImageIndex;
property Index;
property ItemType;
property ListView: TCustomListView read GetListView;
property Owner: TListItems read GetOwnerList;
property Selectable;
property Selected;
property SubItemImages;
property SubItems;
end;
{ TItemEditor }
TItemEditor = class(TCustomEdit)
private
FMenuHook: QPopupMenu_hookH;
FItem: TCustomViewItem;
FEditing: Boolean;
FShouldClose: Boolean;
FPopup: QPopupMenuH;
FFrame: QFrameH;
FFrameHooks: QFrame_hookH;
FViewControl: TCustomViewControl;
procedure FrameDestroyedHook; cdecl;
function PopupMenuFilter(Sender: QObjectH; Event: QEventH): Boolean; cdecl;
protected
procedure ClearMenuHook;
procedure CreateWidget; override;
procedure Execute; virtual;
procedure EditFinished(Accepted: Boolean); virtual;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
procedure HookEvents; override;
procedure InitItem;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyUp(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
procedure KeyString(var S: WideString; var Handled: Boolean); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
{ TCustomViewControl }
TItemChange = (ctText, ctImage, ctState);
TSortDirection = (sdAscending, sdDescending);
TCustomDrawState = set of (cdsSelected, cdsGrayed, cdsDisabled, cdsChecked,
cdsFocused, cdsDefault, cdsHot, cdsMarked, cdsIndeterminate);
TCustomDrawStage = (cdPrePaint, cdPostPaint);
TViewColumnRClickEvent = procedure(Sender: TObject; Column: TListColumn;
const Point: TPoint) of object;
TViewColumnEvent = procedure(Sender: TObject; Column: TListColumn) of object;
TViewColumnClickEvent = TViewColumnEvent;
TViewColumnResizeEvent = TViewColumnEvent;
TViewColumnMovedEvent = TViewColumnEvent;
TCustomDrawViewItemEvent = procedure(Sender: TCustomViewControl;
Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect;
State: TCustomDrawState; Stage: TCustomDrawStage;
var DefaultDraw: Boolean) of object;
TCustomDrawViewSubItemEvent = procedure(Sender: TCustomViewControl;
Item: TCustomViewItem; SubItem: Integer; Canvas: TCanvas; const Rect: TRect;
State: TCustomDrawState; Stage: TCustomDrawStage;
var DefaultDraw: Boolean) of object;
TCustomViewControl = class(TFrameControl)
private
FShowColumnSortIndicators: Boolean;
FMultiSelect: Boolean;
FRowSelect: Boolean;
FShowColumnHeaders: Boolean;
FImageList: TCustomImageList;
FHeader: TCustomHeaderControl;
FMemStream: TMemoryStream;
FViewportHandle: QWidgetH;
FViewportHooks: QWidget_hookH;
FHScrollHooks: QScrollBar_hookH;
FVScrollHooks: QScrollBar_hookH;
FVScrollHandle: QScrollBarH;
FHScrollHandle: QScrollBarH;
FItemHooks: QClxListViewHooksH;
FOnColumnClick: TViewColumnClickEvent;
FColumnDragged: TViewColumnMovedEvent;
FColumnResize: TViewColumnResizeEvent;
FOnCustomDrawItem: TCustomDrawViewItemEvent;
FOnCustomDrawSubItem: TCustomDrawViewSubItemEvent;
FOnCustomDrawBranch: TCustomDrawViewItemEvent;
FSorted: Boolean;
FSortColumn: Integer;
FSortDirection: TSortDirection;
FOwnerDraw: Boolean;
FTimer: TTimer;
FAllowEdit: Boolean;
FReadOnly: Boolean;
FEditor: TItemEditor;
FSelCount: Integer;
FIndent: Integer;
FImageLink: TChangeLink;
procedure ImageListChange(Sender: TObject);
procedure RepopulateItems; virtual;
procedure CheckRemoveEditor;
procedure SetIndent(const Value: Integer);
function GetHandle: QListViewH;
function GetIndent: Integer;
procedure SetMultiSelect(const Value: Boolean);
function GetMultiSelect: Boolean;
function GetRowSelect: Boolean;
procedure SetRowSelect(const Value: Boolean);
procedure SetImageList(const Value: TCustomImageList);
procedure ItemDestroyedHook(AItem: QListViewItemH); cdecl;
procedure ItemDestroyed(AItem: QListViewItemH); virtual;
procedure ItemPaintHook(p: QPainterH; item: QListViewItemH; column, width,
alignment: Integer; var stage: Integer) cdecl;
procedure BranchPaintHook(p: QPainterH; item: QListViewItemH;
w, y, h: Integer; style: GUIStyle; var stage: Integer) cdecl;
procedure ItemChangeHook(item: QListViewItemH; _type: TItemChange); cdecl;
procedure ItemChange(item: QListViewItemH; _type: TItemChange); virtual;
procedure ItemChangingHook(item: QListViewItemH; _type: TItemChange;
var Allow: Boolean); cdecl;
procedure ItemChanging(item: QListViewItemH; _type: TItemChange;
var Allow: Boolean); virtual;
procedure ItemSelectedHook(item: QListViewItemH; wasSelected: Boolean); cdecl;
procedure ItemSelected(item: QListViewItemH; wasSelected: Boolean); virtual;
procedure ItemExpandingHook(item: QListViewItemH; Expand: Boolean;
var Allow: Boolean); cdecl;
procedure ItemExpanding(item: QListViewItemH; Expand: Boolean;
var Allow: Boolean); virtual;
procedure ItemExpandedHook(item: QListViewItemH; Expand: Boolean); cdecl;
procedure ItemExpanded(item: QListViewItemH; Expand: Boolean); virtual;
procedure ItemCheckedHook(item: QListViewItemH; Checked: Boolean); cdecl;
procedure ItemChecked(item: QListViewItemH; Checked: Boolean); virtual;
function GetColumnClick: Boolean;
procedure SetColumnClick(const Value: Boolean);
procedure SetColumns(const Value: TListColumns);
function GetColumns: TListColumns;
procedure SetShowColumnSortIndicators(const Value: Boolean);
function GetColumnResize: Boolean;
procedure SetColumnResize(const Value: Boolean);
function GetColumnMove: Boolean;
procedure SetColumnMove(const Value: Boolean);
procedure SetSorted(const Value: Boolean);
procedure SetOwnerDraw(const Value: Boolean);
procedure TimerIntervalElapsed(Sender: TObject);
procedure StartEditTimer;
procedure EditItem;
procedure ViewportDestroyed; cdecl;
protected
procedure BeginAutoDrag; override;
procedure ColorChanged; override;
procedure CreateWidget; override;
function CreateEditor: TItemEditor; virtual;
function DoCustomDrawViewItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect;
State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; virtual;
function DoCustomDrawViewSubItem(Item: TCustomViewItem; SubItem: Integer; Canvas: TCanvas;
const Rect: TRect; State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; virtual;
function DoCustomDrawViewBranch(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect;
State: TCustomDrawState; Stage: TCustomDrawStage): Boolean; virtual;
procedure DoDrawItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect;
State: TOwnerDrawState); virtual;
procedure DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean); dynamic;
procedure DoEdited(AItem: TCustomViewItem; var S: WideString); dynamic;
procedure DoGetImageIndex(item: TCustomViewItem); virtual;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
function FindDropTarget: TCustomViewItem;
function GetChildHandle: QWidgetH; override;
procedure HookEvents; override;
procedure InitWidget; override;
function IsCustomDrawn: Boolean; virtual;
function IsOwnerDrawn: Boolean; virtual;
function NeedKey(Key: Integer; Shift: TShiftState;
const KeyText: WideString): Boolean; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure ImageListChanged; virtual;
procedure SetShowColumnHeaders(const Value: Boolean);
procedure UpdateControl;
function ViewportHandle: QWidgetH;
procedure WidgetDestroyed; override;
property ColumnClick: Boolean read GetColumnClick write SetColumnClick default False;
property ColumnResize: Boolean read GetColumnResize write SetColumnResize default False;
property ColumnMove: Boolean read GetColumnMove write SetColumnMove default True;
property Columns: TListColumns read GetColumns write SetColumns;
property Images: TCustomImageList read FImageList write SetImageList;
property Height default 97;
property Indent: Integer read GetIndent write SetIndent default 20;
property MultiSelect: Boolean read GetMultiSelect write SetMultiSelect;
property OwnerDraw: Boolean read FOwnerDraw write SetOwnerDraw default False;
property ParentColor default False;
property ReadOnly: Boolean read FReadOnly write FReadOnly default False;
property RowSelect: Boolean read GetRowSelect write SetRowSelect default False;
property SelCount: Integer read FSelCount default 0;
property ShowColumnHeaders: Boolean read FShowColumnHeaders
write SetShowColumnHeaders default False;
property ShowColumnSortIndicators: Boolean read FShowColumnSortIndicators
write SetShowColumnSortIndicators default False;
property SortColumn: Integer read FSortColumn write FSortColumn default 0;
property SortDirection: TSortDirection read FSortDirection
write FSortDirection default sdAscending;
property Sorted: Boolean read FSorted write SetSorted default False;
property TabStop default True;
property Width default 121;
property OnColumnClick: TViewColumnClickEvent read FOnColumnClick
write FOnColumnClick;
property OnColumnDragged: TViewColumnMovedEvent read FColumnDragged
write FColumnDragged;
property OnColumnResize: TViewColumnResizeEvent read FColumnResize
write FColumnResize;
property OnCustomDrawBranch: TCustomDrawViewItemEvent read FOnCustomDrawBranch
write FOnCustomDrawBranch;
property OnCustomDrawItem: TCustomDrawViewItemEvent read FOnCustomDrawItem
write FOnCustomDrawItem;
property OnCustomDrawSubItem: TCustomDrawViewSubItemEvent read FOnCustomDrawSubItem
write FOnCustomDrawSubItem;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure InvertSelection;
function IsEditing: Boolean;
procedure Sort(Column: Integer; Direction: TSortDirection);
property Handle: QListViewH read GetHandle;
end;
{ TCustomListView }
TItemFind = (ifData, ifPartialString, ifExactString, ifNearest);
TSearchDirection = (sdAbove, sdBelow, sdAll);
TViewStyle = (vsList, vsReport);
TLVNotifyEvent = procedure (Sender: TObject; Item: TListItem) of object;
TLVChangeEvent = procedure (Sender: TObject; Item: TListItem;
Change: TItemChange) of object;
TLVChangingEvent = procedure (Sender: TObject; Item: TListItem;
Change: TItemChange; var AllowChange: Boolean) of object;
TLVItemExitViewportEnterEvent = TNotifyEvent;
TLVSelectItemEvent = procedure (Sender: TObject; Item: TListItem;
Selected: Boolean) of object;
TLVItemClickEvent = procedure (Sender: TObject; Button: TMouseButton;
Item: TListItem; const Pt: TPoint; ColIndex: Integer) of object;
TLVItemDoubleClickEvent = TLVNotifyEvent;
TLVEditingEvent = procedure (Sender: TObject; Item: TListItem;
var AllowEdit: Boolean) of object;
TLVEditedEvent = procedure (Sender: TObject; Item: TListItem;
var S: WideString) of object;
TLVButtonDownEvent = procedure (Sender: TObject; Button: TMouseButton;
Item: TListItem; const Pt: TPoint; ColIndex: Integer) of object;
TLVViewportButtonDownEvent = procedure (Sender: TObject; Button: TMouseButton;
const Pt: TPoint) of object;
TListViewDrawItemEvent = procedure(Sender: TCustomListView; Item: TListItem;
Canvas: TCanvas; const Rect: TRect; State: TOwnerDrawState) of object;
TCustomListView = class(TCustomViewControl)
private
FSelected: TListItem;
FItems: TListItems;
FCheckBoxes: Boolean;
FOnInsert: TLVNotifyEvent;
FOnChange: TLVChangeEvent;
FOnChanging: TLVChangingEvent;
FOnDeletion: TLVNotifyEvent;
FOnSelectItem: TLVSelectItemEvent;
FOnItemClick: TLVItemClickEvent;
FOnItemDoubleClick: TLVItemDoubleClickEvent;
FOnItemEnter: TLVNotifyEvent;
FOnItemExitViewportEnter: TLVItemExitViewportEnterEvent;
FOnMouseDown: TLVButtonDownEvent;
FOnViewportMouseDown: TLVViewportButtonDownEvent;
FOnEditing: TLVEditingEvent;
FOnEdited: TLVEditedEvent;
FViewStyle: TViewStyle;
FDownsHooked: Boolean;
FOnGetImageIndex: TLVNotifyEvent;
FOnDrawItem: TListViewDrawItemEvent;
procedure RepopulateItems; override;
procedure SetItems(const Value: TListItems);
procedure SetCheckBoxes(const Value: Boolean);
procedure UpdateItemTypes;
procedure HookMouseDowns;
procedure DoItemDoubleClick(ListItem: QListViewItemH); cdecl;
procedure DoItemClick(Button: Integer; ListItem: QListViewItemH;
Pt: PPoint; ColIndex: Integer); cdecl;
procedure DoOnItemEnter(ListItem: QListViewItemH); cdecl;
procedure DoOnItemExitViewportEnter; cdecl;
procedure DoLVMouseDown(Button: Integer; ListItem: QListViewItemH;
Pt: PPoint; ColIndex: Integer); cdecl;
procedure SetOnItemDoubleClick(const Value: TLVItemDoubleClickEvent);
procedure SetOnItemEnter(const Value: TLVNotifyEvent);
procedure SetOnItemExitViewportEnter(const Value: TLVItemExitViewportEnterEvent);
procedure SetOnMouseDown(const Value: TLVButtonDownEvent);
procedure SetOnViewportButtonDown(const Value: TLVViewportButtonDownEvent);
procedure SetViewStyle(const Value: TViewStyle);
function GetSelected: TListItem;
procedure SetSelected(const Value: TListItem);
function GetItemFocused: TListItem;
procedure SetItemFocused(const Value: TListItem);
procedure SetTopItem(const AItem: TListItem);
function GetTopItem: TListItem;
protected
procedure DoDrawItem(Item: TCustomViewItem; Canvas: TCanvas; const Rect: TRect;
State: TOwnerDrawState); override;
procedure DoEdited(AItem: TCustomViewItem; var S: WideString); override;
procedure DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean); override;
procedure DoGetImageIndex(item: TCustomViewItem); override;
function GetDropTarget: TListItem;
procedure HookEvents; override;
procedure ImageListChanged; override;
procedure Init(AListItemClass: TListItemClass); virtual;
procedure InitWidget; override;
function IsOwnerDrawn: Boolean; override;
procedure ItemChange(item: QListViewItemH; _type: TItemChange); override;
procedure ItemChanging(item: QListViewItemH; _type: TItemChange;
var Allow: Boolean); override;
procedure ItemChecked(item: QListViewItemH; Checked: Boolean); override;
procedure ItemDestroyed(AItem: QListViewItemH); override;
procedure ItemSelected(item: QListViewItemH; wasSelected: Boolean); override;
procedure RestoreWidgetState; override;
procedure SaveWidgetState; override;
property CheckBoxes: Boolean read FCheckBoxes write SetCheckBoxes
default False;
property Height default 150;
property Items: TListItems read FItems write SetItems;
property ReadOnly default False;
property SortDirection default sdAscending;
property ViewStyle: TViewStyle read FViewStyle write SetViewStyle
default vsList;
property OnChange: TLVChangeEvent read FOnChange write FOnChange;
property OnChanging: TLVChangingEvent read FOnChanging write FOnChanging;
property OnDeletion: TLVNotifyEvent read FOnDeletion write FOnDeletion;
property OnDrawItem: TListViewDrawItemEvent read FOnDrawItem write FOnDrawItem;
property OnEdited: TLVEditedEvent read FOnEdited write FOnEdited;
property OnEditing: TLVEditingEvent read FOnEditing write FOnEditing;
property OnGetImageIndex: TLVNotifyEvent read FOnGetImageIndex
write FOnGetImageIndex;
property OnInsert: TLVNotifyEvent read FOnInsert write FOnInsert;
property OnItemClick: TLVItemClickEvent read FOnItemClick write FOnItemClick;
property OnItemDoubleClick: TLVItemDoubleClickEvent read FOnItemDoubleClick
write SetOnItemDoubleClick;
property OnItemEnter: TLVNotifyEvent read FOnItemEnter write SetOnItemEnter;
property OnItemExitViewportEnter: TLVItemExitViewportEnterEvent
read FOnItemExitViewportEnter write SetOnItemExitViewportEnter;
property OnItemMouseDown: TLVButtonDownEvent read FOnMouseDown
write SetOnMouseDown;
property OnSelectItem: TLVSelectItemEvent read FOnSelectItem
write FOnSelectItem;
property OnViewPortMouseDown: TLVViewportButtonDownEvent
read FOnViewportMouseDown write SetOnViewportButtonDown;
public
constructor Create(AOwner: TComponent); overload; override;
constructor Create(AOwner: TComponent; AListItemClass: TListItemClass); reintroduce; overload;
destructor Destroy; override;
function AlphaSort: Boolean;
function FindData(StartIndex: Integer; Value: Pointer; Inclusive,
Wrap: Boolean): TListItem;
function FindCaption(StartIndex: Integer; const Value: WideString;
Partial, Inclusive, Wrap: Boolean): TListItem;
function GetItemAt(X, Y: Integer): TListItem;
function GetNearestItem(const Point: TPoint;
Direction: TSearchDirection): TListItem;
function GetNextItem(StartItem: TListItem; Direction: TSearchDirection;
States: TItemStates): TListItem;
procedure Scroll(DX, DY: Integer);
procedure UpdateItems(FirstIndex, LastIndex: Integer);
property DropTarget: TListItem read GetDropTarget;
property ItemFocused: TListItem read GetItemFocused write SetItemFocused;
property Selected: TListItem read GetSelected write SetSelected;
property TopItem: TListItem read GetTopItem write SetTopItem;
end;
{ TListView }
TListView = class(TCustomListView)
public
property SortColumn;
published
property Align;
property Anchors;
property BorderStyle default bsSunken3d;
property CheckBoxes default False;
property Color;
property ColumnClick default True;
property ColumnMove default True;
property ColumnResize default True;
property Columns;
property Constraints;
property DragMode;
property Enabled;
property Font;
property Height;
property Hint;
property Images;
property Items;
property MultiSelect default False;
property OwnerDraw;
property RowSelect default False;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property SelCount;
property ShowColumnSortIndicators;
property ShowHint;
property SortDirection;
property Sorted;
property TabOrder;
property TabStop;
property ViewStyle;
property Visible;
property Width;
property OnChange;
property OnChanging;
property OnClick;
property OnColumnClick;
property OnColumnDragged;
property OnColumnResize;
property OnContextPopup;
property OnCustomDrawItem;
property OnCustomDrawSubItem;
property OnDblClick;
property OnDeletion;
property OnDragDrop;
property OnDragOver;
property OnDrawItem;
property OnEdited;
property OnEditing;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetImageIndex;
property OnInsert;
property OnItemClick;
property OnItemDoubleClick;
property OnItemEnter;
property OnItemExitViewportEnter;
property OnItemMouseDown;
property OnKeyDown;
property OnKeyPress;
property OnKeyString;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnSelectItem;
property OnStartDrag;
property OnViewPortMouseDown;
end;
{ ETreeViewError }
ETreeViewError = class(Exception);
{ TTreeNodes }
TNodeAttachMode = (naAdd, naAddFirst, naAddChild, naAddChildFirst, naInsert);
TAddMode = (taAddFirst, taAdd, taInsert);
TTreeNodeClass = class of TTreeNode;
TTreeNodes = class(TCustomViewItems)
private
FNodeClass: TTreeNodeClass;
function GetItem(Index: Integer): TTreeNode;
function GetNodesOwner: TCustomTreeView;
procedure ReadData(Stream: TStream);
procedure WriteData(Stream: TStream);
protected
function CreateNode(ParentNode: TTreeNode = nil; AfterNode: TTreeNode = nil): TTreeNode;
procedure DefineProperties(Filer: TFiler); override;
function InternalAddObject(Node: TTreeNode; const S: WideString;
Ptr: Pointer; AddMode: TAddMode): TTreeNode;
function FindItem(ItemH: QListViewItemH): TTreeNode;
function FindPrevSibling(ANode: TTreeNode): TTreeNode;
public
function Add(Node: TTreeNode; const S: WideString): TTreeNode;
function AddChild(Node: TTreeNode; const S: WideString): TTreeNode;
function AddChildFirst(Node: TTreeNode; const S: WideString): TTreeNode;
function AddChildObject(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode;
function AddChildObjectFirst(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode;
function AddFirst(Node: TTreeNode; const S: WideString): TTreeNode;
function AddObject(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode;
function AddObjectFirst(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode;
procedure Assign(Dest: TPersistent); override;
procedure Clear;
procedure Delete(Node: TTreeNode);
function GetFirstNode: TTreeNode;
function GetNode(ItemH: QListViewItemH): TTreeNode;
function Insert(Node: TTreeNode; const S: WideString): TTreeNode;
function InsertObject(Node: TTreeNode; const S: WideString; Ptr: Pointer): TTreeNode;
procedure SetNodeClass(NewNodeClass: TTreeNodeClass);
property Item[Index: Integer]: TTreeNode read GetItem; default;
property Owner: TCustomTreeView read GetNodesOwner;
end;
{ TTreeNode }
PNodeInfo = ^TNodeInfo;
TNodeInfo = packed record
ImageIndex: Integer;
SelectedIndex: Integer;
StateIndex: Integer;
SubItemCount: Integer;
Data: Pointer;
Count: Integer;
Text: string[255];
end;
TTreeNode = class(TCustomViewItem)
private
FDeleting: Boolean;
FSelectedIndex: Integer;
function DoCanExpand(Expand: Boolean): Boolean;
procedure ExpandItem(Expand: Boolean; Recurse: Boolean);
function GetCount: Integer;
function GetItem(Index: Integer): TTreeNode;
function GetLevel: Integer;
function GetParent: TTreeNode;
function GetIndex: Integer;
function GetTreeView: TCustomTreeView;
function IsNodeVisible: Boolean;
function IsEqual(Node: TTreeNode): Boolean;
procedure SetItem(Index: Integer; const Value: TTreeNode);
function GetNodeOwner: TTreeNodes;
procedure SetNodeParent(const Value: TTreeNode);
procedure SetSelectedIndex(const Value: Integer);
function GetDropTarget: Boolean;
{$IF not (defined(LINUX) and defined(VER140))}
function GetSelected: Boolean;
procedure SetSelected(const Value: Boolean);
function GetExpandable: Boolean;
procedure SetExpandable(const Value: Boolean);
function GetCaption: WideString;
procedure SetCaption(const Value: WideString);
{$IFEND}
protected
function CompareCount(CompareMe: Integer): Boolean;
function GetAbsoluteIndex: Integer;
procedure ImageIndexChange(ColIndex: Integer; NewIndex: Integer); override;
procedure ReadData(Stream: TStream; Info: PNodeInfo);
procedure WriteData(Stream: TStream; Info: PNodeInfo);
public
constructor Create(AOwner: TCustomViewItems; AParent:
TCustomViewItem = nil; After: TCustomViewItem = nil); override;
destructor Destroy; override;
procedure AssignTo(Dest: TPersistent); override;
procedure Collapse(Recurse: Boolean);
function AlphaSort(Ascending: Boolean): Boolean;
procedure Delete;
procedure DeleteChildren;
function EditText: Boolean;
procedure Expand(Recurse: Boolean);
function getFirstChild: TTreeNode;
function GetLastChild: TTreeNode;
function GetNext: TTreeNode;
function GetNextChild(Value: TTreeNode): TTreeNode;
function getNextSibling: TTreeNode;
function GetNextVisible: TTreeNode;
function GetPrev: TTreeNode;
function GetPrevChild(Value: TTreeNode): TTreeNode;
function getPrevSibling: TTreeNode;
function GetPrevVisible: TTreeNode;
function HasAsParent(Value: TTreeNode): Boolean;
function IndexOf(Value: TTreeNode): Integer;
procedure MoveTo(Destination: TTreeNode; Mode: TNodeAttachMode); virtual;
property AbsoluteIndex: Integer read GetAbsoluteIndex;
property Checked;
property Count: Integer read GetCount;
property Data;
property Deleting: Boolean read FDeleting;
property DropTarget: Boolean read GetDropTarget;
property Focused: Boolean read GetSelected write SetSelected;
property Expanded;
property Handle;
{$IF defined(LINUX) and defined(VER140)}
property HasChildren: Boolean read FExpandable write SetExpandable;
{$ELSE}
property HasChildren: Boolean read GetExpandable write SetExpandable;
{$IFEND}
property Height;
property ImageIndex;
property Index: Integer read GetIndex;
property IsVisible: Boolean read IsNodeVisible;
property ItemType;
property Item[Index: Integer]: TTreeNode read GetItem write SetItem; default;
property Level: Integer read GetLevel;
property Owner: TTreeNodes read GetNodeOwner;
property Parent: TTreeNode read GetParent write SetNodeParent;
property Selected;
property SelectedIndex: Integer read FSelectedIndex write SetSelectedIndex;
{$IF defined(LINUX) and defined(VER140)}
property Text: WideString read FText write SetCaption;
{$ELSE}
property Text: WideString read GetCaption write SetCaption;
{$IFEND}
property TotalHeight;
property TreeView: TCustomTreeView read GetTreeView;
property Selectable;
property SubItemImages;
property SubItems;
end;
{ TCustomTreeView }
TSortType = (stNone, stText);
TTVItemNotifyEvent = procedure(Sender: TObject; Node: TTreeNode) of object;
TTVDeletedEvent = TTVItemNotifyEvent;
TTVItemEnterEvent = TTVItemNotifyEvent;
TTVItemExitViewportEnterEvent = TNotifyEvent;
TTVChangedEvent = TTVItemNotifyEvent;
TTVChangingEvent = procedure(Sender: TObject; Node: TTreeNode;
var AllowChange: Boolean) of object;
TTVExpandingEvent = procedure(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean) of object;
TTVCollapsingEvent = procedure(Sender: TObject; Node: TTreeNode;
var AllowCollapse: Boolean) of object;
TTVExpandedEvent = TTVItemNotifyEvent;
TTVCollapsedEvent = TTVExpandedEvent;
TTVSelectItemEvent = procedure(Sender: TObject; Node: TTreeNode;
Selected: Boolean) of object;
TTVEditingEvent = procedure (Sender: TObject; Node: TTreeNode;
var AllowEdit: Boolean) of object;
TTVEditedEvent = procedure (Sender: TObject; Node: TTreeNode;
var S: WideString) of object;
TTVItemClickEvent = procedure (Sender: TObject; Button: TMouseButton;
Node: TTreeNode; const Pt: TPoint) of object;
TTVItemDoubleClickEvent = procedure (Sender: TObject;
Node: TTreeNode) of object;
TTVButtonDownEvent = procedure (Sender: TObject; Button: TMouseButton;
Node: TTreeNode; const Pt: TPoint) of object;
TTVViewportButtonDownEvent = procedure (Sender: TObject; Button: TMouseButton;
const Pt: TPoint) of object;
TCustomTreeView = class(TCustomViewControl)
private
FTreeNodes: TTreeNodes;
FSelectedNode: TTreeNode;
FLastNode: TTreeNode;
FSortType: TSortType;
FShowButtons: Boolean;
FMemStream: TMemoryStream;
FOnChange: TTVChangedEvent;
FOnChanging: TTVChangingEvent;
FOnCollapsing: TTVCollapsingEvent;
FOnDeletion: TTVExpandedEvent;
FOnCollapsed: TTVExpandedEvent;
FOnExpanded: TTVExpandedEvent;
FOnExpanding: TTVExpandingEvent;
FAutoExpand: Boolean;
FOnMouseDown: TTVButtonDownEvent;
FOnInsert: TTVDeletedEvent;
FOnItemClick: TTVItemClickEvent;
FOnItemDoubleClick: TTVItemDoubleClickEvent;
FOnItemEnter: TTVItemEnterEvent;
FOnItemExitViewportEnter: TTVItemExitViewportEnterEvent;
FOnViewportMouseDown: TTVViewportButtonDownEvent;
FOnEdited: TTVEditedEvent;
FOnEditing: TTVEditingEvent;
FOnGetImageIndex: TTVExpandedEvent;
FOnGetSelectedIndex: TTVExpandedEvent;
FFullExpansion: Boolean;
FItemMargin: Integer;
procedure RepopulateItems; override;
procedure DoAutoExpand(ExpandedNode: TTreeNode);
procedure SetSortType(const Value: TSortType);
procedure SetAutoExpand(const Value: Boolean);
function GetSelected: TTreeNode;
procedure SetSelected(const Value: TTreeNode);
procedure SetItemMargin(const Value: Integer);
procedure HookMouseDowns;
procedure DoItemClick(p1: Integer; p2: QListViewItemH; p3: PPoint;
p4: Integer); cdecl;
procedure DoItemDoubleClick(p1: QListViewItemH); cdecl;
procedure DoOnItemEnter(item: QListViewItemH); cdecl;
procedure DoOnItemExitViewportEnter; cdecl;
procedure DoOnMouseDown(p1: Integer; p2: QListViewItemH; p3: PPoint; p4: Integer); cdecl;
procedure SetOnItemDoubleClick(const Value: TTVItemDoubleClickEvent);
procedure SetOnItemEnter(const Value: TTVItemEnterEvent);
procedure SetOnItemExitViewportEnter(const Value: TTVItemExitViewportEnterEvent);
procedure SetOnMouseDown(const Value: TTVButtonDownEvent);
procedure SetOnViewportButtonDown(const Value: TTVViewportButtonDownEvent);
procedure SetShowButtons(const Value: Boolean);
procedure SetItems(const Value: TTreeNodes);
procedure SetTopItem(const AItem: TTreeNode);
function GetTopItem: TTreeNode;
procedure ItemChanging(item: QListViewItemH; _type: TItemChange;
var Allow: Boolean); override;
procedure ItemDestroyed(AItem: QListViewItemH); override;
procedure ItemExpanding(item: QListViewItemH; Expand: Boolean;
var Allow: Boolean); override;
procedure ItemExpanded(item: QListViewItemH; Expand: Boolean); override;
procedure ItemChecked(item: QListViewItemH; Checked: Boolean); override;
procedure ItemSelected(item: QListViewItemH; wasSelected: Boolean); override;
protected
function CanCollapse(Node: TTreeNode): Boolean; dynamic;
function CanExpand(Node: TTreeNode): Boolean; dynamic;
procedure Change(Node: TTreeNode); dynamic;
procedure Collapse(Node: TTreeNode); dynamic;
procedure Delete(Node: TTreeNode); dynamic;
procedure DoEdited(AItem: TCustomViewItem; var S: WideString); override;
procedure DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean); override;
procedure DoGetImageIndex(item: TCustomViewItem); override;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
function GetDropTarget: TTreeNode;
procedure Expand(Node: TTreeNode); dynamic;
procedure HookEvents; override;
procedure ImageListChanged; override;
procedure Init(ANodeClass: TTreeNodeClass); virtual;
procedure InitWidget; override;
function IsCustomDrawn: Boolean; override;
procedure Loaded; override;
procedure RestoreWidgetState; override;
procedure SaveWidgetState; override;
property AutoExpand: Boolean read FAutoExpand write SetAutoExpand default False;
property ItemMargin: Integer read FItemMargin write SetItemMargin default 1;
property Items: TTreeNodes read FTreeNodes write SetItems;
property ShowButtons: Boolean read FShowButtons write SetShowButtons default True;
property SortType: TSortType read FSortType write SetSortType default stNone;
property OnChange: TTVChangedEvent read FOnChange write FOnChange;
property OnChanging: TTVChangingEvent read FOnChanging write FOnChanging;
property OnCollapsed: TTVExpandedEvent read FOnCollapsed write FOnCollapsed;
property OnCollapsing: TTVCollapsingEvent read FOnCollapsing write FOnCollapsing;
property OnDeletion: TTVExpandedEvent read FOnDeletion write FOnDeletion;
property OnEdited: TTVEditedEvent read FOnEdited write FOnEdited;
property OnEditing: TTVEditingEvent read FOnEditing write FOnEditing;
property OnExpanding: TTVExpandingEvent read FOnExpanding write FOnExpanding;
property OnExpanded: TTVExpandedEvent read FOnExpanded write FOnExpanded;
property OnGetImageIndex: TTVExpandedEvent read FOnGetImageIndex
write FOnGetImageIndex;
property OnGetSelectedIndex: TTVExpandedEvent read FOnGetSelectedIndex
write FOnGetSelectedIndex;
property OnInsert: TTVDeletedEvent read FOnInsert write FOnInsert;
property OnItemClick: TTVItemClickEvent read FOnItemClick write FOnItemClick;
property OnItemDoubleClick: TTVItemDoubleClickEvent read FOnItemDoubleClick
write SetOnItemDoubleClick;
property OnItemEnter: TTVItemEnterEvent read FOnItemEnter write SetOnItemEnter;
property OnItemExitViewportEnter: TTVItemExitViewportEnterEvent
read FOnItemExitViewportEnter write SetOnItemExitViewportEnter;
property OnItemMouseDown: TTVButtonDownEvent read FOnMouseDown
write SetOnMouseDown;
property OnViewPortMouseDown: TTVViewportButtonDownEvent
read FOnViewportMouseDown write SetOnViewportButtonDown;
public
constructor Create(AOwner: TComponent); overload; override;
constructor Create(AOwner: TComponent; ANodeClass: TTreeNodeClass); reintroduce; overload;
destructor Destroy; override;
function AlphaSort: Boolean;
procedure FullCollapse;
procedure FullExpand;
function GetNodeAt(X, Y: Integer): TTreeNode;
procedure LoadFromFile(const FileName: string);
procedure LoadFromStream(Stream: TStream);
procedure SaveToFile(const FileName: string);
procedure SaveToStream(Stream: TStream);
procedure SelectAll(Select: Boolean);
property DropTarget: TTreeNode read GetDropTarget;
property Selected: TTreeNode read GetSelected write SetSelected;
property TopItem: TTreeNode read GetTopItem write SetTopItem;
end;
{ TTreeView }
TTreeView = class(TCustomTreeView)
{$IF not (defined(LINUX) and defined(VER140))}
private
function GetSelCount: Integer;
{$IFEND}
public
property SortColumn;
published
property Align;
property Anchors;
property AutoExpand default False;
property BorderStyle default bsSunken3d;
property Color;
property ColumnClick default True;
property ColumnMove default True;
property ColumnResize default True;
property Columns;
property Constraints;
property DragMode;
property Enabled;
property Font;
property Height;
property Hint;
property Images;
property ItemMargin;
property Items;
property Indent;
property MultiSelect default False;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property RowSelect;
{$IF defined(LINUX) and defined(VER140)}
property SelectionCount: Integer read FSelCount default 0;
{$ELSE}
property SelectionCount: Integer read GetSelCount default 0;
{$IFEND}
property ShowColumnHeaders;
property ShowColumnSortIndicators;
property ShowButtons;
property ShowHint;
property Sorted default False;
property SortType;
property TabOrder;
property TabStop;
property Visible;
property Width;
property OnChange;
property OnChanging;
property OnClick;
property OnCollapsed;
property OnCollapsing;
property OnColumnClick;
property OnColumnDragged;
property OnColumnResize;
property OnContextPopup;
property OnCustomDrawBranch;
property OnCustomDrawItem;
property OnCustomDrawSubItem;
property OnDblClick;
property OnDeletion;
property OnDragDrop;
property OnDragOver;
property OnEdited;
property OnEditing;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnExpanding;
property OnExpanded;
property OnGetImageIndex;
property OnGetSelectedIndex;
property OnInsert;
property OnItemClick;
property OnItemDoubleClick;
property OnItemEnter;
property OnItemExitViewportEnter;
property OnKeyDown;
property OnKeyPress;
property OnKeyString;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
property OnItemMouseDown;
property OnViewPortMouseDown;
end;
{ TIconView }
TArrangement = (arLeftToRight, arTopToBottom);
TResizeMode = (rmFixed, rmAdjust);
TItemTextPos = (itpBottom, itpRight);
TCustomIconView = class;
TIconViewItems = class;
TIconView = class;
TIconViewItem = class(TPersistent)
private
FOwner: TIconViewItems;
FDestroying: Boolean;
FImageIndex: TImageIndex;
FStates: TItemStates;
FAllowRename: Boolean;
FCaption: WideString;
FSelectable: Boolean;
procedure SetAllowRename(const Value: Boolean);
function GetHandle: QIconViewItemH;
procedure SetCaption(const Value: WideString);
function GetIndex: Integer;
function GetSelected: Boolean;
procedure SetSelected(const Value: Boolean);
procedure SetSelectable(const Value: Boolean);
function IconViewValid: Boolean;
procedure UpdateImage;
procedure SetImageIndex(const Value: TImageIndex);
procedure SetStates(const Value: TItemStates);
function GetIconView: TCustomIconView;
function GetLeft: Integer;
function GetTop: Integer;
function GetWidth: Integer;
function GetHeight: Integer;
protected
FHandle: QIconViewItemH;
procedure CreateWidget(AfterItem: TIconViewItem);
procedure InitWidget;
procedure DestroyWidget;
function HandleAllocated: Boolean;
function IsEqual(AItem: TIconViewItem): Boolean;
property IconView: TCustomIconView read GetIconView;
public
constructor Create(AOwner: TIconViewItems; AfterItem: TIconViewItem = nil);
destructor Destroy; override;
function BoundingRect: TRect;
function IconRect: TRect;
procedure MakeVisible;
procedure Move(const Pt: TPoint);
procedure MoveBy(const Pt: TPoint);
procedure Repaint;
function TextRect: TRect;
property AllowRename: Boolean read FAllowRename write SetAllowRename
default True;
property Caption: WideString read FCaption write SetCaption;
property Handle: QIconViewItemH read GetHandle;
property Height: Integer read GetHeight;
property ImageIndex: TImageIndex read FImageIndex write SetImageIndex;
property Index: Integer read GetIndex;
property Left: Integer read GetLeft;
property Selectable: Boolean read FSelectable write SetSelectable
default True;
property Selected: Boolean read GetSelected write SetSelected;
property States: TItemStates read FStates write SetStates;
property Top: Integer read GetTop;
property Width: Integer read GetWidth;
end;
{ TiconViewItems }
TIconViewItemClass = class of TIconViewItem;
TIconViewItems = class(TPersistent)
private
FOwner: TCustomIconView;
FIconViewItemClass: TIconViewItemClass;
FUpdateCount: Integer;
FItems: TObjectList;
protected
procedure DefineProperties(Filer: TFiler); override;
function FindItem(ItemH: QIconViewItemH): TIconViewItem;
function GetCount: Integer;
function GetItem(Index: Integer): TIconViewItem;
function IconViewHandle: QIconViewH;
procedure ReadData(Stream: TStream);
procedure SetItem(Index: Integer; AObject: TIconViewItem);
procedure SetUpdateState(Updating: Boolean); virtual;
procedure UpdateImages;
procedure WriteData(Stream: TStream);
public
constructor Create(AOwner: TCustomIconView); overload;
constructor Create(AOwner: TCustomIconView;
AItemClass: TIconViewItemClass); overload;
destructor Destroy; override;
function Add: TIconViewItem;
procedure BeginUpdate;
procedure Clear;
procedure Delete(Index: Integer);
procedure EndUpdate;
function IndexOf(Value: TIconViewItem): Integer;
function Insert(Index: Integer): TIconViewItem;
procedure SetItemClass(AItemClass: TIconViewItemClass);
property Count: Integer read GetCount;
property Item[Index: Integer]: TIconViewItem read GetItem write SetItem; default;
property Owner: TCustomIconView read FOwner;
end;
{ TIconOptions }
TIconArrangement = (iaTop, iaLeft);
TIconOptions = class(TPersistent)
private
FAutoArrange: Boolean;
FArrangement: TIconArrangement;
FWrapText: Boolean;
FIconView: TCustomIconView;
procedure SetArrangement(Value: TIconArrangement);
procedure SetAutoArrange(Value: Boolean);
procedure SetWrapText(Value: Boolean);
public
constructor Create(AOwner: TCustomIconView);
published
property Arrangement: TIconArrangement read FArrangement
write SetArrangement default ialeft;
property AutoArrange: Boolean read FAutoArrange write SetAutoArrange
default True;
property WrapText: Boolean read FWrapText write SetWrapText
default True;
end;
{ TCustomIconView }
TIVItemMouseEvent = procedure(Sender: TObject; Button: TMouseButton;
Item: TIconViewItem; const Pt: TPoint) of object;
TIVMouseEvent = procedure(Sender: TObject; Button: TMouseButton;
const Pt: TPoint) of object;
TIVItemEvent = procedure(Sender: TObject; Item: TIconViewItem) of object;
TIVSelectItemEvent = procedure(Sender: TObject; Item: TIconViewItem;
Selected: Boolean) of object;
TIVItemDoubleClickEvent = TIVItemEvent;
TIVItemExitViewportEnterEvent = TNotifyEvent;
TIVItemEnterEvent = TIVItemEvent;
TIVEditedEvent = procedure(Sender: TObject; Item: TIconViewItem;
const NewName: WideString) of object;
TIVItemClickEvent = procedure(Sender: TObject; Item: TIconViewItem) of object;
TIVViewportClickedEvent = TIVMouseEvent;
TIVChangeEvent = procedure (Sender: TObject; Item: TIconViewItem;
Change: TItemChange) of object;
TIVChangingEvent = procedure (Sender: TObject; Item: TIconViewItem;
Change: TItemChange; var AllowChange: Boolean) of object;
TCustomIconView = class(TFrameControl)
private
FItemsMovable: Boolean;
FMultiSelect: Boolean;
FResizeMode: TResizeMode;
FShowToolTips: Boolean;
FSort: Boolean;
FSpacing: Integer;
FSelCount: Integer;
FTextPosition: TItemTextPos;
FSortDirection: TSortDirection;
FItemHooks: QClxIconViewHooksH;
FIconViewItems: TIconViewItems;
FOnItemClicked: TIVItemClickEvent;
FOnItemDoubleClick: TIVItemDoubleClickEvent;
FOnItemEnter: TIVItemEnterEvent;
FOnItemExitViewportEnter: TIVItemExitViewportEnterEvent;
FOnEdited: TIVEditedEvent;
FOnItemChange: TIVChangeEvent;
FOnItemChanging: TIVChangingEvent;
FImages: TCustomImageList;
FImageChanges: TChangeLink;
FViewportHandle: QWidgetH;
FViewportHooks: QWidget_hookH;
FOnSelectItem: TIVSelectItemEvent;
FIconOptions: TIconOptions;
FSelected: TIconViewItem;
procedure OnImageChanges(Sender: TObject);
function GetHandle: QIconViewH;
procedure SetMultiSelect(const Value: Boolean);
procedure SetSpacing(const Value: Integer);
procedure SetTextPos(const Value: TItemTextPos);
procedure SetResizeMode(const Value: TResizeMode);
procedure SetShowToolTips(const Value: Boolean);
procedure SetIconViewItems(const Value: TIconViewItems);
procedure SetSort(const Value: Boolean);
procedure SetSortDirection(const Value: TSortDirection);
procedure SetItemsMovable(const Value: Boolean);
procedure DoItemClicked(item: QIconViewItemH); cdecl;
procedure DoItemDoubleClicked(item: QIconViewItemH); cdecl;
procedure DoItemEnter(item: QIconViewItemH); cdecl;
procedure DoViewportEnter; cdecl;
procedure DoEdited(item: QIconViewItemH; p2: PWideString); cdecl;
procedure ItemDestroyedHook(item: QIconViewItemH); cdecl;
procedure ChangingHook(item: QIconViewItemH; _type: TItemChange;
var Allow: Boolean); cdecl;
procedure ChangeHook(item: QIconViewItemH; _type: TItemChange); cdecl;
procedure SelectedHook(item: QIconViewItemH; Value: Boolean); cdecl;
procedure PaintCellHook(p: QPainterH; item: QIconViewItemH;
cg: QColorGroupH; var stage: Integer); cdecl;
procedure PaintFocusHook(p: QPainterH; item: QIconViewItemH;
cg: QColorGroupH; var stage: Integer); cdecl;
procedure SetOnItemClicked(const Value: TIVItemClickEvent);
procedure SetOnItemDoubleClick(const Value: TIVItemDoubleClickEvent);
procedure SetOnItemEnter(const Value: TIVItemEnterEvent);
procedure SetOnItemExitViewportEnter(const Value: TIVItemExitViewportEnterEvent);
procedure SetOnEdited(const Value: TIVEditedEvent);
procedure SetImages(const Value: TCustomImageList);
procedure SetSelected(const Value: TIconViewItem);
procedure SetIconOptions(const Value: TIconOptions);
protected
procedure BeginAutoDrag; override;
procedure ColorChanged; override;
procedure CreateWidget; override;
procedure DoChange(Item: TIconViewItem; Change: TItemChange); dynamic;
procedure DoChanging(Item: TIconViewItem; Change: TItemChange;
var AllowChange: Boolean); dynamic;
procedure HookEvents; override;
procedure ImageListChanged; dynamic;
procedure InitWidget; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
function ViewportHandle: QWidgetH;
procedure WidgetDestroyed; override;
property BorderStyle default bsSunken3d;
property Height default 97;
property IconOptions: TIconOptions read FIconOptions write SetIconOptions;
property Images: TCustomImageList read FImages write SetImages;
property Items: TIconViewItems read FIconViewItems write SetIconViewItems;
property ItemsMovable: Boolean read FItemsMovable write SetItemsMovable
default True;
property MultiSelect: Boolean read FMultiSelect write SetMultiSelect
default False;
property ParentColor default False;
property ResizeMode: TResizeMode read FResizeMode write SetResizeMode
default rmAdjust;
property SelCount: Integer read FSelCount;
property Selected: TIconViewItem read FSelected write SetSelected;
property ShowToolTips: Boolean read FShowToolTips write SetShowToolTips
default True;
property Sort: Boolean read FSort write SetSort default False;
property SortDirection: TSortDirection read FSortDirection
write SetSortDirection default sdAscending;
property Spacing: Integer read FSpacing write SetSpacing default 5;
property TabStop default True;
property TextPosition: TItemTextPos read FTextPosition write SetTextPos
default itpBottom;
property Width default 121;
property OnChange: TIVChangeEvent read FOnItemChange write FOnItemChange;
property OnChanging: TIVChangingEvent read FOnItemChanging
write FOnItemChanging;
property OnItemDoubleClick: TIVItemDoubleClickEvent read FOnItemDoubleClick
write SetOnItemDoubleClick;
property OnItemExitViewportEnter: TIVItemExitViewportEnterEvent
read FOnItemExitViewportEnter write SetOnItemExitViewportEnter;
property OnItemEnter: TIVItemEnterEvent read FOnItemEnter
write SetOnItemEnter;
property OnEdited: TIVEditedEvent read FOnEdited
write SetOnEdited;
property OnItemClicked: TIVItemClickEvent read FOnItemClicked
write SetOnItemClicked;
property OnSelectItem: TIVSelectItemEvent read FOnSelectItem
write FOnSelectItem;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Handle: QIconViewH read GetHandle;
procedure Clear;
procedure SelectAll(Select: Boolean);
function FindItemByText(const Str: WideString): TIconViewItem;
function FindItemByPoint(const Pt: TPoint): TIconViewItem;
function GetNextItem(StartItem: TIconViewItem; Direction: TSearchDirection;
States: TItemStates): TIconViewItem;
procedure RepaintItem(AItem: TIconViewItem);
procedure EnsureItemVisible(AItem: TIconViewItem);
function FindVisibleItem(First: Boolean; const ARect: TRect): TIconViewItem;
procedure UpdateControl;
procedure UpdateItems(FirstIndex, LastIndex: Integer);
end;
{ TIconView }
TIconView = class(TCustomIconView)
public
property SelCount;
property Selected;
published
property Align;
property Anchors;
property BorderStyle;
property Color;
property Constraints;
property DragMode;
property Height;
property Hint;
property IconOptions;
property Images;
property Items;
property ItemsMovable;
property MultiSelect;
property ParentColor;
property ParentShowHint;
property PopupMenu;
property ResizeMode;
property ShowHint;
property ShowToolTips;
property Sort;
property SortDirection;
property Spacing;
property TabOrder;
property TabStop;
property TextPosition;
property Width;
property Visible;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnItemDoubleClick;
property OnItemExitViewportEnter;
property OnItemEnter;
property OnEdited;
property OnItemClicked;
property OnKeyDown;
property OnKeyPress;
property OnKeyString;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnSelectItem;
property OnStartDrag;
end;
{ TToolBar }
TToolButtonStyle = (tbsButton, tbsCheck, tbsDropDown, tbsSeparator, tbsDivider);
TToolButtonState = (tbsChecked, tbsPressed, tbsEnabled, tbsHidden,
tbsIndeterminate, tbsWrap, tbsEllipses, tbsMarked);
TToolBar = class;
TToolButton = class;
{ TToolButtonActionLink }
TToolButtonActionLink = class(TControlActionLink)
protected
FClient: TToolButton;
procedure AssignClient(AClient: TObject); override;
function IsCheckedLinked: Boolean; override;
function IsImageIndexLinked: Boolean; override;
procedure SetChecked(Value: Boolean); override;
procedure SetImageIndex(Value: Integer); override;
end;
TToolButtonActionLinkClass = class of TToolButtonActionLink;
TToolButton = class(TCustomControl)
private
FAllowAllUp: Boolean;
FAutoSize: Boolean;
FDown: Boolean;
FGrouped: Boolean;
FMouseIn: Boolean;
FImageIndex: TImageIndex;
FIndeterminate: Boolean;
FMarked: Boolean;
FDropDownMenu: TPopupMenu;
FMenuDropped: Boolean;
FWrap: Boolean;
FStyle: TToolButtonStyle;
FUpdateCount: Integer;
FJustChecked: Boolean;
{ FShowCaption: Boolean; }
FCaption: TCaption;
function DropDownRect: TRect;
function GetIndex: Integer;
function IsCheckedStored: Boolean;
function IsImageIndexStored: Boolean;
function IsWidthStored: Boolean;
{ procedure ResizeButton; }
procedure SetAutoSize(Value: Boolean);
procedure SetDown(Value: Boolean);
procedure SetDropDownMenu(Value: TPopupMenu);
procedure SetGrouped(Value: Boolean);
procedure SetImageIndex(Value: TImageIndex);
procedure SetIndeterminate(Value: Boolean);
procedure SetMarked(Value: Boolean);
procedure SetStyle(Value: TToolButtonStyle);
procedure SetWrap(Value: Boolean);
procedure SetAllowAllUp(const Value: Boolean);
protected
FToolBar: TToolBar;
procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override;
procedure AssignTo(Dest: TPersistent); override;
procedure BeginUpdate; virtual;
procedure DoPaint(Canvas: TCanvas);
function DropDownWidth: Integer; virtual;
procedure EndUpdate; virtual;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
procedure InitWidget; override;
function IsEnabled: Boolean;
function GetActionLinkClass: TControlActionLinkClass; override;
function GetText: TCaption; override;
procedure MouseEnter(AControl: TControl); override;
procedure MouseLeave(AControl: TControl); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Paint; override;
procedure SetName(const Value: TComponentName); override;
procedure SetParent(const Value: TWidgetControl); override;
procedure SetText(const Value: TCaption); override;
procedure SetToolBar(AToolBar: TToolBar);
procedure ValidateContainer(AComponent: TComponent); override;
function WantKey(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; override;
public
constructor Create(AOwner: TComponent); override;
function CheckMenuDropDown: Boolean; dynamic;
procedure Click; override;
procedure ChangeBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
property Index: Integer read GetIndex;
property Toolbar: TToolBar read FToolBar write SetToolBar;
published
property Style: TToolButtonStyle read FStyle write SetStyle default tbsButton;
property Action;
property AllowAllUp: Boolean read FAllowAllUp write SetAllowAllUp default False;
property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
property Caption;
property Down: Boolean read FDown write SetDown stored IsCheckedStored default False;
property DragMode;
property DropDownMenu: TPopupMenu read FDropDownMenu write SetDropDownMenu;
property Enabled;
property Grouped: Boolean read FGrouped write SetGrouped default False;
property ImageIndex: TImageIndex read FImageIndex write SetImageIndex stored IsImageIndexStored default -1;
property Indeterminate: Boolean read FIndeterminate write SetIndeterminate default False;
property Marked: Boolean read FMarked write SetMarked default False;
property ParentShowHint;
property PopupMenu;
{ property ShowCaption: Boolean read FShowCaption write SetShowCaption; }
property Wrap: Boolean read FWrap write SetWrap default False;
property ShowHint;
property Visible;
property Width stored IsWidthStored;
property OnClick;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
{ TToolBar }
TGroupChangeReason = (gcDownState, gcAllowAllUp);
TToolBar = class(TCustomControl)
private
FButtonWidth: Integer;
FButtonHeight: Integer;
FWrapable: Boolean;
FAutoSize: Boolean;
FBorderWidth: TBorderWidth;
FControls: TList;
FEdgeBorders: TEdgeBorders;
FEdgeOuter: TEdgeStyle;
FEdgeInner: TEdgeStyle;
FIndent: Integer;
FFlat: Boolean;
FList: Boolean;
FShowCaptions: Boolean;
FHotImages: TCustomImageList;
FImages: TCustomImageList;
FDisabledImages: TCustomImageList;
FImageWidth: Integer;
FImageHeight: Integer;
FImageChangeLink: TChangeLink;
FResizeCount: Integer;
FRightEdge: Integer;
procedure AdjustSize; reintroduce;
procedure DoPaint(ACanvas: TCanvas);
function EdgeSpacing(Edge: TEdgeBorder): Integer;
function GetControl(Index: Integer): TControl;
procedure GroupChange(Requestor: TToolButton; Reason: TGroupChangeReason);
function HasImages: Boolean;
procedure ImageListChange(Sender: TObject);
procedure InternalSetButtonWidth(const Value: Integer; RestrictSize: Boolean);
function LastControl: TControl;
procedure ResizeButtons(Button: TToolButton);
procedure SetWrapable(const Value: Boolean);
procedure SetButtonHeight(const Value: Integer);
procedure SetButtonWidth(const Value: Integer);
procedure SetAutoSize(const Value: Boolean);
procedure SetBorderWidth(const Value: TBorderWidth);
procedure SetEdgeBorders(const Value: TEdgeBorders);
procedure SetEdgeInner(const Value: TEdgeStyle);
procedure SetEdgeOuter(const Value: TEdgeStyle);
procedure SetIndent(const Value: Integer);
procedure SetFlat(const Value: Boolean);
procedure SetShowCaptions(const Value: Boolean);
procedure SetDisabledImages(const Value: TCustomImageList);
procedure SetHotImages(const Value: TCustomImageList);
procedure SetImages(const Value: TCustomImageList);
procedure SetList(const Value: Boolean);
protected
procedure ControlsAligned; override;
procedure ControlsListChanged(Control: TControl; Inserting: Boolean); override;
function CustomAlignInsertBefore(C1, C2: TControl): Boolean; override;
procedure CustomAlignPosition(Control: TControl; var NewLeft, NewTop, NewWidth,
NewHeight: Integer; var AlignRect: TRect); override;
procedure DoResize;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
procedure FontChanged; override;
procedure InitWidget; override;
procedure AdjustClientRect(var Rect: TRect); override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ButtonCount: Integer;
function ControlCount: Integer;
procedure Invalidate; override;
property Controls[Index: Integer]: TControl read GetControl;
published
property Align default alTop;
property Anchors;
property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
property Bitmap;
property BorderWidth: TBorderWidth read FBorderWidth write SetBorderWidth default 0;
property ButtonHeight: Integer read FButtonHeight write SetButtonHeight default 22;
property ButtonWidth: Integer read FButtonWidth write SetButtonWidth default 23;
property Caption;
property Color;
property Constraints;
property DisabledImages: TCustomImageList read FDisabledImages write SetDisabledImages;
property DragMode;
property EdgeBorders: TEdgeBorders read FEdgeBorders write SetEdgeBorders default [ebTop];
property EdgeInner: TEdgeStyle read FEdgeInner write SetEdgeInner default esRaised;
property EdgeOuter: TEdgeStyle read FEdgeOuter write SetEdgeOuter default esLowered;
property Enabled;
property Flat: Boolean read FFlat write SetFlat default False;
property Font;
property Height default 32;
property HotImages: TCustomImageList read FHotImages write SetHotImages;
property Images: TCustomImageList read FImages write SetImages;
property Indent: Integer read FIndent write SetIndent default 1;
property List: Boolean read FList write SetList default False;
property Masked default False;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowCaptions: Boolean read FShowCaptions write SetShowCaptions default False;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property Wrapable: Boolean read FWrapable write SetWrapable default True;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDrag;
end;
{ Utility functions }
function DefaultMimeFactory: TMimeSourceFactory;
procedure SetDefaultMimeFactory(Value: TMimeSourceFactory);
procedure CheckRange(AMin, AMax: Integer);
implementation
uses
QConsts, QActnList, Math, QForms;
const
STATUSBAR_HEIGHT = 19;
SIZE_GRIP_SIZE = 15;
SCROLL_BUTTON_WIDTH = 17;
SELECTED_TAB_SIZE_DELTA = 2;
FRAME_BORDER_WIDTH = 2;
TAB_FLAT_BORDER = 4;
STATUS_PANEL_SPACER = 2;
TabDefaultHeightMap: array [TTabStyle] of Integer = (19, 24, 25, 18);
TabDefaultWidthMap: array [TTabStyle] of Integer = (45, 45, 53, 40);
TabDefaultBorderWidthMap: array [TTabStyle] of Integer = (2, 4, 6, 0);
TabDefaultTextOffsetMap: array [TTabStyle] of Integer = (-1, 1, 1, 0);
TabButtonsLeftMap: array [TTabStyle] of Integer = (SELECTED_TAB_SIZE_DELTA, 0, -4, 0);
FrameMap: array [Boolean] of Integer =
(Integer(QFrameShape_NoFrame) or Integer(QFrameShadow_Plain),
(Integer(QFrameShape_PopUpPanel) or Integer(QFrameShadow_Raised)));
BevelShadowStyle: array [TStatusPanelBevel] of QControls.TBorderStyle =
(bsNone, bsSunkenPanel, bsRaisedPanel);
{ Helper routines }
function ButtonToMouseButton(Button: Integer): TMouseButton;
begin
case Button of
Integer(ButtonState_MidButton): Result := mbMiddle;
Integer(ButtonState_RightButton): Result := mbRight;
else
Result := mbLeft;
end;
end;
procedure CheckRange(AMin, AMax: Integer);
begin
if (AMax < AMin) or (AMin > AMax) then
raise ERangeException.Create(Format(SInvalidRangeError,[AMin, AMax]));
end;
{ TProgressBar }
constructor TProgressBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := 150;
Height := 18;
Max := 100;
FStep := 10;
FFillColor := clHighlight;
ControlStyle := ControlStyle - [csSetCaption];
end;
procedure TProgressBar.FontChanged;
begin
inherited;
FTextColor := Font.Color;
end;
function TProgressBar.GetText: TCaption;
begin
Result := FText;
end;
function TProgressBar.AdjustToParent(const Rect: TRect): TRect;
var
H, W: Integer;
begin
H := Rect.Bottom - Rect.Top;
W := Rect.Right - Rect.Left;
Result.Top := Rect.Top + Top;
Result.Left := Rect.Left + Left;
Result.Right := Result.Left + W;
Result.Bottom := Result.Top + H;
end;
procedure TProgressBar.EraseText(const AText: WideString; BackgroundColor : TColor);
var
Rect: TRect;
PrevBrush: TBrushRecall;
begin
PrevBrush := TBrushRecall.Create(Canvas.Brush);
try
Rect := CalcTextRect(ClientRect, ClientRect, AText);
Canvas.Brush.Color := BackgroundColor;
Canvas.FillRect(Rect);
finally
PrevBrush.Free;
end;
end;
function TProgressBar.CalcTextRect(Rect: TRect; const BoundingRect: TRect;
const AText: WideString): TRect;
const
cTextFlags = Integer(AlignmentFlags_AlignHCenter)
or Integer(AlignmentFlags_AlignVCenter);
begin
Canvas.TextExtent(AText, Rect, cTextFlags);
IntersectRect(Result, Rect, BoundingRect);
end;
procedure TProgressBar.InternalPaint;
const
cTextFlags = Integer(AlignmentFlags_AlignHCenter)
or Integer(AlignmentFlags_AlignVCenter);
cTextBorder = 4;
cSectionSpacer = 2;
var
Rect: TRect;
PrevRect: TRect;
TextRect: TRect;
PrevPen: TPenRecall;
PrevBrush: TBrushRecall;
PrevFont: TFontRecall;
function CalcSectionSize(const BoundingRect: TRect): Integer;
begin
if Orientation = pbHorizontal then
Result := 2 * (BoundingRect.Bottom - BoundingRect.Top - 1) div 3
else
Result := 2 * (BoundingRect.Right - BoundingRect.Left - 1) div 3;
end;
procedure DrawSpacer(Rect: TRect; SectionSize: Integer);
var
PrevBrush: TBrushRecall;
PrevPen: TPenRecall;
begin
if not Transparent then
begin
PrevBrush := nil;
PrevPen := TPenRecall.Create(Canvas.Pen);
try
PrevBrush := TBrushRecall.Create(Canvas.Brush);
Canvas.Pen.Color := Color;
Canvas.Pen.Width := 1;
Canvas.Brush.Style := bsClear;
InflateRect(Rect, 1, 1);
Canvas.Rectangle(Rect);
finally
PrevBrush.Free;
PrevPen.Free;
end;
end;
end;
function SectionCount(const ARect: TRect; FillArea: TRect; SectionSize: Integer): Integer;
var
TotalPixels: Integer;
begin
if Orientation = pbHorizontal then
TotalPixels := FillArea.Right - ARect.Left
else
TotalPixels := ARect.Bottom - FillArea.Top;
Result := ((TotalPixels - cSectionSpacer) div
(CalcSectionSize(ARect) + cSectionSpacer)) + 1;
end;
procedure DrawSections(BoundingRect: TRect; var FillArea: TRect);
var
SectionSize: Integer;
Sections: Integer;
I: Integer;
begin
InflateRect(FillArea, -1, -1);
InflateRect(BoundingRect, -1, -1);
SectionSize := CalcSectionSize(BoundingRect);
{ Draw an empty the progress bar }
if Position = Min then
begin
if not Transparent then
begin
Canvas.Brush.Color := Color;
Canvas.FillRect(BoundingRect);
end;
InflateRect(FillArea, 1, 1);
Exit;
end;
if SectionSize <> 0 then
begin
Sections := SectionCount(BoundingRect, FillArea, SectionSize);
if FSections <> Sections then
begin
FSections := Sections;
{ Draw each section }
for I := 0 to Sections - 1 do
begin
if Orientation = pbHorizontal then
begin
FillArea.Left := BoundingRect.Left + (I * (SectionSize + cSectionSpacer));
FillArea.Right := FillArea.Left + SectionSize;
FillArea.Right := Math.Min(FillArea.Right, BoundingRect.Right - 1);
Canvas.FillRect(FillArea);
DrawSpacer(FillArea, SectionSize);
Inc(FillArea.Right, cSectionSpacer);
FillArea.Left := FillArea.Right;
end else
begin
FillArea.Bottom := BoundingRect.Bottom - (I * (SectionSize + cSectionSpacer));
FillArea.Top := FillArea.Bottom - SectionSize;
FillArea.Top := Math.Max(FillArea.Top, BoundingRect.Top + 1);
Canvas.FillRect(FillArea);
DrawSpacer(FillArea, SectionSize);
Dec(FillArea.Top, cSectionSpacer);
FillArea.Bottom := FillArea.Top;
end;
end;
if Orientation = pbHorizontal then
Dec(FillArea.Right, cSectionSpacer)
else
Inc(FillArea.Top, cSectionSpacer);
end else
if Orientation = pbHorizontal then
FillArea.Right := BoundingRect.Left + (Sections * (SectionSize + cSectionSpacer))
else
FillArea.Top := BoundingRect.Bottom - (Sections * (SectionSize + cSectionSpacer));
end;
InflateRect(FillArea, 1, 1);
end;
function PaintProgress(var ARect: TRect): Boolean;
var
TotalPixels: Integer;
Rect: TRect;
begin
Result := False;
PrevRect := ARect;
Rect := ARect;
Canvas.SetClipRect(AdjustToParent(ARect));
try
if (FTotalSteps > 0) then
begin
{ Calculate the size of the fill area in pixels based on the position }
case Orientation of
pbHorizontal:
begin
TotalPixels := ARect.Right - ARect.Left;
ARect.Right := ARect.Left + ((ScalePosition(Position) * TotalPixels) div FTotalSteps);
ARect.Right := Math.Min(ARect.Right, ClientWidth);
end;
pbVertical:
begin
TotalPixels := ARect.Bottom - ARect.Top;
ARect.Top := ARect.Bottom - ((ScalePosition(Position) * TotalPixels) div FTotalSteps);
ARect.Top := Math.Min(ARect.Top, ClientHeight);
end;
end;
if EqualRect(FFillArea, ARect) then Exit;
FFillArea := ARect;
Result := True;
Canvas.Brush.Color := FillColor;
{ Draw the progress }
if Smooth then
Canvas.FillRect(ARect)
else
DrawSections(PrevRect, ARect);
{ Calculate the rest of the non-progress area if not transparent }
if not Transparent then
begin
Rect := PrevRect;
if Orientation = pbHorizontal then
begin
Rect.Left := ARect.Right;
if Rect.Left > Rect.Right then Rect.Left := Rect.Right;
end else
begin
Rect.Bottom := ARect.Top;
if Rect.Bottom < Rect.Top then Rect.Bottom := Rect.Top;
end;
end;
end;
if not Transparent then
begin
Canvas.Brush.Color := Color;
Canvas.FillRect(Rect);
end;
finally
Canvas.ResetClipRegion;
end;
end;
procedure XORText(const BoundingRect: TRect; FillRect, TextRect: TRect;
const Caption: WideString; TextFlags: Integer);
procedure DrawText(BackgroundColor, FontColor: TColor);
begin
EraseText(FPrevText, BackgroundColor);
Canvas.Brush.Color := BackgroundColor;
Canvas.FillRect(TextRect);
Canvas.Font.Color := FontColor;
Canvas.TextRect(TextRect, TextRect.Left, TextRect.Top, Caption, cTextFlags);
end;
begin
{ Qt doesn't handle XORing text very well in windows. So instead we will
paint the text twice with different colors for inside and outside of
the fill area. By using SetClipRect we can achieve an XORed look.
}
try
if Transparent then Canvas.Brush.Style := bsClear;
if Orientation = pbHorizontal then
begin
FillRect.Left := BoundingRect.Left;
TextRect.Top := BoundingRect.Top;
TextRect.Bottom := BoundingRect.Bottom;
if (FillRect.Right > TextRect.Left) and (FillRect.Right < TextRect.Right) then
Canvas.SetClipRect(AdjustToParent(FillRect));
{ Draw the text that is inside of the fill area }
if FillRect.Right > TextRect.Left then
DrawText(FillColor, clHighlightText);
if FillRect.Right < TextRect.Right then
begin
{ Draw the text that is outside of the fill area }
if (FillRect.Right > TextRect.Left) then
begin
Rect := BoundingRect;
Rect.Left := FillRect.Right;
Canvas.SetClipRect(AdjustToParent(Rect));
end;
DrawText(Color, FTextColor);
end;
end else
begin
FillRect.Bottom := BoundingRect.Bottom;
TextRect.Right := BoundingRect.Right;
TextRect.Left := BoundingRect.Left;
if (FillRect.Top > TextRect.Top) and (FillRect.Top < TextRect.Bottom) then
Canvas.SetClipRect(AdjustToParent(FillRect));
{ Draw the text that is inside of the fill area }
if FillRect.Top < TextRect.Bottom then
DrawText(FillColor, clHighlightText);
if FillRect.Top > TextRect.Top then
begin
{ Draw the text that is outside of the fill area }
if (FillRect.Top < TextRect.Bottom) then
begin
Rect := BoundingRect;
Rect.Bottom := FillRect.Top;
Canvas.SetClipRect(AdjustToParent(Rect));
end;
DrawText(Color, FTextColor);
end;
end;
finally
Canvas.ResetClipRegion;
end;
end;
begin
Canvas.Start;
PrevPen := nil;
PrevFont := nil;
PrevBrush := TBrushRecall.Create(Canvas.Brush);
try
PrevFont := TFontRecall.Create(Canvas.Font);
PrevPen := TPenRecall.Create(Canvas.Pen);
Canvas.Brush.Style := bsSolid;
Rect := Classes.Rect(0, 0, Width, Height);
{ Adjust for the frame }
InflateRect(Rect, -1, -1);
{ Adjust for the BorderWidth }
InflateRect(Rect, -BorderWidth, -BorderWidth);
if IsRectEmpty(Rect) then Exit;
TextRect := Rect;
{ Adjust the fill area depending on where the text will be displayed }
if not Smooth then
begin
if ShowCaption and (Caption <> '') then
begin
if Orientation = pbHorizontal then
begin
Rect.Right := Rect.Right - (Canvas.TextWidth(Caption) + (cTextBorder * 2));
if Rect.Right < Rect.Left then Rect.Right := Rect.Left;
TextRect.Left := Rect.Right;
end else
begin
Rect.Top := Rect.Top + Canvas.TextHeight(Caption);
if Rect.Top > Rect.Bottom then Rect.Top := Rect.Bottom;
TextRect.Bottom := Rect.Top;
end;
end;
end;
{ Paint the progress area }
if PaintProgress(Rect) then
{ Draw the text }
if ShowCaption and (Caption <> '')then
begin
Canvas.Font := Font;
Canvas.Font.Color := FTextColor;
if Smooth then
begin
TextRect := CalcTextRect(TextRect, PrevRect, Caption);
XORText(PrevRect, Rect, TextRect, Caption, cTextFlags);
Exit;
end else
begin
Canvas.SetClipRect(AdjustToParent(TextRect));
if not Transparent then
begin
Canvas.Brush.Color := Color;
Canvas.FillRect(TextRect);
end else
Canvas.Brush.Style := bsClear;
end;
Canvas.TextRect(TextRect, TextRect.Left, TextRect.Top, Caption, cTextFlags);
end;
finally
PrevPen.Free;
PrevFont.Free;
PrevBrush.Free;
Canvas.Stop;
end;
end;
procedure TProgressBar.InternalDrawFrame;
var
R: TRect;
procedure DrawBorder(ARect: TRect);
const
BorderWidthAdj: array[Boolean] of Integer = (0,1);
var
PrevBrush: TBrushRecall;
PrevPen: TPenRecall;
i : Integer;
begin
with Canvas do
begin
PrevBrush := nil;
PrevPen := TPenRecall.Create(Pen);
try
PrevBrush := TBrushRecall.Create(Brush);
Brush.Style := bsClear;
if Transparent then
Pen.Style := psClear
else
Pen.Style := psSolid;
Pen.Color := Color;
for i := 1 to BorderWidth + BorderWidthAdj[Smooth] do
if not IsRectEmpty(ARect) then
begin
Rectangle(ARect);
InflateRect(ARect, -1, -1);
end;
finally
PrevPen.Free;
PrevBrush.Free;
end;
end;
end;
begin
R := Rect(0 , 0, Width, Height);
{ Draw frame }
DrawEdge(Canvas, R, esNone, esLowered, [ebLeft, ebTop, ebBottom, ebRight]);
InflateRect(R, -1, -1);
DrawBorder(R);
end;
function TProgressBar.ScalePosition(Value: Integer): Integer;
begin
{ Adjust the Position to fit in the scale of 0 to FTotalSteps }
Result := Abs(Value - Min);
end;
procedure TProgressBar.SetBorderWidth(const Value: TBorderWidth);
begin
if FBorderWidth <> Value then
begin
FBorderWidth := Value;
RequestAlign;
Invalidate;
end;
end;
procedure TProgressBar.SetFillColor(const Value: TColor);
begin
if FFillColor <> Value then
begin
FFillColor := Value;
Invalidate;
end;
end;
procedure TProgressBar.Paint;
var
PrevBrush: TBrushRecall;
PrevPen: TPenRecall;
begin
PrevBrush := nil;
PrevPen := TPenRecall.Create(Canvas.Pen);
try
PrevBrush := TBrushRecall.Create(Canvas.Brush);
FFillArea := Rect(-1, -1, -1, -1);
FSections := -1;
InternalDrawFrame;
InternalPaint;
finally
PrevPen.Free;
PrevBrush.Free;
end;
end;
procedure TProgressBar.SetText(const Value: TCaption);
begin
if FText <> Value then
begin
FText := Value;
Invalidate;
end;
end;
procedure TProgressBar.Changing(var Text: WideString; NewPosition: Integer);
begin
if Assigned(FOnChanging) then
FOnChanging(Self, Text, NewPosition);
end;
procedure TProgressBar.SetMax(const Value: Integer);
begin
if FMax <> Value then
begin
SetRange(Min, Value);
if Value < Position then
FPosition := Value;
FMax := Value;
Invalidate;
end;
end;
procedure TProgressBar.SetMin(const Value: Integer);
begin
if FMin <> Value then
begin
SetRange(Value, Max);
FPosition := Value;
FMin := Value;
Invalidate;
end;
end;
procedure TProgressBar.SetOrientation(const Value: TProgressBarOrientation);
begin
if FOrientation <> Value then
begin
FOrientation := Value;
Invalidate;
end;
end;
procedure TProgressBar.SetPosition(Value: Integer);
var
Text: WideString;
begin
if FPosition <> Value then
begin
FPosition := Value;
if (FPosition > Max) or (FPosition < Min) then
begin
if WrapRange then
begin
if FTotalSteps > 0 then
if Value > Max then
FPosition := (ScalePosition(Value) mod (FTotalSteps + 1)) + Min
else
FPosition := Max - (ScalePosition(Value) mod (FTotalSteps + 1)) + 1
else
FPosition := Value;
end else
if FPosition > Max then FPosition := Max else FPosition := Min;
end;
Text := Caption;
FPrevText := Text;
Changing(Text, Position);
if Caption <> Text then
FText := Text;
if (Transparent or ((Position = 0) and (Value <= Max))) then
Invalidate
else
if (Parent <> nil) and Visible then
InternalPaint;
end;
end;
procedure TProgressBar.SetRange(const AMin, AMax: Integer);
begin
if not (csLoading in ComponentState) then
CheckRange(AMin, AMax);
FTotalSteps := AMax - AMin;
end;
procedure TProgressBar.SetShowCaption(const Value: Boolean);
begin
if FShowCaption <> Value then
begin
FShowCaption := Value;
Invalidate;
end;
end;
procedure TProgressBar.SetSmooth(const Value: Boolean);
begin
if FSmooth <> Value then
begin
FSmooth := Value;
Invalidate;
end;
end;
procedure TProgressBar.SetStep(const Value: Integer);
begin
if FStep <> Value then
FStep := Value;
end;
procedure TProgressBar.SetTransparent(const Value: Boolean);
begin
if FTransparent <> Value then
begin
FTransparent := Value;
Invalidate;
end;
end;
procedure TProgressBar.StepBy(Delta: Integer);
begin
Position := Position + Delta;
end;
procedure TProgressBar.StepIt;
begin
WrapRange := True;
try
Position := Position + FStep;
finally
WrapRange := False;
end;
end;
{ TTrackBar }
procedure TTrackBar.Changed;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
constructor TTrackBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
{ Height and Width set initally for Vertical so that ChangeAspectRatio in
SetOrientation can change to the proper aspect ratio for Horizontal when
called in InitWidget }
Width := 45;
Height := 150;
FOrientation := trVertical;
TabStop := True;
FTickMarks := tmBottomRight;
ControlStyle := ControlStyle - [csDoubleClicks];
InputKeys := [ikArrows];
end;
procedure TTrackBar.CreateWidget;
var
Method: TMethod;
begin
FHandle := QClxSlider_create(ParentWidget, PChar(Name), Method);
Hooks := QSlider_hook_create(FHandle);
end;
procedure TTrackBar.InitWidget;
begin
inherited InitWidget;
LineSize := 1;
PageSize := 2;
Frequency := 1;
Min := 0;
Max := 10;
TickMarks := tmBottomRight;
TickStyle := tsAuto;
Orientation := trHorizontal;
QWidget_setFocusPolicy(FHandle, QWidgetFocusPolicy_ClickFocus);
UpdateSettings;
// SetRange(Min, Max);
end;
procedure TTrackBar.HookEvents;
var
Method: TMethod;
begin
QSlider_valueChanged_Event(Method) := ValueChangedHook;
QSlider_hook_hook_valueChanged(QSlider_hookH(Hooks), Method);
QSlider_sliderMoved_Event(Method) := ValueChangedHook;
QSlider_hook_hook_valueChanged(QSlider_hookH(Hooks), Method);
inherited HookEvents;
end;
procedure TTrackBar.Loaded;
begin
inherited Loaded;
if Orientation = trVertical then
ChangeAspectRatio;
SetRange(FMin, FMax);
end;
procedure TTrackBar.ChangeAspectRatio;
begin
SetBounds(Left, Top, Height, Width);
end;
function TTrackBar.GetHandle: QClxSliderH;
begin
HandleNeeded;
Result := QClxSliderH(FHandle);
end;
function TTrackBar.GetOrientation: TTrackBarOrientation;
begin
Result := TTrackBarOrientation(QSlider_orientation(Handle));
end;
procedure TTrackBar.SetFrequency(const Value: Integer);
begin
{ Note: if Frequency is set to 0 then the QT determines the Tick interval from
the LineSize. }
QSlider_setTickInterval(Handle, Value);
end;
procedure TTrackBar.SetLineSize(const Value: Integer);
begin
QRangeControl_setSteps(RangeControl, Value, PageSize);
end;
procedure TTrackBar.SetMax(const Value: Integer);
begin
if (csLoading in ComponentState) then
SetRange(FMin, Value)
else
SetRange(Min, Value);
end;
procedure TTrackBar.SetMin(const Value: Integer);
begin
if (csLoading in ComponentState) then
SetRange(Value, FMax)
else
SetRange(Value, Max);
end;
procedure TTrackBar.SetOrientation(const Value: TTrackBarOrientation);
begin
if FOrientation <> Value then
begin
FOrientation := Value;
QSlider_setOrientation(Handle, Qt.Orientation(Value));
ChangeAspectRatio;
UpdateSettings;
end;
end;
procedure TTrackBar.SetPageSize(const Value: Integer);
begin
QRangeControl_setSteps(RangeControl, LineSize, Value);
end;
procedure TTrackBar.SetPosition(const Value: Integer);
begin
QRangeControl_setValue(RangeControl, Value);
end;
procedure TTrackBar.SetRange(const AMin, AMax: Integer);
begin
FMin := AMin;
FMax := AMax;
if not HandleAllocated or (csLoading in ComponentState) then
Exit;
try
CheckRange(AMin, AMax);
except
FMin := Min;
FMax := Max;
raise;
end;
QRangeControl_setRange(RangeControl, FMin, FMax);
Invalidate;
end;
procedure TTrackBar.SetTickMarks(const Value: TTickMark);
begin
if FTickMarks <> Value then
begin
FTickMarks := Value;
UpdateSettings;
end;
end;
procedure TTrackBar.SetTickStyle(const Value: TTickStyle);
begin
if FTickStyle <> Value then
begin
FTickStyle := Value;
case FTickStyle of
tsAuto: UpdateSettings;
tsNone: QSlider_setTickmarks(Handle, QSliderTickSetting_NoMarks);
end;
end;
end;
function TTrackBar.GetFrequency: Integer;
begin
Result := QSlider_tickInterval(Handle);
end;
function TTrackBar.GetRangeControl: QRangeControlH;
begin
Result := QSlider_to_QRangeControl(Handle);
end;
function TTrackBar.GetLineSize: Integer;
begin
Result := QRangeControl_lineStep(RangeControl);
end;
function TTrackBar.GetPageSize: Integer;
begin
Result := QRangeControl_pageStep(RangeControl);
end;
function TTrackBar.GetMax: Integer;
begin
Result := QRangeControl_maxValue(RangeControl);
end;
function TTrackBar.GetMin: Integer;
begin
Result := QRangeControl_minValue(RangeControl);
end;
function TTrackBar.GetPosition: Integer;
begin
Result := QRangeControl_value(RangeControl);
end;
function TTrackBar.GetTickMarks: TTickMark;
const
TickSettingMap:
array [Ord(QSliderTickSetting_Above)..Ord(QSliderTickSetting_Both)] of TTickMark = (tmTopLeft, tmBottomRight, tmBoth);
var
TickSetting: Integer;
begin
TickSetting := Integer(QSlider_tickMarks(Handle));
if TickSetting = Integer(QSliderTickSetting_NoMarks) then
Result := FTickMarks
else
Result := TickSettingMap[TickSetting];
end;
function TTrackBar.GetTickStyle: TTickStyle;
begin
Result := FTickStyle;
end;
procedure TTrackBar.UpdateSettings;
const
TickMarksMap: array [TTickMark, TTrackBarOrientation] of QSliderTickSetting =
((QSliderTickSetting_Below, QSliderTickSetting_Right),
(QSliderTickSetting_Above, QSliderTickSetting_Left),
(QSliderTickSetting_Both, QSliderTickSetting_Both));
begin
if TickStyle <> tsNone then
QSlider_setTickMarks(Handle, TickMarksMap[FTickMarks, Orientation]);
end;
procedure TTrackBar.ValueChangedHook(Value: Integer);
begin
{ The Value parameter from Qt is not used }
try
Changed;
except
Application.HandleException(Self);
end;
end;
{ TStatusPanel }
constructor TStatusPanel.Create(Collection: TCollection);
begin
inherited Create(Collection);
Width := 50;
FBevel := pbLowered;
FVisible := True;
end;
destructor TStatusPanel.Destroy;
begin
if PanelPosition = ppRight then
Dec(StatusPanels.FFixedPanelCount);
inherited Destroy;
end;
procedure TStatusPanel.Assign(Source: TPersistent);
begin
if Source is TStatusPanel then
begin
Text := TStatusPanel(Source).Text;
Width := TStatusPanel(Source).Width;
Alignment := TStatusPanel(Source).Alignment;
Bevel := TStatusPanel(Source).Bevel;
end else
inherited Assign(Source);
end;
function TStatusPanel.GetDisplayName: string;
begin
Result := Text;
if Result = '' then
Result := inherited GetDisplayName;
end;
procedure TStatusPanel.SetAlignment(const Value: TAlignment);
begin
if FAlignment <> Value then
begin
FAlignment := Value;
Changed(False);
end;
end;
procedure TStatusPanel.SetBevel(const Value: TStatusPanelBevel);
begin
if FBevel <> Value then
begin
FBevel := Value;
Changed(False);
end;
end;
procedure TStatusPanel.SetStyle(Value: TStatusPanelStyle);
begin
if FStyle <> Value then
begin
FStyle := Value;
Changed(False);
end;
end;
procedure TStatusPanel.SetText(const Value: WideString);
begin
if FText <> Value then
begin
FText := Value;
Changed(False);
end;
end;
procedure TStatusPanel.SetWidth(const Value: Integer);
begin
if FWidth <> Value then
begin
FWidth := Value;
Changed(True);
end;
end;
procedure TStatusPanel.SetPanelPosition(const Value: TPanelPosition);
begin
if FPanelPosition <> Value then
begin
if FPanelPosition = ppRight then
Dec(StatusPanels.FFixedPanelCount);
FPanelPosition := Value;
if FPanelPosition = ppRight then
Inc(StatusPanels.FFixedPanelCount);
Changed(False);
end;
end;
procedure TStatusPanel.SetVisible(const Value: Boolean);
begin
if FVisible <> Value then
begin
FVisible := Value;
Changed(False);
end;
end;
function TStatusPanel.GetStatusPanels: TStatusPanels;
begin
Result := TStatusPanels(Collection);
end;
{ TStatusPanels }
constructor TStatusPanels.Create(StatusBar: TStatusBar);
begin
inherited Create(TStatusPanel);
FStatusBar := StatusBar;
end;
function TStatusPanels.Add: TStatusPanel;
begin
Result := TStatusPanel(inherited Add);
end;
function TStatusPanels.GetItem(Index: Integer): TStatusPanel;
begin
Result := TStatusPanel(inherited GetItem(Index));
end;
function TStatusPanels.GetOwner: TPersistent;
begin
Result := FStatusBar;
end;
procedure TStatusPanels.Update(Item: TCollectionItem);
begin
StatusBar.UpdatePanels;
end;
procedure TStatusPanels.SetItem(Index: Integer; const Value: TStatusPanel);
begin
inherited SetItem(Index, Value);
FStatusBar.Update;
end;
{ TStatusBar }
function TStatusBar.FindPanel(PanelPosition: TPanelPosition;
Index: Integer): TStatusPanel;
var
I, Count: Integer;
begin
Result := nil;
Count := 0;
for I := 0 to Panels.Count-1 do
if Panels[I].PanelPosition = PanelPosition then
begin
if Count = Index then
begin
Result := Panels[I];
Break;
end;
Inc(Count);
end;
end;
function TStatusBar.ExecuteAction(Action: TBasicAction): Boolean;
begin
if AutoHint and (Action is THintAction) and not DoHint then
begin
if SimplePanel or (Panels.Count = 0) then
SimpleText := THintAction(Action).Hint
else
Panels[0].Text := THintAction(Action).Hint;
Result := True;
end else
Result := inherited ExecuteAction(Action);
end;
procedure TStatusBar.BeginUpdate;
begin
Inc(FUpdateCount);
end;
constructor TStatusBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle - [csAcceptsControls, csSetCaption]
+ [csNoFocus];
Align := alBottom;
FPanels := TStatusPanels.Create(Self);
FSizeGrip := True;
BorderStyle := bsNone;
BevelInner := bvNone;
BevelOuter := bvNone;
ParentColor := False;
end;
destructor TStatusBar.Destroy;
begin
FreeAndNil(FPanels);
inherited Destroy;
end;
function TStatusBar.DoHint: Boolean;
begin
if Assigned(FOnHint) then
begin
FOnHint(Self);
Result := True;
end else
Result := False;
end;
procedure TStatusBar.CursorChanged;
var
I: Integer;
begin
inherited;
for I := 0 to ControlCount-1 do
Controls[I].Cursor := Cursor;
end;
procedure TStatusBar.ControlsAligned;
begin
inherited ControlsAligned;
UpdatePanels;
end;
procedure TStatusBar.DoPanelClick(Panel: TStatusPanel);
begin
if Assigned(FOnPanelClick) then
FOnPanelClick(Self, Panel);
end;
procedure TStatusBar.DrawPanel(Panel: TStatusPanel; const Rect: TRect);
var
PrevBrush: TBrushRecall;
begin
if Assigned(FOnDrawPanel) then
FOnDrawPanel(Self, Panel, Rect)
else
begin
PrevBrush := TBrushRecall.Create(Canvas.Brush);
try
Canvas.Brush.Color := Color;
Canvas.FillRect(Rect);
finally
PrevBrush.Free;
end;
end;
end;
procedure TStatusBar.EnabledChanged;
var
I: Integer;
begin
inherited;
for I := 0 to ControlCount-1 do
Controls[I].Enabled := Enabled;
end;
procedure TStatusBar.Resize;
begin
inherited;
ValidateSizeGrip;
UpdatePanels;
end;
function TStatusBar.GetPanel(PanelPosition: TPanelPosition;
Index: Integer): TStatusPanel;
begin
Result := FindPanel(PanelPosition, Index);
if Result = nil then raise EListError.Create(Format(SListIndexError,[Index]));
end;
procedure TStatusBar.EndUpdate;
begin
Dec(FUpdateCount);
if FUpdateCount = 0 then
Update;
end;
procedure TStatusBar.FlipChildren(AllLevels: Boolean);
var
I: Integer;
begin
if HandleAllocated and
(not SimplePanel) and (Panels.Count > 0) then
begin
BeginUpdate;
try
{ Flip 'em }
for I := 0 to Panels.Count - 1 do
begin
if Panels[I].PanelPosition = ppLeft then
Panels[I].PanelPosition := ppRight
else
Panels[I].PanelPosition := ppLeft;
end;
finally
EndUpdate;
end;
end;
end;
procedure TStatusBar.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited;
ValidateSizeGrip;
end;
procedure TStatusBar.InitWidget;
begin
Height := STATUSBAR_HEIGHT;
BorderWidth := 0;
Color := clBackground;
end;
procedure TStatusBar.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
I: Integer;
Point: TPoint;
begin
inherited MouseUp(Button, Shift, X, Y);
Point.X := X;
Point.Y := Y;
for I := 0 to Panels.Count - 1 do
if PtInRect(Panels[I].FBounds, Point) then
begin
DoPanelClick(Panels[I]);
Break;
end;
end;
procedure TStatusBar.Invalidate;
begin
inherited Invalidate;
ValidateSizeGrip;
end;
function TStatusBar.IsFontStored: Boolean;
begin
Result := not ParentFont;
end;
procedure TStatusBar.PaletteCreated;
begin
// We don't want a SizeGrip to show up by default when the component is
// created off the palette. The default is left True so we can read in old
// StatusBar's from VCL
SizeGrip := False;
end;
procedure TStatusBar.RequestAlign;
begin
inherited RequestAlign;
Invalidate;
end;
procedure TStatusBar.Paint;
const
cTextFlags: array [TAlignment] of Integer = ( Integer(AlignmentFlags_AlignLeft),
Integer(AlignmentFlags_AlignRight),
Integer(AlignmentFlags_AlignHCenter));
cEdgeInner: array [TStatusPanelBevel] of TEdgeStyle = (esNone, esNone, esRaised);
cEdgeOuter: array [TStatusPanelBevel] of TEdgeStyle = (esNone, esLowered, esNone);
var
I: Integer;
R: TRect;
begin
Canvas.Font := Font;
if (Panels.Count = 0) or SimplePanel then
begin
R := Rect(BorderWidth, STATUS_PANEL_SPACER - BorderWidth, Width - BorderWidth,
Height - BorderWidth);
{ Find out where the Right border is }
for I := 0 to Panels.Count - 1 do
if Panels[I].PanelPosition = ppRight then
R.Right := Panels[I].FBounds.Left - STATUS_PANEL_SPACER;
DrawEdge(Canvas, R, esNone, cEdgeOuter[pbLowered], [ebLeft, ebTop, ebBottom, ebRight]);
if SimplePanel then
Canvas.TextRect(R, R.Left, R.Top, SimpleText,
Integer(AlignmentFlags_AlignVCenter) or cTextFlags[taLeftJustify]);
end;
if not (Panels.Count = 0) then
for I := 0 to Panels.Count - 1 do
if Panels[I].Visible and (not Panels[I].FHidden) then
begin
R := Panels[I].FBounds;
DrawEdge(Canvas, R, cEdgeInner[Panels[I].Bevel], cEdgeOuter[Panels[I].Bevel],
[ebLeft, ebTop, ebBottom, ebRight]);
InflateRect(R, -STATUS_PANEL_SPACER, -STATUS_PANEL_SPACER);
if Panels[I].Style = psOwnerDraw then
DrawPanel(Panels[I], R)
else
begin
if R.Right - R.Left > STATUS_PANEL_SPACER then
Canvas.TextRect(R, R.Left, R.Top, Panels[I].Text,
Integer(AlignmentFlags_AlignVCenter) or cTextFlags[Panels[I].Alignment]);
end;
InflateRect(R, STATUS_PANEL_SPACER, STATUS_PANEL_SPACER);
end;
end;
procedure TStatusBar.SetPanels(const Value: TStatusPanels);
begin
FPanels.Assign(Value);
end;
procedure TStatusBar.SetSimplePanel(const Value: Boolean);
begin
if FSimplePanel <> Value then
begin
FSimplePanel := Value;
UpdatePanels;
end;
end;
procedure TStatusBar.SetSimpleText(const Value: WideString);
begin
if FSimpleText <> Value then
begin
FSimpleText := Value;
Invalidate;
end;
end;
procedure TStatusBar.Update;
begin
if FUpdateCount = 0 then
begin
inherited Update;
UpdatePanels;
end;
end;
procedure TStatusBar.UpdatePanels;
const
cSizeGripMap: array [Boolean] of Integer = (0, SIZE_GRIP_SIZE + STATUS_PANEL_SPACER);
var
LeftSide: Integer;
RightSide: Integer;
NewLeft: Integer;
NewRight: Integer;
LastLeft: Integer;
I: Integer;
R: TRect;
begin
if HandleAllocated and (Panels <> nil) then
begin
LeftSide := BorderWidth;
RightSide := Width - BorderWidth;
NewLeft := LeftSide;
LastLeft := -1;
for I := 0 to Panels.Count-1 do
begin
if (Panels[I].PanelPosition = ppRight) and Panels[I].Visible then
begin
NewLeft := RightSide - Panels[I].Width;
TStatusPanel(Panels[I]).FBounds := Rect(NewLeft,
STATUS_PANEL_SPACER + BorderWidth, RightSide, Height - BorderWidth);
R := TStatusPanel(Panels[I]).FBounds;
RightSide := NewLeft - STATUS_PANEL_SPACER;
end;
end;
for I := 0 to Panels.Count-1 do
begin
if (Panels[I].PanelPosition = ppLeft) and Panels[I].Visible then
begin
NewRight := LeftSide + Panels[I].Width;
NewRight := Min(NewRight, RightSide);
Panels[I].FHidden := (NewRight <= LeftSide - STATUS_PANEL_SPACER) or SimplePanel;
if Panels[I].FHidden then Continue;
TStatusPanel(Panels[I]).FBounds := Rect(LeftSide,
STATUS_PANEL_SPACER + BorderWidth, NewRight,
Height - BorderWidth);
R := TStatusPanel(Panels[I]).FBounds;
LeftSide := NewRight + STATUS_PANEL_SPACER;
LastLeft := I;
end;
end;
if LastLeft > -1 then
begin
NewLeft := Max(NewLeft - STATUS_PANEL_SPACER, RightSide);
TStatusPanel(Panels[LastLeft]).FBounds.Right := NewLeft;
end;
Invalidate;
end;
end;
procedure TStatusBar.SetSizeGrip(const Value: Boolean);
begin
if FSizeGrip <> Value then
begin
FSizeGrip := Value;
ValidateSizeGrip;
end;
end;
type
TOpenCustomForm = class(TCustomForm);
procedure TStatusBar.ValidateSizeGrip;
var
Form: TCustomForm;
APoint, P: TPoint;
begin
Form := GetParentForm(Self);
if (Form <> nil) and
(TOpenCustomForm(Form).BorderStyle in [fbsSizeable, fbsSizeToolWin]) then
begin
P := Point(Width, Height);
QWidget_mapToParent(Handle, @APoint, @P);
if (APoint.X = Form.ClientWidth) {and (APoint.Y = Form.ClientHeight)} then
begin
if FSizeGripHandle = nil then
FSizeGripHandle := QSizeGrip_Create(Handle, nil);
PositionSizeGrip;
Exit;
end;
end;
if FSizeGripHandle <> nil then
QWidget_hide(FSizeGripHandle);
end;
procedure TStatusBar.PositionSizeGrip;
var
NewGripSizeHeight: Integer;
NewGripSizeLeft: Integer;
begin
if FSizeGripHandle <> nil then
begin
NewGripSizeHeight := Height - (BorderWidth * 2) - 6;
NewGripSizeLeft := Width - SIZE_GRIP_SIZE - BorderWidth - 2;
QWidget_setGeometry(FSizeGripHandle,
NewGripSizeLeft,
BorderWidth + 4,
SIZE_GRIP_SIZE,
NewGripSizeHeight);
QWidget_raise(FSizeGripHandle);
if SizeGrip and (Align in [alBottom, alRight, alClient]) then
QWidget_show(FSizeGripHandle)
else
QWidget_hide(FSizeGripHandle);
end;
end;
function TStatusBar.GetBorderWidth: TBorderWidth;
begin
Result := inherited BorderWidth;
end;
procedure TStatusBar.SetBorderWidth(const Value: TBorderWidth);
begin
inherited BorderWidth := Value;
PositionSizeGrip;
Update;
end;
procedure TStatusBar.CMRecreateWindow(var Message: TMessage);
begin
ValidateSizeGrip;
end;
{ TTab }
procedure TTab.Assign(Source: TPersistent);
begin
if Source is TTab then
begin
Caption := TTab(Source).Caption;
Enabled := TTab(Source).Enabled;
FTabRect := TTab(Source).TabRect;
Highlighted := TTab(Source).Highlighted;
ImageIndex := TTab(Source).ImageIndex;
Selected := TTab(Source).Selected;
Visible := TTab(Source).Visible;
end
else
inherited Assign(Source);
end;
constructor TTab.Create(Collection: TCollection);
begin
inherited Create(Collection);
Tabs.BeginUpdate;
try
Width := TabDefaultWidthMap[Tabs.TabControl.Style];
Height := TabDefaultHeightMap[Tabs.TabControl.Style];
FVisible := True;
FEnabled := True;
FImageIndex := Index;
finally
Tabs.EndUpdate;
end;
end;
function TTab.GetTabs: TTabs;
begin
Result := TTabs(Collection);
end;
function TTab.CalculateWidth: Integer;
var
ImageRef: TCustomImageList;
begin
Result := TabDefaultWidthMap[Tabs.TabControl.Style];
if Caption <> '' then
begin
{ Set the Width based on the width of the caption and Images }
Result := Tabs.TabControl.Canvas.TextWidth(Caption) +
(TabDefaultBorderWidthMap[Tabs.TabControl.Style] * 4);
ImageRef := Tabs.TabControl.GetImageRef;
if Tabs.TabControl.HasImages(Self) then
Result := Result + ImageRef.Width + (Tabs.TabControl.ImageBorder * 2);
if Result < TabDefaultWidthMap[Tabs.TabControl.Style] then
Result := TabDefaultWidthMap[Tabs.TabControl.Style];
end;
end;
function TTab.CalculateHeight: Integer;
begin
Result := Tabs.CalculateTabHeight(Caption);
end;
procedure TTab.SetCaption(const Value: TCaption);
begin
if FCaption <> Value then
begin
FCaption := Value;
Tabs.BeginUpdate;
try
Width := CalculateWidth;
Height := CalculateHeight;
finally
Tabs.EndUpdate;
end;
end;
end;
procedure TTab.SetEnabled(const Value: Boolean);
begin
if FEnabled <> Value then
begin
FEnabled := Value;
Changed(True);
end;
end;
function TTab.GetDisplayName: string;
begin
Result := FCaption;
if Result = '' then
Result := inherited GetDisplayName;
end;
function TTab.GetHeight: Integer;
begin
Result := TabRect.Bottom - TabRect.Top;
end;
function TTab.GetWidth: Integer;
begin
Result := TabRect.Right - TabRect.Left;
end;
procedure TTab.SetHeight(const Value: Integer);
var
NewValue: Integer;
begin
if Value <> (FTabRect.Bottom - FTabRect.Top) then
begin
Tabs.FUpdating := True;
try
if Value = 0 then
NewValue := CalculateHeight
else
NewValue := Value;
if FTabRect.Bottom <> FTabRect.Top + NewValue then
begin
FTabRect.Bottom := FTabRect.Top + NewValue;
Changed(True);
end;
finally
Tabs.FUpdating := False;
end;
end;
end;
procedure TTab.SetWidth(const Value: Integer);
var
NewValue: Integer;
begin
if Value <> (FTabRect.Right - FTabRect.Left) then
begin
Tabs.FUpdating := True;
try
if Value = 0 then
NewValue := CalculateWidth
else
NewValue := Value;
if FTabRect.Right <> FTabRect.Left + NewValue then
begin
FTabRect.Right := FTabRect.Left + NewValue;
Changed(True);
end;
finally
Tabs.FUpdating := False;
end;
end;
end;
function TTab.GetLeft: Integer;
begin
Result := TabRect.Left;
end;
function TTab.GetTop: Integer;
begin
Result := TabRect.Top;
end;
procedure TTab.SetLeft(const Value: Integer);
begin
if TabRect.Left <> Value then
begin
Tabs.FUpdating := True;
try
FTabRect.Right := Value + Width;
FTabRect.Left := Value;
Changed(True);
finally
Tabs.FUpdating := False;
end;
end;
end;
procedure TTab.SetTop(const Value: Integer);
begin
if TabRect.Top <> Value then
begin
Tabs.FUpdating := True;
try
FTabRect.Bottom := Value + Height;
FTabRect.Top := Value;
Changed(True);
finally
Tabs.FUpdating := False;
end;
end;
end;
procedure TTab.SetVisible(const Value: Boolean);
begin
if FVisible <> Value then
begin
FVisible := Value;
Changed(True);
end;
end;
function TTab.GetImageIndex: Integer;
begin
Result := FImageIndex;
end;
procedure TTab.SetImageIndex(const Value: Integer);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
Changed(True);
end;
end;
procedure TTab.SetSelected(const Value: Boolean);
begin
if FSelected <> Value then
begin
if Value and (Index <> Tabs.TabControl.TabIndex) then
if (Tabs.TabControl.Style = tsTabs) then
Exit
else
if not Tabs.TabControl.MultiSelect then
Tabs.TabControl.MultiSelect := True;
FSelected := Value;
Changed(True);
end;
end;
procedure TTab.SetHighlighted(const Value: Boolean);
begin
if FHighlighted <> Value then
begin
FHighlighted := Value;
Changed(True);
end;
end;
{ TTabs }
function TTabs.Add(const ACaption: WideString): TTab;
begin
Result := TTab(inherited Add);
Result.FCaption := ACaption;
Result.Changed(True);
end;
constructor TTabs.Create(TabControl: TCustomTabControl);
begin
inherited Create(TTab);
FTabControl := TabControl;
end;
function TTabs.GetItem(Index: Integer): TTab;
begin
Result := TTab(inherited GetItem(Index));
end;
function TTabs.GetOwner: TPersistent;
begin
Result := FTabControl;
end;
procedure TTabs.Update(Item: TCollectionItem);
begin
if FUpdating then Exit;
FUpdating := True;
if Item = nil then
begin
FTabControl.RequestLayout;
end else
FTabControl.Invalidate;
FUpdating := False;
end;
procedure TTabs.SetItem(Index: Integer; const Value: TTab);
begin
inherited SetItem(Index, Value);
if Assigned(TabControl) then
TabControl.Invalidate;
end;
function TTabs.CalculateTabHeight(const S: WideString): Integer;
var
ImageRef: TCustomImageList;
begin
{ Set the Height based on the height of the caption and Images }
with TabControl.Canvas do
if S = '' then
Result := TextHeight('Zy')
else
Result := TextHeight(S);
ImageRef := TabControl.GetImageRef;
if Assigned(ImageRef) then
if Result < ImageRef.Height then
Result := ImageRef.Height + 4;
if Result < TabDefaultHeightMap[TabControl.Style] then
Result := TabDefaultHeightMap[TabControl.Style];
end;
{ TTabButton }
type
TTabButtonDirection = (tbdLeft, tbdRight);
TTabScrollButton = class(TSpeedButton)
private
FTimer: TTimer;
FInitialDelay: Word;
FDelay: Word;
FDirection: TTabButtonDirection;
procedure TimerExpired(Sender: TObject);
procedure SetDirection(const Value: TTabButtonDirection);
protected
procedure ChangeScale(MV, DV, MH, DH: Integer); override;
procedure EnabledChanged; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure Paint; override;
procedure VisibleChanged; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Delay: Word read FDelay write FDelay default 50;
property InitialDelay: Word read FInitialDelay write FInitialDelay default 400;
property Direction: TTabButtonDirection read FDirection write SetDirection;
end;
constructor TTabScrollButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FInitialDelay := 400;
FDelay := 50;
ControlStyle := ControlStyle + [csNoDesignVisible];
end;
destructor TTabScrollButton.Destroy;
begin
FreeAndNil(FTimer);
inherited Destroy;
end;
procedure TTabScrollButton.TimerExpired(Sender: TObject);
begin
FTimer.Interval := FDelay;
if (FState = bsDown) and MouseCapture then
begin
try
Click;
except
FTimer.Enabled := False;
raise;
end;
end;
end;
procedure TTabScrollButton.SetDirection(const Value: TTabButtonDirection);
begin
if FDirection <> Value then
FDirection := Value;
end;
procedure TTabScrollButton.ChangeScale(MV, DV, MH, DH: Integer);
begin
{ Don't scale }
end;
procedure TTabScrollButton.EnabledChanged;
begin
{ Don't notify }
end;
procedure TTabScrollButton.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited MouseDown(Button, Shift, X, Y);
if FTimer = nil then
begin
FTimer := TTimer.Create(Self);
FTimer.OnTimer := TimerExpired;
end;
FTimer.Interval := FInitialDelay;
FTimer.Enabled := True;
end;
procedure TTabScrollButton.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited MouseUp(Button, Shift, X, Y);
if FTimer <> nil then
FTimer.Enabled := False;
end;
procedure TTabScrollButton.Paint;
const
EnabledColors: array [Boolean] of TColor = (clActiveMid, clBlack);
var
PaintRect: TRect;
Offset: TPoint;
PrevPen: TPenRecall;
PrevBrush: TBrushRecall;
begin
inherited Paint;
with Canvas do
begin
Offset := Point(0,0);
PaintRect := Rect(0, 0, Width - 1, Height - 1);
case FState of
bsDown:
begin
Inc(Offset.X);
Inc(Offset.Y);
end;
end;
PrevPen := nil;
PrevBrush := TBrushRecall.Create(Brush);
try
PrevPen := TPenRecall.Create(Pen);
Pen.Color := EnabledColors[Enabled];
Brush.Color := EnabledColors[Enabled];
Pen.Width := 1;
case Direction of
tbdLeft:
Polygon([ Point(4 + Offset.X, 7 + Offset.Y),
Point(7 + Offset.X, 4 + Offset.Y),
Point(7 + Offset.X, 10 + Offset.Y),
Point(4 + Offset.X, 7 + Offset.Y)]);
tbdRight:
Polygon([ Point(6 + Offset.X, 4 + Offset.Y),
Point(6 + Offset.X, 10 + Offset.Y),
Point(9 + Offset.X, 7 + Offset.Y),
Point(6 + Offset.X, 4 + Offset.Y)]);
end;
finally
PrevPen.Free;
PrevBrush.Free;
end;
end;
end;
procedure TTabScrollButton.VisibleChanged;
begin
inherited;
if Visible then Parent.Invalidate;
end;
{ TCustomTabControl }
procedure TabControlError(const S: string);
begin
raise EListError.Create(S);
end;
constructor TCustomTabControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csAcceptsControls, csDoubleClicks, csClickEvents, csOpaque];
FTabs := TTabs.Create(Self);
Width := 289;
Height := 193;
FRowCount := 0;
FFirstVisibleTab := 0;
FLastVisibleTab := 0;
FImageBorder := 3;
FImageChangeLink := TChangeLink.Create;
FImageChangeLink.OnChange := ImageListChange;
FMouseOver := -1;
FShowFrame := False;
FHotTrackColor := clBlue;
FTracking := -1;
TabStop := True;
InputKeys := [ikArrows];
FBitmap := TBitmap.Create;
FBitmap.Height := 2;
FBitmap.Width := 2;
FBitmap.Canvas.Pen.Color := clActiveLight;
FBitmap.Canvas.Polyline([Point(0,1),Point(0,1)]);
FBitmap.Canvas.Polyline([Point(1,0),Point(1,0)]);
FBitmap.Canvas.Pen.Color := clBackground;
FBitmap.Canvas.Polyline([Point(0,0),Point(0,0)]);
FBitmap.Canvas.Polyline([Point(1,1),Point(1,1)]);
FDblBuffer := TBitmap.Create;
CreateButtons;
end;
procedure TCustomTabControl.BeginUpdate;
begin
Tabs.BeginUpdate;
end;
destructor TCustomTabControl.Destroy;
begin
FreeAndNil(FDblBuffer);
FreeAndNil(FBitmap);
FreeAndNil(FImageChangeLink);
FreeAndNil(FTabs);
inherited Destroy;
end;
procedure TCustomTabControl.EndUpdate;
begin
Tabs.EndUpdate;
end;
function TCustomTabControl.IndexOfTabAt(X, Y: Integer): Integer;
var
I: Integer;
Rect: TRect;
begin
Result := -1;
if Tabs.Count > 0 then
for I := FFirstVisibleTab to FLastVisibleTab do
begin
Rect := Tabs[I].TabRect;
if Rect.Right > RightSide then Rect.Right := RightSide;
if PtInRect(Rect, Point(X, Y)) and Tabs[I].Visible then
begin
Result := I;
Break;
end;
end;
end;
function TCustomTabControl.TabRect(Index: Integer): TRect;
begin
Result := Tabs[Index].TabRect;
end;
procedure TCustomTabControl.ScrollTabs(Delta: Integer);
var
I: Integer;
begin
if not FMultiLine then
begin
for I := 0 to Abs(Delta)-1 do
if Delta < 0 then
FButtons[tbLeft].Click
else
FButtons[tbRight].Click;
end;
end;
procedure TCustomTabControl.Changed(Value: Integer);
begin
if Assigned(FOnChanged) then
FOnChanged(Self, Value);
end;
procedure TCustomTabControl.DrawHighlight(Canvas: TCanvas; const Rect: TRect;
ASelected, AHighlight, AEnabled: Boolean);
const
StyleAdjustment: array [TTabStyle] of Integer = (1, 0, 1, 0);
var
PrevBrush: TBrushRecall;
R: TRect;
begin
if ASelected and ((Style in [tsButtons, tsFlatButtons]) and not AHighlight) then
Canvas.Brush.Bitmap := FBitmap;
R := Rect;
if (Style = tsTabs) then
begin
Inc(R.Bottom);
if ASelected then
InflateRect(R, SELECTED_TAB_SIZE_DELTA, SELECTED_TAB_SIZE_DELTA)
else Inc(R.Bottom);
end;
PrevBrush := TBrushRecall.Create(Canvas.Brush);
try
if AHighlight then
begin
if AEnabled then
Canvas.Brush.Color := clActiveHighlight
else
Canvas.Brush.Color := clDisabledHighlight;
Canvas.Brush.Bitmap := nil;
end;
Canvas.Brush.Style := bsSolid;
Canvas.FillRect(R);
finally
PrevBrush.Free;
end;
Canvas.Brush.Bitmap := nil;
end;
function TCustomTabControl.DrawTab(TabIndex: Integer; const Rect: TRect;
Active: Boolean): Boolean;
begin
Result := True;
if Assigned(FOnDrawTab) then
FOnDrawTab(Self, TabIndex, Rect, Active, Result);
end;
procedure TCustomTabControl.EnabledChanged;
begin
inherited;
EnableScrollButtons;
end;
procedure TCustomTabControl.FontChanged;
begin
inherited;
Canvas.Font := Font;
RequestLayout;
end;
function TCustomTabControl.GetImageIndex(ATabIndex: Integer): Integer;
begin
Result := Tabs[ATabIndex].ImageIndex;
if Assigned(FOnGetImageIndex) then
FOnGetImageIndex(Self, ATabIndex, Result);
end;
procedure TCustomTabControl.AdjustTabRect(var Rect: TRect);
begin
case Style of
tsTabs:
begin
Inc(Rect.Top, 1);
end;
tsButtons:
begin
Dec(Rect.Right, 3);
Inc(Rect.Top, 3);
end;
tsFlatButtons:
begin
InflateRect(Rect, -2, -2);
Inc(Rect.Left, 2);
Dec(Rect.Right, 1);
Inc(Rect.Top);
Inc(Rect.Bottom);
end;
end;
end;
procedure TCustomTabControl.AdjustTabClientRect(var Rect: TRect);
begin
{ Adjust the Tabs rectangle to ignore the Borders }
case Style of
tsTabs:
begin
InflateRect(Rect, -TabDefaultBorderWidthMap[Style] - 1,
-TabDefaultBorderWidthMap[Style] - 1);
Inc(Rect.Bottom, TabDefaultBorderWidthMap[Style] - 1);
Dec(Rect.Left, TabDefaultBorderWidthMap[Style] - 1);
end;
tsButtons:
begin
InflateRect(Rect, -2, -2);
Dec(Rect.Right, 3);
Inc(Rect.Top, 3);
end;
tsFlatButtons:
begin
InflateRect(Rect, -4, -4);
Inc(Rect.Left, 2);
Dec(Rect.Right, TAB_FLAT_BORDER + 1);
Inc(Rect.Bottom);
Inc(Rect.Top);
end;
end;
end;
procedure TCustomTabControl.Loaded;
begin
inherited Loaded;
if Images <> nil then
UpdateTabImages;
RequestLayout;
end;
procedure TCustomTabControl.UpdateTabImages;
var
I: Integer;
begin
for I := 0 to FTabs.Count - 1 do
FTabs[I].ImageIndex := GetImageIndex(I);
TabsChanged;
end;
function TCustomTabControl.WantKey(Key: Integer; Shift: TShiftState;
const KeyText: WideString): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Tabs.Count - 1 do
if IsAccel(Key, Tabs[I].Caption) and (ssAlt in Shift) then
begin
TabIndex := Tabs[I].Index;
SetFocus;
Result := True;
Break;
end else
Result := inherited WantKey(Key, Shift, KeyText);
end;
function TCustomTabControl.WidgetFlags: Integer;
begin
Result := inherited WidgetFlags or Integer(WidgetFlags_WRepaintNoErase);
end;
procedure TCustomTabControl.SetTabIndex(const Value: Integer);
function CalculateFirstVisibleTab(Value: Integer): Integer;
var
vTotalWidth: Integer;
begin
vTotalWidth := 0;
if Value > 0 then
repeat
{ Set Width because we might get here before LayoutTabs}
Tabs[Value].Width := TabWidth;
if Tabs[Value].Visible then
Inc(vTotalWidth, Tabs[Value].Width);
if (vTotalWidth + Tabs[Value - 1].Width +
(SELECTED_TAB_SIZE_DELTA * 2) <= Rightside) then
Dec(Value);
until (Value = 0) or
(vTotalWidth + (SELECTED_TAB_SIZE_DELTA * 2) >= Rightside);
Result := Value;
end;
begin
if FTabIndex <> Value then
begin
if (Value <> -1) and (Value < 0) or (Value > Tabs.Count-1) then
{ Don't raise exception to maximize compatibility with VCL }
Exit;
if CanChange then
begin
if not MultiLine and (Value <> -1) and ((Value <= FFirstVisibleTab) or
(Value >= FLastVisibleTab)) then
begin
if (Value >= FLastVisibleTab) then
begin
FLastVisibleTab := Value;
FFirstVisibleTab := CalculateFirstVisibleTab(Value);
{ Sanity Check. The RightSide function bases its result on whether or
not the TabScrollButtons are visible and this is determined in part
by the variable FFirstVisibleTab. Since this is what we are
calculating this becomes a chicken & egg situation. We need to
recalculate it again if FFirstVisibleTab is greater than 0 so we can
be assured of an accurate result. }
if FFirstVisibleTab > 0 then FFirstVisibleTab := CalculateFirstVisibleTab(Value);
end else
FFirstVisibleTab := Value;
end;
if Value = -1 then
EraseControlFlag;
if FTracking <> -1 then
Tabs[FTracking].Selected := False;
FTracking := -1;
FTabIndex := Value;
Change;
Changed(FTabIndex);
if Multiline and (FLastVisibleTab = Tabs.Count - 1) then
begin
if FTabIndex <> -1 then
CalculateRows(Tabs[FTabIndex].Row);
{ Reset to prevent Layout }
FLayoutCount := 0;
Invalidate;
end else
RequestLayout;
end;
end;
end;
function TCustomTabControl.GetDisplayRect: TRect;
begin
Result := ClientRect;
Inc(Result.Top, GetTotalTabHeight + 1);
end;
function TCustomTabControl.GetImageRef: TCustomImageList;
begin
if Assigned(Images) then
Result := Images
else if Assigned(HotImages) and HotTrack then
Result := HotImages
else
Result := nil;
end;
function TCustomTabControl.GetTabIndex: Integer;
begin
Result := FTabIndex;
end;
function TCustomTabControl.GetTabHeight: Integer;
begin
Result := TabHeight;
if Result = 0 then
Result := Tabs.CalculateTabHeight('');
end;
procedure TCustomTabControl.CalcImageTextOffset(const ARect: TRect; const S: WideString;
Image: TCustomImageList; var ImagePos, TextPos: TPoint);
var
TotalWidth: Integer;
TotalHeight: Integer;
begin
if Assigned(Image) then
begin
TotalWidth := Canvas.TextWidth(S) + (ImageBorder * 2) + Image.Width;
TotalHeight := Image.Height;
ImagePos.X := ((ARect.Right - ARect.Left) - TotalWidth) div 2;
ImagePos.Y := ((ARect.Bottom - ARect.Top) - TotalHeight) div 2;
TextPos.X := ImagePos.X + (ImageBorder * 2) + Image.Width;
end else
begin
ImagePos := Point(0,0);
TotalWidth := Canvas.TextWidth(S);
TextPos.X := ((ARect.Right - ARect.Left) - TotalWidth) div 2;
end;
TotalHeight := Canvas.TextHeight(S);
TextPos.Y := ((ARect.Bottom - ARect.Top) - TotalHeight) div 2;
end;
procedure TCustomTabControl.CalculateRows(SelectedRow: Integer);
var
I: Integer;
begin
if Style = tsTabs then
begin
for I := FLastVisibleTab downto FFirstVisibleTab do
begin
if Tabs[I].Row > SelectedRow then Continue;
if (Tabs[I].Row = SelectedRow) then
Tabs[I].FRow := 1
else
if Tabs[I].Row < SelectedRow then
Tabs[I].FRow := Tabs[I].Row + 1;
end;
CalculateTabPositions;
end;
end;
procedure TCustomTabControl.CalculateTabPositions;
const
TopSpace: array [TTabStyle] of Integer = (2, 0, 0, 0);
var
LTabHeight: Integer;
I: Integer;
begin
LTabHeight := GetTabHeight;
for I := FFirstVisibleTab to FLastVisibleTab do
begin
if not Tabs[I].Visible then Continue;
if not MultiLine then
Tabs[I].Top := TopSpace[Style]
else
case Style of
tsTabs:
Tabs[I].Top := LTabHeight * (FRowCount - Tabs[I].Row) + SELECTED_TAB_SIZE_DELTA;
tsButtons, tsFlatButtons:
Tabs[I].Top := LTabHeight * (Tabs[I].Row - 1);
tsNoTabs:
Tabs[I].Top := 0;
end;
Tabs[I].Height := LTabHeight;
end;
end;
procedure TCustomTabControl.EnableScrollButtons;
begin
FUpdating := True;
try
FButtons[tbLeft].Enabled := Enabled and (FFirstVisibleTab > 0);
FButtons[tbRight].Enabled := Enabled and (FLastVisibleTab < Tabs.Count) and
(Tabs.Count > 0) and
((FLastVisibleTab <> -1) and
(Tabs[FLastVisibleTab].TabRect.Right > RightSide)) and not
((FLastVisibleTab = Tabs.Count - 1) and
(Tabs[FLastVisibleTab].Width > RightSide));
finally
FUpdating := False;
end;
end;
function TCustomTabControl.FindNextVisibleTab(Index: Integer): Integer;
function BackTrack: Integer;
var
vLeft: Integer;
begin
Result := Index - 1;
vLeft := RightSide;
while (Result > 0) and (vLeft > 0) do
begin
if Tabs[Result].Visible then
Dec(vLeft, Tabs[Result].Width);
Dec(Result);
end;
end;
begin
while (Index < Tabs.Count) and not Tabs[Index].Visible do
Inc(Index);
Result := Min(Index, Tabs.Count - 1);
end;
function TCustomTabControl.FindPrevVisibleTab(Index: Integer): Integer;
begin
Result := 0;
while (Index >= 0) and not Tabs[Index].Visible do
Dec(Index);
if Index > -1 then Result := Index;
end;
procedure TCustomTabControl.BeginDblBuffer;
begin
with FDblBuffer do
begin
Height := GetTotalTabHeight;
Width := Self.Width;
Canvas.Font := Self.Canvas.Font;
Canvas.Brush := Self.Canvas.Brush;
Canvas.Pen := Self.Canvas.Pen;
Canvas.FillRect(Rect(0, 0, Width, Height));
end;
end;
procedure TCustomTabControl.EndDblBuffer;
begin
Canvas.Draw(0, 0, FDblBuffer);
end;
procedure TCustomTabControl.StretchTabs(ARow: Integer);
var
Stretch: Integer;
I: Integer;
FirstTab, LastTab: TTab;
TabCount: Integer;
procedure CalcRowStats(Row: Integer; var AFirstTab, ALastTab: TTab; var ATabCount: Integer);
var
I: Integer;
begin
ATabCount := 0;
AFirstTab := nil;
ALastTab := nil;
for I := FFirstVisibleTab to FLastVisibleTab do
begin
if Tabs[I].FRow = Row then
begin
Inc(ATabCount);
if AFirstTab = nil then
AFirstTab := Tabs[I];
ALastTab := Tabs[I];
end else
if (AFirstTab <> nil) and (ALastTab <> nil) then
Break;
end;
end;
begin
CalcRowStats(ARow, FirstTab, LastTab, TabCount);
if TabCount < 1 then Exit;
Stretch := RightSide - LastTab.TabRect.Right;
Tabs[FirstTab.Index].Width := Tabs[FirstTab.Index].Width + (Stretch div TabCount);
for I := FirstTab.Index + 1 to LastTab.Index do
begin
if not Tabs[I].Visible then Continue;
Tabs[I].Width := Tabs[I].Width + (Stretch div TabCount);
Tabs[I].Left := Tabs[I - 1].TabRect.Right;
end;
Tabs[LastTab.Index].Width := Tabs[LastTab.Index].Width + (Stretch mod TabCount);
if LastTab.Index > FirstTab.Index then
Tabs[LastTab.Index].Left := Tabs[LastTab.Index - 1].TabRect.Right;
end;
function TCustomTabControl.GetTotalTabHeight: Integer;
const
SpaceBetweenTabAndFrame: array [TTabStyle] of Integer = (1, 0, -1, 0);
var
I: Integer;
vCurrRow: Integer;
vRowCount: Integer;
begin
Result := 0;
if (Tabs.Count > 0) and not (Style = tsNoTabs) then
begin
if MultiLine then
begin
vCurrRow := -1;
vRowCount := 0;
for I := 0 to Tabs.Count - 1 do
if Tabs[I].Visible and (vCurrRow <> Tabs[I].Row) then
begin
Inc(vRowCount);
vCurrRow := Tabs[I].Row;
end;
end
else
vRowCount := 1;
Result := vRowCount * GetTabHeight;
Inc(Result, SpaceBetweenTabAndFrame[Style] + SELECTED_TAB_SIZE_DELTA);
end;
end;
function TCustomTabControl.GetTabs: TTabs;
begin
Result := TTabs(FTabs);
end;
function TCustomTabControl.HasImages(ATab: TTab): Boolean;
var
ImageRef: TCustomImageList;
begin
ImageRef := GetImageRef;
Result := Assigned(ImageRef) and (ImageRef.Count > 0);
if Result and (ATab <> nil) then
Result := (ATab.ImageIndex > -1) and
(GetImageIndex(ATab.Index) < ImageRef.Count) and
(GetImageIndex(ATab.Index) >= 0);
end;
function TCustomTabControl.RightSide: Integer;
begin
DisplayScrollButtons;
if FButtons[tbLeft].Visible then
Result := FButtons[tbLeft].Left - 1
else
Result := Width + RightSideAdjustment;
end;
procedure TCustomTabControl.ButtonClick(Sender: TObject);
begin
BeginUpdate;
try
if Sender = FButtons[tbLeft] then
FFirstVisibleTab := FindPrevVisibleTab(FFirstVisibleTab - 1);
if Sender = FButtons[tbRight] then
if (Tabs[FLastVisibleTab].TabRect.Right > RightSide) or
(FindNextVisibleTab(FLastVisibleTab + 1) < Tabs.Count) then
FFirstVisibleTab := FindNextVisibleTab(FFirstVisibleTab + 1);
finally
EndUpdate;
end;
end;
procedure TCustomTabControl.EraseControlFlag(const Value: Boolean = True);
begin
FErase := Value;
end;
procedure TCustomTabControl.CreateButtons;
var
Button: TTabButtons;
begin
if FButtons[tbLeft] = nil then
begin
for Button := tbLeft to tbRight do
begin
FButtons[Button] := TTabScrollButton.Create(Self);
with FButtons[Button] do
begin
Parent := Self;
Visible := False;
Top := 2;
Width := SCROLL_BUTTON_WIDTH;
Height := SCROLL_BUTTON_WIDTH;
OnClick := ButtonClick;
Visible := False;
TTabScrollButton(FButtons[Button]).Direction := TTabButtonDirection(Button);
end;
end;
end;
end;
procedure TCustomTabControl.DisplayScrollButtons;
var
IsShowing: Boolean;
begin
PositionButtons;
IsShowing := False;
if (FLastVisibleTab > -1) and (FLastVisibleTab <= Tabs.Count - 1) and
not Multiline then
begin
IsShowing := (Tabs.Count > 0) and (FFirstVisibleTab > 0) or
(FLastVisibleTab < Tabs.Count -1) or
(Tabs[FLastVisibleTab].TabRect.Right >= Width +
RightSideAdjustment);
end;
FButtons[tbLeft].Visible := IsShowing;
FButtons[tbRight].Visible := IsShowing;
end;
procedure TCustomTabControl.DrawFocus;
const
FocusRectAdjust: array[TTabStyle] of Integer = (2, 0, 0, 0);
var
R,
Rect: TRect;
begin
if Focused and TabStop and not (csDesigning in ComponentState) and
(TabIndex > -1) and Tabs[TabIndex].Visible then
begin
R := Classes.Rect(0, 0, RightSide, GetTotalTabHeight);
Rect := Tabs[TabIndex].TabRect;
AdjustTabClientRect(Rect);
InflateRect(Rect, FocusRectAdjust[Style], FocusRectAdjust[Style]);
Canvas.Start;
try
Canvas.SetClipRect(R);
Canvas.DrawFocusRect(Rect);
finally
InflateRect(Rect, -FocusRectAdjust[Style], -FocusRectAdjust[Style]);
Canvas.ResetClipRegion;
Canvas.Stop;
end;
end;
end;
procedure TCustomTabControl.LayoutTabs;
var
I,
NewLeft,
PrevTab,
CurrTab,
NextTab,
MinTabs,
NumTabs: Integer;
begin
if (Style = tsNoTabs) then Exit;
FRowCount := 0;
MinTabs := 0;
NumTabs := 0;
FUpdating := True;
try
if Tabs.Count < 1 then Exit;
FLayoutCount := 0;
{ Tabs start at 2 so that a selected tab will be flush with the left border }
NewLeft := TabButtonsLeftMap[Style];
FRowCount := 1;
FLastVisibleTab := Tabs.Count - 1;
{ Find another Tab if the current one has been hidden }
if (TabIndex <> -1) and not Tabs[TabIndex].Visible then
begin
PrevTab := TabIndex;
NextTab := FindNextVisibleTab(TabIndex);
if not Tabs[NextTab].Visible then NextTab := FindPrevVisibleTab(TabIndex);
if not Tabs[NextTab].Visible then NextTab := PrevTab;
TabIndex := NextTab;
end;
for I := FFirstVisibleTab to FLastVisibleTab do
begin
if not Tabs[I].Visible then Continue;
{ Set initial Height and Width }
Tabs[I].Height := TabHeight;
Tabs[I].Width := TabWidth;
if MultiLine then
begin
{ Check to see if Tab will fit on current row }
if (NewLeft + Tabs[I].Width > RightSide) then
begin
Inc(FRowCount);
NewLeft := TabButtonsLeftMap[Style];
end;
Tabs[I].FRow := FRowCount;
end else
if (NewLeft > RightSide) and (I > 0) then
begin
FLastVisibleTab := FindPrevVisibleTab(I - 1);
Break;
end;
Tabs[I].Left := NewLeft;
NewLeft := Tabs[I].TabRect.Right;
if (NewLeft * 2) < RightSide then Inc(MinTabs);
Inc(NumTabs);
end;
{ Make sure the last visible tab is properly set. }
if not MultiLine and
(Tabs[FLastVisibleTab].TabRect.Left + SELECTED_TAB_SIZE_DELTA > RightSide) then
FLastVisibleTab := FindPrevVisibleTab(FLastVisibleTab - 1);
{ Check here to see if the last row has enough tabs to fill it. If not then
steal a tab from the prev row until we do or until the prev row is left
with the min number of tabs. }
if (FRowCount > 1) and (Style = tsTabs) then
begin
CurrTab := FLastVisibleTab;
repeat
Dec(CurrTab);
until Tabs[CurrTab].Row <> FRowCount;
while ((NewLeft * 2) < RightSide) and (NumTabs > MinTabs) and
(CurrTab > 0) do
begin
Tabs[CurrTab].FRow := FRowCount;
Inc(NewLeft, Tabs[CurrTab].Width);
Dec(NumTabs);
Dec(CurrTab);
end;
NewLeft := TabButtonsLeftMap[Style];
for I := CurrTab + 1 to FLastVisibleTab do
begin
Tabs[I].Left := NewLeft;
Inc(NewLeft, Tabs[I].Width);
end
end;
{ Recalculate all the rows of the selected Row and below if the Selected Tab is
not on the first row }
if MultiLine and (TabIndex <> -1) and (Tabs[TabIndex].Row > 1) and
(FRowCount >= Tabs[TabIndex].Row) then
CalculateRows(Tabs[TabIndex].Row);
{ Set the Top for each Tab based on its row }
CalculateTabPositions;
{ Adjust each Tab's width to fit in its row if there is no fixed TabWidth and
RaggedRight is not specified }
if (not RaggedRight) and MultiLine and (TabWidth = 0) and (FRowCount > 1) then
for I := 1 to FRowCount do
StretchTabs(I);
finally
FUpdating := False;
end;
end;
procedure TCustomTabControl.PositionButtons;
begin
FButtons[tbRight].Top := GetTotalTabHeight - FButtons[tbRight].Height - 2;
FButtons[tbLeft].Top := GetTotalTabHeight - FButtons[tbLeft].Height - 2;
FButtons[tbRight].Left := Width - SCROLL_BUTTON_WIDTH;
FButtons[tbLeft].Left := Width - ((SCROLL_BUTTON_WIDTH) * 2);
end;
function TCustomTabControl.RightSideAdjustment: Integer;
const
Adjustment: array [TTabStyle] of Integer = (-2, 3, 6, 0);
begin
Result := Adjustment[Style];
end;
procedure TCustomTabControl.SetTabs(const Value: TTabs);
begin
FTabs.Assign(Value);
RequestLayout;
end;
procedure TCustomTabControl.SetHotTrack(const Value: Boolean);
begin
if FHotTrack <> Value then
begin
FHotTrack := Value;
RequestLayout;
end;
end;
procedure TCustomTabControl.SetHotTrackColor(const Value: TColor);
begin
if FHotTrackColor <> Value then
begin
FHotTrackColor := Value;
end;
end;
procedure TCustomTabControl.SetImages(const Value: TCustomImageList);
begin
if Images <> nil then
Images.UnRegisterChanges(FImageChangeLink);
FImages := Value;
if Images <> nil then
begin
Images.RegisterChanges(FImageChangeLink);
Images.FreeNotification(Self);
end;
ImageListChange(Value);
end;
procedure TCustomTabControl.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = Images) then
Images := nil;
end;
procedure TCustomTabControl.AdjustClientRect(var Rect: TRect);
begin
{ Don't include the tab area }
Inc(Rect.Top, GetTotalTabHeight);
InflateRect(Rect, -(FRAME_BORDER_WIDTH * 2), -(FRAME_BORDER_WIDTH * 2));
{ This can happen if the TabControl is not very tall }
if Rect.Bottom < Rect.Top then
Rect.Bottom := Rect.Top;
end;
function TCustomTabControl.CanChange: Boolean;
begin
Result := True;
if Assigned(FOnChanging) then
FOnChanging(Self, Result);
end;
function TCustomTabControl.CanShowTab(TabIndex: Integer): Boolean;
begin
Result := True;
end;
procedure TCustomTabControl.Change;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TCustomTabControl.InternalDrawTabFrame(ACanvas: TCanvas; const ARect: TRect; Tab: TTab;
HotTracking: Boolean = False);
var
R: TRect;
PrevPen: TPenRecall;
procedure DrawTabFrame(Erase: Boolean);
begin
with ACanvas do
begin
if Erase then Pen.Color := clBackground else Pen.Color:= clBtnHighlight;
Polyline([Point(R.Left, R.Bottom),
Point(R.Left, R.Top + 2),
Point(R.Left + 1, R.Top + 1),
Point(R.Left + 2, R.Top),
Point(R.Right - 3, R.Top)]);
if Erase then Pen.Color := clBackground else Pen.Color:= clBtnShadow;
Polyline([Point(R.Right - 2, R.Top + 2),
Point(R.Right - 2, R.Bottom)]);
if Erase then Pen.Color := clBackground else Pen.Color:= clBlack;
Polyline([Point(R.Right - 2, R.Top + 1),
Point(R.Right - 1, R.Top + 2),
Point(R.Right - 1, R.Bottom)]);
end;
end;
begin
if not Tab.Visible then Exit;
with ACanvas do
begin
Start;
try
if not MultiLine then
SetClipRect(ARect);
R := Tab.TabRect;
AdjustTabRect(R);
case Style of
tsTabs:
begin
if Tab.Index = TabIndex then
begin
Dec(R.Top, SELECTED_TAB_SIZE_DELTA);
Inc(R.Right, SELECTED_TAB_SIZE_DELTA);
Dec(R.Left, SELECTED_TAB_SIZE_DELTA);
Inc(R.Bottom, SELECTED_TAB_SIZE_DELTA - 1);
end;
if DrawTab(Tab.Index, R, Tab.Enabled) then
begin
{ Erase the frame area }
PrevPen:= TPenRecall.Create(Pen);
try
Brush.Style := bsSolid;
Pen.Color:= clBackground;
Inc(R.Bottom, 1);
Rectangle(R);
InflateRect(R, -1, -1);
Rectangle(R);
InflateRect(R, 1, 1);
Dec(R.Bottom, 1);
if TabIndex = Tab.Index then
begin
InflateRect(R, -SELECTED_TAB_SIZE_DELTA, -SELECTED_TAB_SIZE_DELTA);
Rectangle(R);
InflateRect(R, SELECTED_TAB_SIZE_DELTA, SELECTED_TAB_SIZE_DELTA);
end;
DrawTabFrame(False);
finally
PrevPen.Free;
end;
end;
end;
tsButtons:
begin
InternalDrawFrame(ACanvas, R, True, (Tab.Index = TabIndex) or (Tab.Selected),
True);
end;
tsFlatButtons:
begin
PrevPen := TPenRecall.Create(Pen);
try
Pen.Color:= clBtnShadow;
MoveTo(R.Right, R.Top);
LineTo(R.Right, R.Bottom - 1);
Pen.Color:= clBtnHighlight;
MoveTo(R.Right + 1, R.Top);
LineTo(R.Right + 1, R.Bottom - 1);
finally
PrevPen.Free;
end;
Dec(R.Right, TAB_FLAT_BORDER);
if (Tab.Index = TabIndex) or (Tab.Selected) then
InternalDrawFrame(ACanvas, R, True, True, True)
else
begin
Brush.Style := bsSolid;
FillRect(R);
end;
end;
end;
finally
if not MultiLine then
ResetClipRegion;
Stop;
end;
end;
end;
procedure TCustomTabControl.InternalDrawTabContents(ACanvas: TCanvas; const ARect: TRect; Tab: TTab;
HotTracking: Boolean = False);
const
TextFlags: array [TTabStyle] of Integer = ( Integer(AlignmentFlags_AlignLeft),
Integer(AlignmentFlags_AlignHCenter),
Integer(AlignmentFlags_AlignHCenter),
0);
var
PrevFontColor: TColor;
R: TRect;
ImageOffset: TPoint;
TextOffset: TPoint;
ImageRef: TCustomImageList;
procedure CalcSelectedOffset(var Point: TPoint);
begin
if (Tab.Index = TabIndex) or Tab.Selected then
begin
Inc(Point.X, TabDefaultTextOffsetMap[Style]);
Inc(Point.Y, TabDefaultTextOffsetMap[Style]);
end;
end;
begin
if not Tab.Visible then Exit;
PrevFontColor := Canvas.Font.Color;
with ACanvas do
begin
Start;
try
if not MultiLine then
SetClipRect(ARect);
R := Tab.TabRect;
AdjustTabClientRect(R);
if not HotTracking then
DrawHighlight(ACanvas, R, (TabIndex = Tab.Index), Tab.Highlighted, Tab.Enabled);
ImageRef := Images;
if HotTrack and Assigned(HotImages) then
ImageRef := HotImages;
if Assigned(ImageRef) and HasImages(Tab) then
begin
CalcImageTextOffset(R, Tab.Caption, ImageRef, ImageOffset, TextOffset);
CalcSelectedOffset(ImageOffset);
CalcSelectedOffset(TextOffset);
if ((ImageRef = HotImages) and Hottracking) or (ImageRef = Images) then
ImageRef.Draw(ACanvas, R.Left + ImageOffset.X, R.Top + ImageOffset.Y,
GetImageIndex(Tab.Index), itImage, Tab.Enabled and Enabled);
end else
begin
CalcImageTextOffset(R, Tab.Caption, nil, ImageOffset, TextOffset);
CalcSelectedOffset(TextOffset);
end;
{ Draw Text }
if not Tab.Enabled or not Enabled then
begin
{ offset the first text slightly to give the recessed disabled look }
Font.Color := clDisabledLight;
TextRect(R, R.Left + TextOffset.X + 1, R.Top + TextOffset.Y + 1, Tab.Caption,
Integer(AlignmentFlags_SingleLine) or
Integer(AlignmentFlags_ShowPrefix));
Font.Color := clDisabledText;
end else
if HotTracking and (Style <> tsFlatButtons) then
Font.Color := HotTrackColor
else
if Tab.Highlighted then
Font.Color := clHighlightedText;
TextRect(R, R.Left + TextOffset.X, R.Top + TextOffset.Y, Tab.Caption,
Integer(AlignmentFlags_SingleLine) or
Integer(AlignmentFlags_ShowPrefix));
finally
Font.Color := PrevFontColor;
if not Multiline then
ResetClipRegion;
Stop;
end;
end;
end;
procedure TCustomTabControl.InternalDrawFrame(ACanvas: TCanvas; ARect: TRect; AShowFrame: Boolean = True;
Sunken: Boolean = False; Fill : Boolean = True);
const
FrameColorOuter: array [Boolean] of TColor = (clActiveLight, clActiveShadow);
FrameColorInner: array [Boolean] of TColor = (clBackground, clActiveDark);
FrameRectOffset: array [Boolean] of Integer = (3, -1);
var
PrevPen: TPenRecall;
PrevBrush: TBrushRecall;
DrawRegion: QRegionH;
ControlRegion: QRegionH;
VControl: TControl;
I: Integer;
R: TRect;
function DisplayFrame: Boolean;
begin
Result := AShowFrame or (Style = tsTabs);
end;
begin
with ACanvas do
try
Start;
if (csDesigning in ComponentState) and not AShowFrame and (Style = tsNoTabs) then
begin
PrevPen := nil;
PrevBrush := TBrushRecall.Create(Canvas.Brush);
try
PrevPen := TPenRecall.Create(Canvas.Pen);
Pen.Style := psDot;
Brush.Style := bsSolid;
if Fill then FillRect(ARect);
Rectangle(0, GetTotalTabHeight, Width, Height);
Exit;
finally
PrevBrush.Free;
PrevPen.Free;
end;
end;
Dec(ARect.Bottom, 1);
Dec(ARect.Right, 1);
if DisplayFrame then
begin
PrevPen := TPenRecall.Create(Canvas.Pen);
try
Pen.Color := FrameColorOuter[Sunken];
Polyline([Point(ARect.Left, ARect.Bottom),
Point(ARect.Left, ARect.Top),
Point(ARect.Right - 1, ARect.Top)]);
Pen.Color := FrameColorInner[Sunken];
Polyline([Point(ARect.Left + 1, ARect.Bottom - 1),
Point(ARect.Left + 1, ARect.Top + 1),
Point(ARect.Right - 2, ARect.Top + 1)]);
Pen.Color := FrameColorOuter[not Sunken];
Polyline([Point(ARect.Right, ARect.Top),
Point(ARect.Right, ARect.Bottom),
Point(ARect.Left, ARect.Bottom)]);
Pen.Color := FrameColorInner[not Sunken];
Polyline([Point(ARect.Right -1, ARect.Top + 1),
Point(ARect.Right - 1, ARect.Bottom - 1),
Point(ARect.Left + 1, ARect.Bottom - 1)]);
finally
PrevPen.Free;
end;
end;
InflateRect(ARect, FrameRectOffset[DisplayFrame], FrameRectOffset[DisplayFrame]);
Inc(ARect.Top);
Inc(ARect.Left);
{ Clear the interior of the page }
if Fill then
begin
FillRect(ARect);
end else
begin
DrawRegion := QRegion_create(@ARect, QRegionRegionType_Rectangle);
try
{ Erase the interior excluding any opaque controls }
for I := 0 to ControlCount - 1 do
begin
VControl := TControl(Controls[I]);
if (VControl.Visible or ((csDesigning in VControl.ComponentState) and
not (csNoDesignVisible in VControl.ControlStyle))) and
(csOpaque in VControl.ControlStyle) then
begin
R := VControl.BoundsRect;
ControlRegion := QRegion_create(@R, QRegionRegionType_Rectangle);
try
QRegion_subtract(DrawRegion, DrawRegion, ControlRegion);
finally
QRegion_destroy(ControlRegion);
end;
if QRegion_isEmpty(DrawRegion) then
Break;
end;
end;
if not QRegion_isEmpty(DrawRegion) then
QWidget_erase(Self.Handle, DrawRegion);
finally
QRegion_destroy(DrawRegion);
end;
end;
finally
Stop;
end;
end;
procedure TCustomTabControl.Paint;
const
TabFrameAdj: array [Boolean] of Integer = (0, SELECTED_TAB_SIZE_DELTA);
var
I: Integer;
R: TRect;
begin
inherited Paint;
if FLayoutCount > 0 then LayoutTabs;
EnableScrollButtons;
DisplayScrollButtons;
Canvas.Brush.Color := Color;
Canvas.Brush.Style := bsSolid;
R := Rect(0, GetTotalTabHeight, Width, Height);
InternalDrawFrame(Canvas, R, ShowFrame, False, FErase);
EraseControlFlag(False);
if (Style <> tsNoTabs) and (Tabs.Count > 0) then
begin
BeginDblBuffer;
try
R := Rect(0, 0, RightSide, GetTotalTabHeight + 1);
for I := FFirstVisibleTab to FLastVisibleTab do
if Tabs[I].Visible then
if I <> TabIndex then
begin
InternalDrawTabFrame(FDblBuffer.Canvas, R, Tabs[I], (I = FMouseOver) and HotTrack);
InternalDrawTabContents(FDblBuffer.Canvas, R, Tabs[I], (I = FMouseOver) and HotTrack);
end;
finally
EndDblBuffer;
end;
if (TabIndex >= FFirstVisibleTab) and (TabIndex <= FLastVisibleTab) and
(TabIndex > -1) then
begin
{ Draw Selected Tab }
InternalDrawTabFrame(Canvas, R, Tabs[TabIndex], (TabIndex = FMouseOver) and HotTrack);
InternalDrawTabContents(Canvas, R, Tabs[TabIndex], (TabIndex = FMouseOver) and HotTrack);
DrawFocus;
end;
end;
end;
procedure TCustomTabControl.RequestAlign;
begin
inherited RequestAlign;
RequestLayout;
end;
procedure TCustomTabControl.RequestLayout;
begin
if FUpdating then Exit;
Inc(FLayoutCount);
Invalidate;
end;
procedure TCustomTabControl.Resize;
begin
inherited Resize;
PositionButtons;
RequestLayout;
end;
procedure TCustomTabControl.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
vTabIndex: Integer;
begin
if Button <> mbLeft then Exit;
vTabIndex := IndexOfTabAt(X, Y);
if vTabIndex = -1 then Exit;
if not Tabs[vTabIndex].Enabled then Exit;
{ Mark tab as selected if CTRL down. If the user clicks on the currently
selected tab then unselect the rest }
if (ssCtrl in Shift) and MultiSelect and
(Style in [tsButtons, tsFlatButtons]) then
begin
Tabs[vTabIndex].Selected := not Tabs[vTabIndex].Selected;
if vTabIndex = TabIndex then
begin
TabIndex := -1;
UnselectTabs;
end;
Invalidate;
end else
begin
UnselectTabs;
if (vTabIndex > -1) and (vTabIndex <> TabIndex) then
if (Style <> tsFlatButtons) or (FTracking = vTabIndex) then
TabIndex := vTabIndex;
end;
{ Call inherited last. This allows the OnChanging, OnPageChanging and OnChanged
events to fire before the Mouse up. }
inherited MouseUp(Button, Shift, X, Y);
end;
procedure TCustomTabControl.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited MouseDown(Button, Shift, X, Y);
if (Button = mbLeft) and (Style = tsFlatButtons) then
begin
FTracking := IndexOfTabAt(X, Y);
FMouseOver := -1;
DoHotTrack(FTracking);
end;
end;
procedure TCustomTabControl.DoHotTrack(const Value: Integer);
procedure DrawHotTrack(Erase: Boolean);
var
R, Rect: TRect;
begin
if FMouseOver > -1 then
begin
R := Classes.Rect(0, 0, RightSide, GetTotalTabHeight + 1);
case Style of
tsTabs, tsButtons:
begin
if HotTrack then
begin
InternalDrawTabContents(Canvas, R, Tabs[FMouseOver], not Erase);
if Erase then
begin
if (FMouseOver <> TabIndex) and (FMouseOver >= FFirstVisibleTab) and
(FMouseOver <= FLastVisibleTab) then
begin
InternalDrawTabFrame(Canvas, R, Tabs[TabIndex], not Erase);
InternalDrawTabContents(Canvas, R, Tabs[TabIndex], not Erase);
end;
DrawFocus;
end;
end;
end;
tsFlatButtons:
begin
if not (HotTrack) and (FTracking > -1) and (FMouseOver <> FTracking)
and (FTracking <> TabIndex) then
begin
InternalDrawTabFrame(Canvas, R, Tabs[FTracking]);
InternalDrawTabContents(Canvas, R, Tabs[FTracking]);
end;
if Erase then
begin
InternalDrawTabFrame(Canvas, R, Tabs[FMouseOver]);
InternalDrawTabContents(Canvas, R, Tabs[FMouseOver]);
end else
begin
Canvas.Start;
try
Canvas.SetClipRect(R);
if (FMouseOver <> TabIndex) then
begin
Rect := Tabs[FMouseOver].TabRect;
AdjustTabRect(Rect);
Dec(Rect.Right, TAB_FLAT_BORDER);
DrawShadePanel(Canvas, Rect, False, 1, Palette.ColorGroup(cgActive));
end;
InternalDrawTabContents(Canvas, R, Tabs[FMouseOver], HotTrack);
if (FMouseOver = TabIndex) and
((FTracking = -1) or (FTracking = TabIndex)) then DrawFocus;
finally
Canvas.ResetClipRegion;
Canvas.Stop;
end;
end;
if FMouseOver = TabIndex then
DrawFocus;
end;
end;
end;
end;
begin
if (FMouseOver <> Value) then
begin
if MultiLine or ((FMouseOver >= FFirstVisibleTab) and
(FMouseOver <= FLastVisibleTab)) then
DrawHotTrack(True);
FMouseOver := Value;
if HotTrack or (FTracking = Value) then
DrawHotTrack(False);
end;
end;
procedure TCustomTabControl.MouseLeave(AControl: TControl);
begin
inherited MouseLeave(AControl);
// When the mouse leaves at high speed it might leave a tab highlighted. Kill it.
DoHotTrack(-1);
end;
procedure TCustomTabControl.MouseMove(Shift: TShiftState; X, Y: Integer);
var
Index: Integer;
begin
inherited MouseMove(Shift, X, Y);
Index := IndexOfTabAt(X, Y);
if (Index = -1) or (Tabs[Index].TabRect.Left <= RightSide) then
DoHotTrack(Index);
end;
function TCustomTabControl.DoMouseWheel(Shift: TShiftState;
WheelDelta: Integer; const MousePos: TPoint): Boolean;
begin
inherited DoMouseWheel(Shift, WheelDelta, MousePos);
Result := True;
end;
function TCustomTabControl.DoMouseWheelDown(Shift: TShiftState;
const MousePos: TPoint): Boolean;
begin
Result := inherited DoMouseWheelDown(Shift, MousePos);
if TabIndex > 0 then
TabIndex := TabIndex - 1;
end;
function TCustomTabControl.DoMouseWheelUp(Shift: TShiftState;
const MousePos: TPoint): Boolean;
begin
Result := inherited DoMouseWheelUp(Shift, MousePos);
if TabIndex < Tabs.Count-1 then
TabIndex := TabIndex + 1;
end;
procedure TCustomTabControl.ImageListChange(Sender: TObject);
begin
RequestLayout;
end;
procedure TCustomTabControl.KeyUp(var Key: Word; Shift: TShiftState);
var
Delta: Integer;
function RangeCheckTracking(const Value: Integer): Integer;
begin
Result := Value;
if (Result > Tabs.Count - 1) or (Result < -1) then
Result := FTracking;
end;
procedure ChangeTracking(const Delta: ShortInt);
begin
if FTracking = -1 then
FTracking := RangeCheckTracking(TabIndex + Delta)
else
begin
Tabs[FTracking].Selected := False;
FTracking := RangeCheckTracking(FTracking + Delta);
end;
if FTracking > -1 then
Tabs[FTracking].Selected := True;
if not Multiline then
ScrollTabs(Delta);
end;
procedure ChangeTabIndex(const Delta: Integer);
begin
if (TabIndex + Delta > Tabs.Count - 1) or (TabIndex + Delta < 0) then
Exit
else
TabIndex := TabIndex + Delta;
end;
begin
inherited KeyUp(Key, Shift);
Delta := 0;
case Key of
Key_Tab:
if (ssCtrl in Shift) then
if ssShift in Shift then
Delta := -1
else
Delta := 1;
Key_Right, Key_Down:
if not (Shift = [ssAlt]) then
Delta := 1;
Key_Left, Key_Up:
if not (Shift = [ssAlt]) then
Delta := -1;
Key_Home:
if not (Shift = [ssAlt]) then
if FTracking <> -1 then
Delta := - FTracking
else
Delta := -TabIndex;
Key_End:
if not (Shift = [ssAlt]) then
if FTracking <> -1 then
Delta := Tabs.Count - FTracking - 1
else
Delta := Tabs.Count - TabIndex - 1;
Key_Return, Key_Enter, Key_Space:
if not (Shift = [ssAlt]) then
if FTracking <> -1 then
TabIndex := FTracking;
end;
if Delta <> 0 then
if (Style = tsTabs) or (Key = Key_Tab) then
ChangeTabIndex(Delta)
else
ChangeTracking(Delta);
end;
procedure TCustomTabControl.SetMultiLine(const Value: Boolean);
begin
if FMultiLine <> Value then
begin
FMultiLine := Value;
FFirstVisibleTab := 0;
FLastVisibleTab := Tabs.Count-1;
RequestLayout;
end;
end;
procedure TCustomTabControl.SetMultiSelect(const Value: Boolean);
begin
if FMultiSelect <> Value then
begin
FMultiSelect := Value;
if not FMultiSelect then
UnselectTabs;
Invalidate;
end;
end;
procedure TCustomTabControl.SetOwnerDraw(const Value: Boolean);
begin
if FOwnerDraw <> Value then
begin
FOwnerDraw := Value;
end;
end;
procedure TCustomTabControl.SetRaggedRight(const Value: Boolean);
begin
if FRaggedRight <> Value then
begin
FRaggedRight := Value;
RequestLayout;
end;
end;
procedure TCustomTabControl.SetStyle(Value: TTabStyle);
begin
if FStyle <> Value then
begin
FStyle := Value;
if csDesigning in ComponentState then
FShowFrame := FShowFrame and (Value = tsTabs);
EraseControlFlag;
RequestLayout;
end;
end;
procedure TCustomTabControl.SetTabHeight(const Value: Smallint);
begin
if FTabSize.Y <> Value then
begin
if Value < 0 then
raise EInvalidOperation.CreateFmt(SPropertyOutOfRange, [Self.Classname]);
FTabSize.Y := Value;
TabsChanged;
end;
end;
procedure TCustomTabControl.SetTabWidth(const Value: Smallint);
begin
if FTabSize.X <> Value then
begin
if Value < 0 then
raise EInvalidOperation.CreateFmt(SPropertyOutOfRange, [Self.Classname]);
FTabSize.X := Value;
TabsChanged;
end;
end;
procedure TCustomTabControl.TabsChanged;
begin
RequestLayout;
end;
procedure TCustomTabControl.SetShowFrame(const Value: Boolean);
begin
if FShowFrame <> Value then
begin
FShowFrame := Value;
EraseControlFlag;
Invalidate;
end;
end;
procedure TCustomTabControl.SetHotImages(const Value: TCustomImageList);
begin
if HotImages <> nil then
HotImages.UnRegisterChanges(FImageChangeLink);
FHotImages := Value;
if HotImages <> nil then
begin
HotImages.RegisterChanges(FImageChangeLink);
HotImages.FreeNotification(Self);
end;
ImageListChange(Value);
end;
procedure TCustomTabControl.UnselectTabs;
var
I: Integer;
begin
for I := 0 to Tabs.Count-1 do
if Tabs[I].Selected then
Tabs[I].Selected := False;
end;
{ TTabSheet }
constructor TTabSheet.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Align := alClient;
ControlStyle := ControlStyle + [csAcceptsControls, csNoDesignVisible];
Visible := False;
TabVisible := True;
end;
destructor TTabSheet.Destroy;
begin
if (FPageControl <> nil) and
not (csDestroying in FPageControl.ComponentState) then
FPageControl.RemovePage(Self);
inherited Destroy;
end;
procedure TTabSheet.InitWidget;
begin
inherited;
QWidget_setFocusPolicy(Handle, QWidgetFocusPolicy_NoFocus);
end;
function TTabSheet.GetTabIndex: Integer;
begin
if Assigned(FTab) then
Result := FTab.Index
else
Result := -1;
end;
procedure TTabSheet.AdjustClientRect(var Rect: TRect);
begin
inherited AdjustClientRect(Rect);
InflateRect(Rect, -BorderWidth, -BorderWidth);
if Rect.Bottom < Rect.Top then
Rect.Bottom := Rect.Top;
end;
procedure TTabSheet.DoHide;
begin
if Assigned(FOnHide) then FOnHide(Self);
end;
procedure TTabSheet.DoShow;
begin
if Assigned(FOnShow) then FOnShow(Self);
end;
procedure TTabSheet.EnabledChanged;
begin
inherited;
if Assigned(FPageControl) then
FPageControl.UpdateTab(Self);
end;
procedure TTabSheet.ReadState(Reader: TReader);
begin
inherited ReadState(Reader);
if Reader.Parent is TPageControl then
PageControl := TPageControl(Reader.Parent);
end;
procedure TTabSheet.TextChanged;
begin
if Assigned(FPageControl) then
FPageControl.UpdateTab(Self);
end;
procedure TTabSheet.ShowingChanged;
begin
inherited;
try
if Showing then
DoShow
else
DoHide;
except
Application.HandleException(Self);
end;
end;
procedure TTabSheet.SetBorderWidth(const Value : TBorderWidth);
begin
if FBorderWidth <> Value then
begin
FBorderWidth := Value;
Realign;
Invalidate;
end;
end;
procedure TTabSheet.SetHighlighted(const Value: Boolean);
begin
if FHighlighted <> Value then
FHighlighted := Value;
if Assigned(FPageControl) then
FPageControl.UpdateTab(Self);
end;
procedure TTabSheet.SetImageIndex(const Value: TImageIndex);
begin
if FImageIndex <> Value then
FImageIndex := Value;
if Assigned(FPageControl) then
FPageControl.UpdateTab(Self);
end;
procedure TTabSheet.SetPageControl(const Value: TPageControl);
begin
if PageControl <> Value then
begin
if PageControl <> nil then PageControl.RemovePage(Self);
Parent := Value;
if Value <> nil then Value.InsertPage(Self);
end;
end;
function TTabSheet.GetPageIndex: Integer;
begin
if PageControl <> nil then
Result := PageControl.FPages.IndexOf(Self)
else
Result := -1;
end;
procedure TTabSheet.SetPageIndex(const Value: Integer);
var
I, MaxPageIndex: Integer;
begin
if PageControl <> nil then
begin
MaxPageIndex := PageControl.PageCount - 1;
if Value > MaxPageIndex then
raise EListError.CreateResFmt(@SPageIndexError, [Value, MaxPageIndex]);
I := TabIndex;
PageControl.FPages.Move(PageIndex, Value);
PageControl.TabIndex := PageIndex;
if I >= 0 then PageControl.MoveTab(I, PageControl.TabIndex);
end;
end;
procedure TTabSheet.SetTabVisible(const Value: Boolean);
begin
if FTabVisible <> Value then
FTabVisible := Value;
if Assigned(FPageControl) then
FPageControl.UpdateTab(Self);
end;
{ TPageControl }
constructor TPageControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle - [csAcceptsControls];
FPages := TList.Create;
end;
procedure TPageControl.DoContextPopup(const MousePos: TPoint; var Handled: Boolean);
begin
{ Since the TTabSheet doesn't cover the entire client area (there is a 4 pixel
border) we don't want the popup to display for the PageControl unless it is
within the Tab area. }
Handled := (MousePos.Y > GetTotalTabHeight) and
(ControlAtPos(MousePos, False, True) = nil);
if not Handled then inherited DoContextPopup(MousePos, Handled);
end;
function TPageControl.CanShowTab(TabIndex: Integer): Boolean;
begin
Result := TTabSheet(FPages[TabIndex]).Enabled;
end;
procedure TPageControl.Changed(Value: Integer);
begin
inherited Changed(Value);
ActivePageIndex := Value;
end;
procedure TPageControl.Change;
var
Form: TCustomForm;
begin
UpdateActivePage;
if csDesigning in ComponentState then
begin
Form := GetParentForm(Self);
if (Form <> nil) and (Form.DesignerHook <> nil) then Form.DesignerHook.Modified;
end;
inherited Change;
end;
procedure TPageControl.ChangeActivePage(Page: TTabSheet);
var
ParentForm: TCustomForm;
AllowChange: Boolean;
begin
AllowChange := True;
if FActivePage <> Page then
begin
if not (csLoading in ComponentState) then
PageChanging(Page, AllowChange);
if not AllowChange then Exit;
ParentForm := GetParentForm(Self);
if (ParentForm <> nil) and (FActivePage <> nil) and
FActivePage.ContainsControl(ParentForm.ActiveControl) then
begin
ParentForm.ActiveControl := FActivePage;
if ParentForm.ActiveControl <> FActivePage then
begin
TabIndex := FActivePage.TabIndex;
Exit;
end;
end;
if Page <> nil then
begin
Page.Visible := True;
Page.BringToFront;
if (ParentForm <> nil) and (FActivePage <> nil) and
(ParentForm.ActiveControl = FActivePage) then
if Page.CanFocus then
ParentForm.ActiveControl := Page else
ParentForm.ActiveControl := Self;
end;
if FActivePage <> nil then FActivePage.Visible := False;
FActivePage := Page;
if not (csLoading in ComponentState) then
PageChange;
if (ParentForm <> nil) and (FActivePage <> nil) and
(ParentForm.ActiveControl = FActivePage) then
FActivePage.SelectFirst;
end;
end;
destructor TPageControl.Destroy;
begin
FPages.Free;
inherited Destroy;
end;
function TPageControl.FindNextPage(CurPage: TTabSheet; GoForward,
CheckTabVisible: Boolean): TTabSheet;
var
I, StartIndex: Integer;
begin
if (PageCount > 0) then
begin
StartIndex := FPages.IndexOf(CurPage);
if StartIndex = -1 then
if GoForward then
StartIndex := PageCount - 1
else
StartIndex := 0;
I := StartIndex;
repeat
if GoForward then
begin
Inc(I);
if I = PageCount then
I := 0;
end else
begin
if I = 0 then
I := PageCount;
Dec(I);
end;
Result := Pages[I];
if not CheckTabVisible or Result.TabVisible then
Exit;
until I = StartIndex;
end;
Result := nil;
end;
procedure TPageControl.DeleteTab(Page: TTabSheet; Index: Integer);
var
UpdateIndex: Boolean;
begin
UpdateIndex := Page = ActivePage;
Tabs.Delete(Index);
if UpdateIndex then
begin
if Index >= Tabs.Count then
Index := Tabs.Count - 1;
TabIndex := Index;
end;
UpdateActivePage;
end;
function TPageControl.GetActivePageIndex: Integer;
begin
if ActivePage <> nil then
Result := ActivePage.GetPageIndex
else
Result := -1;
end;
function TPageControl.DesignEventQuery(Sender: QObjectH; Event: QEventH): Boolean;
var
Index: Integer;
MousePos: TPoint;
Control: TControl;
begin
Result := False;
if (Sender = Handle) and
(QEvent_type(Event) in [QEventType_MouseButtonPress,
QEventType_MouseButtonRelease, QEventType_MouseButtonDblClick]) then
begin
MousePos := Point(QMouseEvent_x(QMouseEventH(Event)),
QMouseEvent_y(QMouseEventH(Event)));
Control := ControlAtPos(MousePos, True, True);
if (Control is TTabScrollButton) then
Result := Control.Enabled
else
begin
Index := IndexOfTabAt(MousePos.X, MousePos.Y);
Result := (Index <> -1) and (Index <> TabIndex);
end;
end;
end;
procedure TPageControl.GetChildren(Proc: TGetChildProc; Root: TComponent);
var
I: Integer;
begin
for I := 0 to FPages.Count - 1 do Proc(TComponent(FPages[I]));
end;
function TPageControl.GetPage(Index: Integer): TTabSheet;
begin
Result := TTabSheet(FPages[Index]);
end;
function TPageControl.GetPageCount: Integer;
begin
Result := FPages.Count;
end;
procedure TPageControl.MoveTab(CurIndex, NewIndex: Integer);
begin
Tabs[CurIndex].Index := NewIndex;
end;
procedure TPageControl.InsertPage(const APage: TTabSheet);
begin
BeginUpdate;
try
FPages.Add(aPage);
APage.FPageControl := Self;
InsertTab(APage);
UpdateActivePage;
finally
EndUpdate;
end;
end;
procedure TPageControl.InsertTab(Page: TTabSheet);
begin
Page.FTab := TTab(Tabs.Add(Page.Caption));
UpdateTab(Page);
UpdateActivePage;
end;
procedure TPageControl.RemovePage(const APage: TTabSheet);
var
NextSheet: TTabSheet;
begin
NextSheet := FindNextPage(aPage, True, not (csDesigning in ComponentState));
if NextSheet = APage then NextSheet := nil;
DeleteTab(APage, APage.PageIndex);
APage.FPageControl := nil;
FPages.Remove(APage);
SetActivePage(NextSheet);
end;
procedure TPageControl.UpdateTab(Page: TTabSheet);
begin
if Assigned(FTabs) then
begin
Tabs[Page.TabIndex].Caption := Page.Caption;
Tabs[Page.TabIndex].ImageIndex := Page.ImageIndex;
Tabs[Page.TabIndex].Highlighted := Page.Highlighted;
Tabs[Page.TabIndex].Visible := Page.TabVisible;
end;
end;
procedure TPageControl.SelectNextPage(GoForward: Boolean);
var
Page: TTabSheet;
begin
Page := FindNextPage(ActivePage, GoForward, True);
if (Page <> nil) and (Page <> ActivePage) then
begin
TabIndex := Page.TabIndex;
end;
end;
procedure TPageControl.SetActivePage(aPage: TTabSheet);
begin
if (aPage <> nil) and (aPage.PageControl <> Self) then Exit;
ChangeActivePage(aPage);
if aPage = nil then
TabIndex := -1
else if aPage = FActivePage then
begin
TabIndex := aPage.PageIndex;
end;
end;
procedure TPageControl.SetActivePageIndex(const Value: Integer);
begin
if (Value > -1) and (Value < PageCount) then
ActivePage := TTabSheet(Pages[Value])
else
ActivePage := nil;
end;
procedure TPageControl.PageChange;
begin
if Assigned(FOnPageChange) then
FOnPageChange(Self);
end;
procedure TPageControl.PageChanging(NewPage: TTabSheet; var AllowChange: Boolean);
begin
if Assigned(FOnPageChanging) then
FOnPageChanging(Self, NewPage, AllowChange);
end;
procedure TPageControl.SetChildOrder(Child: TComponent; Order: Integer);
begin
TTabSheet(Child).PageIndex := Order;
end;
procedure TPageControl.ShowControl(AControl: TControl);
begin
if (AControl is TTabSheet) and (TTabSheet(AControl).PageControl = Self) then
SetActivePage(TTabSheet(AControl));
inherited ShowControl(AControl);
end;
procedure TPageControl.UpdateActivePage;
begin
if TabIndex >= 0 then
SetActivePage(FPages[TabIndex])
else
SetActivePage(nil);
end;
procedure TPageControl.Update;
begin
if Style = tsNoTabs then Realign;
inherited Update;
end;
{ utility routines for TreeView/TreeNode }
procedure TreeViewError(const Msg: string);
begin
raise ETreeViewError.Create(Msg);
end;
procedure TreeViewErrorFmt(const Msg: string; Format: array of const);
begin
raise ETreeViewError.CreateFmt(Msg, Format);
end;
type
TListViewHeader = class(TCustomHeaderControl)
private
FHidden: Boolean;
FHiddenChanging: Boolean;
procedure SetSections(const Value: TListColumns);
function GetSections: TListColumns;
procedure SetHidden(const Value: Boolean);
function ListViewHandle: QListViewH;
function ViewControl: TCustomViewControl;
protected
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; override;
function GetHandle: QHeaderH; override;
procedure ColumnClicked(Section: TCustomHeaderSection); override;
procedure ColumnMoved(Section: TCustomHeaderSection); override;
procedure ColumnResized(Section: TCustomHeaderSection); override;
procedure CreateWidget; override;
procedure DestroyWidget; override;
procedure HookEvents; override;
procedure InitWidget; override;
procedure Update; override;
procedure UpdateWidgetShowing; override;
property Handle: QHeaderH read GetHandle;
property Hidden: Boolean read FHidden write SetHidden default True;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Sections: TListColumns read GetSections write SetSections;
end;
type
TSubItems = class(TStringList)
private
FOwner: TCustomViewItem;
protected
function GetHandle: QListViewItemH;
function HandleAllocated: Boolean;
function Add(const S: string): Integer; override;
procedure Delete(Index: Integer); override;
procedure Put(Index: Integer; const S: string); override;
procedure PutObject(Index: Integer; AObject: TObject); override;
procedure InsertItem(Index: Integer; const S: string; AObject: TObject); override;
public
constructor Create(AOwner: TCustomViewItem);
procedure Insert(Index: Integer; const S: string); override;
procedure AssignTo(Dest: TPersistent); override;
property Handle: QListViewItemH read GetHandle;
property Owner: TCustomViewItem read FOwner;
end;
procedure TCustomViewItems.Delete(Index: Integer);
begin
FItems[Index].Delete;
end;
function TCustomViewItems.FindViewItem(ItemH: QListViewItemH): TCustomViewItem;
var
I: Integer;
begin
Result := nil;
if ItemH = nil then
Exit;
Result := TCustomViewItem(QClxObjectMap_find(ItemH));
if Assigned(Result) then
Exit;
for I := 0 to Count-1 do
begin
if FItems[I].Handle = ItemH then
begin
Result := FItems[I];
Exit;
end;
end;
end;
{ TSubItems }
function TSubItems.Add(const S: string): Integer;
var
WS: WideString;
begin
Result := inherited Add(S);
Objects[Result] := Pointer(-1);
if HandleAllocated and FOwner.ViewControlValid and
FOwner.ViewControl.ShowColumnHeaders then
begin
WS := S;
QListViewItem_setText(Handle, Result+1, PWideString(@WS));
end;
end;
procedure TSubItems.AssignTo(Dest: TPersistent);
var
I: Integer;
begin
if Dest is TSubItems then
begin
BeginUpdate;
try
TStrings(Dest).Clear;
for I := 0 to Count-1 do
TStrings(Dest).AddObject(Strings[I], Objects[I]);
finally
EndUpdate;
end;
end
else
inherited AssignTo(Dest);
end;
constructor TSubItems.Create(AOwner: TCustomViewItem);
begin
inherited Create;
FOwner := AOwner;
end;
procedure TSubItems.Delete(Index: Integer);
begin
inherited Delete(Index);
if HandleAllocated then
QListViewItem_setText(Handle, Index+1, nil);
end;
function TSubItems.GetHandle: QListViewItemH;
begin
if FOwner.HandleAllocated then
Result := FOwner.Handle
else
Result := nil;
end;
function TSubItems.HandleAllocated: Boolean;
begin
Result := Handle <> nil;
end;
procedure TSubItems.Insert(Index: Integer; const S: string);
begin
inherited Insert(Index, S);
Objects[Index] := Pointer(-1);
end;
procedure TSubItems.InsertItem(Index: Integer; const S: string; AObject: TObject);
var
WS: WideString;
begin
inherited InsertItem(Index, S, AObject);
if HandleAllocated and FOwner.ViewControlValid and
FOwner.ViewControl.ShowColumnHeaders then
begin
Inc(Index);
WS := S;
QListViewItem_setText(FOwner.Handle, Index, PWideString(@WS));
FOwner.ImageIndexChange(Index, Integer(AObject));
end;
end;
procedure TSubItems.Put(Index: Integer; const S: string);
var
WS: WideString;
begin
inherited Put(Index, S);
if HandleAllocated and FOwner.ViewControlValid and
FOwner.ViewControl.ShowColumnHeaders then
begin
WS := S;
QListViewItem_setText(Handle, Index+1, PWideString(@WS));
end;
end;
procedure TSubItems.PutObject(Index: Integer; AObject: TObject);
begin
if Integer(Objects[Index]) <> Integer(AObject) then
begin
inherited PutObject(Index, AObject);
Inc(Index);
FOwner.ImageIndexChange(Index, Integer(AObject));
end;
end;
{ TCustomViewControl }
constructor TCustomViewControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csCaptureMouse, csClickEvents, csDoubleClicks];
FImageLink := TChangeLink.Create;
FImageLink.OnChange := ImageListChange;
FHeader := TListViewHeader.Create(Self);
FIndent := 20;
FTimer := TTimer.Create(nil);
FTimer.Enabled := False;
FTimer.Interval := 500;
FTimer.OnTimer := TimerIntervalElapsed;
FSortDirection := sdAscending;
ParentColor := False;
TabStop := True;
BorderStyle := bsSunken3d;
InputKeys := [ikChars, ikArrows];
Height := 97;
Width := 121;
end;
destructor TCustomViewControl.Destroy;
begin
CheckRemoveEditor;
if Assigned(FMemStream) then
FreeAndNil(FMemStream);
FTimer.Free;
FHeader.Free;
FImageLink.Free;
inherited Destroy;
if Assigned(FItemHooks) then
QClxListViewHooks_destroy(FItemHooks);
end;
procedure TCustomViewControl.ColorChanged;
begin
inherited ColorChanged;
UpdateControl;
end;
procedure TCustomViewControl.CreateWidget;
begin
FHandle := QListView_create(ParentWidget, nil);
Hooks := QListView_hook_create(FHandle);
FItemHooks := QClxListViewHooks_create;
FViewportHandle := QScrollView_viewport(Handle);
QClxObjectMap_add(FViewportHandle, Integer(Self));
FHScrollHandle := QScrollView_horizontalScrollBar(Handle);
QClxObjectMap_add(FHScrollHandle, Integer(Self));
FVScrollHandle := QScrollView_verticalScrollBar(Handle);
QClxObjectMap_add(FVScrollHandle, Integer(Self));
end;
const
cSelMode: array [Boolean] of QListViewSelectionMode = (QListViewSelectionMode_Single,
QListViewSelectionMode_Extended);
cSortDirection: array [TSortDirection] of Boolean = (True, False);
procedure TCustomViewControl.InitWidget;
begin
inherited InitWidget;
QWidget_setMouseTracking(FViewportHandle, True);
QWidget_setAcceptDrops(FViewportHandle, True);
QListView_setShowSortIndicator(Handle, FShowColumnSortIndicators);
QListView_setTreeStepSize(Handle, FIndent);
TListViewHeader(FHeader).Hidden := not FShowColumnHeaders;
QListView_setSelectionMode(Handle, cSelMode[FMultiSelect]);
QListView_setAllColumnsShowFocus(Handle, FRowSelect);
if Sorted then
QListView_setSorting(Handle, SortColumn, cSortDirection[SortDirection])
else
QListView_setSorting(Handle, -1, False);
UpdateControl;
end;
function TCustomViewControl.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
if (Sender = QScrollView_verticalScrollBar(Handle)) or
(Sender = QScrollView_horizontalScrollBar(Handle)) then
begin
Result := False;
case QEvent_type(Event) of
QEventType_MouseButtonPress,
QEventType_MouseButtonDblClick,
QEventType_FocusIn:
CheckRemoveEditor;
end;
Exit;
end;
if (QEvent_type(Event) = QEventType_FocusIn) then
CheckRemoveEditor;
Result := inherited EventFilter(Sender, Event);
end;
procedure TCustomViewControl.ItemChangeHook(item: QListViewItemH; _type: TItemChange);
begin
try
ItemChange(item, _type);
except
Application.HandleException(Self);
end;
end;
procedure TCustomViewControl.ItemChangingHook(item: QListViewItemH; _type: TItemChange;
var Allow: Boolean);
begin
try
ItemChanging(item, _type, Allow);
except
Application.HandleException(Self);
end;
end;
procedure TCustomViewControl.ItemCheckedHook(item: QListViewItemH; Checked: Boolean);
begin
try
ItemChecked(item, Checked);
except
Application.HandleException(Self);
end;
end;
procedure TCustomViewControl.ItemChecked(item: QListViewItemH; Checked: Boolean);
begin
{ stubbed for children }
end;
procedure TCustomViewControl.ItemDestroyedHook(AItem: QListViewItemH);
begin
try
ItemDestroyed(AItem);
except
Application.HandleException(Self);
end;
end;
procedure TCustomViewControl.ItemDestroyed(AItem: QListViewItemH);
begin
{ stubbed for children }
end;
procedure TCustomViewControl.ItemSelectedHook(item: QListViewItemH; wasSelected: Boolean);
begin
try
ItemSelected(item, wasSelected);
except
Application.HandleException(Self);
end;
end;
procedure TCustomViewControl.ItemChange(item: QListViewItemH; _type: TItemChange);
begin
{ stubbed for children }
end;
procedure TCustomViewControl.ItemChanging(item: QListViewItemH; _type: TItemChange;
var Allow: Boolean);
begin
{ stubbed for children }
end;
procedure TCustomViewControl.ItemSelected(item: QListViewItemH; wasSelected: Boolean);
begin
{ stubbed for children }
end;
procedure TCustomViewControl.DoGetImageIndex(item: TCustomViewItem);
begin
{ stubbed for children }
end;
procedure TCustomViewControl.DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean);
begin
{ stubbed for children }
end;
procedure TCustomViewControl.DoEdited(AItem: TCustomViewItem; var S: WideString);
begin
{ stubbed for children }
end;
procedure TCustomViewControl.ItemExpandingHook(item: QListViewItemH; Expand: Boolean;
var Allow: Boolean);
begin
try
ItemExpanding(item, Expand, Allow);
except
Application.HandleException(Self);
end;
end;
procedure TCustomViewControl.ItemExpanding(item: QListViewItemH; Expand: Boolean;
var Allow: Boolean);
begin
{ stubbed for children }
end;
procedure TCustomViewControl.ItemExpandedHook(item: QListViewItemH; Expand: Boolean);
begin
try
ItemExpanded(item, Expand);
except
Application.HandleException(Self);
end;
end;
procedure TCustomViewControl.ItemExpanded(item: QListViewItemH; Expand: Boolean);
begin
{ stubbed for children }
end;
function TCustomViewControl.IsEditing: Boolean;
begin
Result := Assigned(FEditor) and FEditor.FEditing;
end;
procedure TCustomViewControl.StartEditTimer;
begin
if not ReadOnly then
FTimer.Enabled := True;
FAllowEdit := False;
end;
procedure TCustomViewControl.TimerIntervalElapsed(Sender: TObject);
begin
if Visible then
begin
FTimer.Enabled := False;
FAllowEdit := True;
end;
end;
procedure TCustomViewControl.CheckRemoveEditor;
begin
if not Assigned(FEditor) then
Exit;
FEditor.EditFinished(True);
FEditor := nil;
end;
procedure TCustomViewControl.EditItem;
begin
CheckRemoveEditor;
if not (csDesigning in ComponentState) and not ReadOnly then
begin
FEditor := CreateEditor;
FEditor.Execute;
end;
end;
function TCustomViewControl.FindDropTarget: TCustomViewItem;
var
Pt: TPoint;
begin
if HandleAllocated then
begin
QCursor_pos(@Pt);
QWidget_mapFromGlobal(ViewportHandle, @Pt, @Pt);
Result := TCustomViewItem(QClxObjectMap_find(QListView_itemAt(Handle, @Pt)));
end
else
Result := nil;
end;
function TCustomViewControl.CreateEditor: TItemEditor;
begin
Result := TItemEditor.Create(Self);
end;
function TCustomViewControl.GetHandle: QListViewH;
begin
HandleNeeded;
Result := QListViewH(FHandle);
end;
function TCustomViewControl.GetIndent: Integer;
begin
Result := FIndent;
end;
procedure TCustomViewControl.SetIndent(const Value: Integer);
begin
if FIndent <> Value then
begin
FIndent := Value;
if FIndent < 0 then
FIndent := 0;
if HandleAllocated then
begin
QListView_setTreeStepSize(Handle, FIndent);
UpdateControl;
end;
end;
end;
procedure TCustomViewControl.SetMultiSelect(const Value: Boolean);
begin
if MultiSelect <> Value then
begin
FMultiSelect := Value;
if HandleAllocated then
begin
if FMultiSelect then
QListView_selectAll(Handle, False);
QListView_setSelectionMode(Handle, cSelMode[FMultiSelect]);
end;
end;
end;
function TCustomViewControl.GetMultiSelect: Boolean;
begin
Result := FMultiSelect;
end;
function TCustomViewControl.GetRowSelect: Boolean;
begin
Result := FRowSelect;
end;
procedure TCustomViewControl.SetRowSelect(const Value: Boolean);
begin
if RowSelect <> Value then
begin
FRowSelect := Value;
if HandleAllocated then
QListView_setAllColumnsShowFocus(Handle, FRowSelect);
end;
end;
procedure TCustomViewControl.InvertSelection;
begin
if HandleAllocated then
QListView_invertSelection(Handle);
end;
procedure TCustomViewControl.SetImageList(const Value: TCustomImageList);
begin
if FImageList <> Value then
begin
if Assigned(FImageList) then
FImageList.UnRegisterChanges(FImageLink);
FImageList := Value;
if Assigned(FImageList) then
FImageList.RegisterChanges(FImageLink);
ImageListChanged;
end;
end;
procedure TCustomViewControl.ImageListChange(Sender: TObject);
begin
ImageListChanged;
end;
procedure TCustomViewControl.ImageListChanged;
begin
{ stubbed out for children }
end;
function TCustomViewControl.NeedKey(Key: Integer; Shift: TShiftState;
const KeyText: WideString): Boolean;
begin
Result := inherited NeedKey(Key, Shift, KeyText) and (Shift * [ssShift, ssAlt, ssCtrl] = []);
end;
procedure TCustomViewControl.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = FImageList) then
begin
if (Operation = opRemove) then
FImageList := nil;
ImageListChanged;
end;
end;
procedure TCustomViewControl.SetOwnerDraw(const Value: Boolean);
begin
if Value <> FOwnerDraw then
begin
FOwnerDraw := Value;
if HandleAllocated then
QWidget_update(ViewportHandle);
end;
end;
type
TViewControlItemPaint_event = procedure(p: QPainterH; item: QListViewItemH; column,
width, alignment: Integer; var stage: Integer) of object cdecl;
TViewControlBranchPaint_event = procedure(p: QPainterH; item: QListViewItemH;
w, y, h: Integer; style: GUIStyle; var stage: Integer) of object cdecl;
TViewControlItemSelected_event = procedure (item: QListViewItemH;
wasSelected: Boolean) of object cdecl;
TViewControlItemChange_event = procedure (item: QListViewItemH;
_type: TItemChange) of object cdecl;
TViewControlItemChanging_event = procedure (item: QListViewItemH;
_type: TItemChange; var Allow: Boolean) of object cdecl;
TViewControlItemExpanding_event = procedure (item: QListViewItemH;
Expanding: Boolean; var Allow: Boolean) of object cdecl;
TViewControlItemExpanded_event = procedure (item: QListViewItemH;
Expanding: Boolean) of object cdecl;
TViewControlItemChecked_event = procedure (item: QListViewItemH;
Checked: Boolean) of object cdecl;
TViewControlItemDestroyed_event = procedure (item: QListViewItemH) of object cdecl;
procedure TCustomViewControl.HookEvents;
var
Method: TMethod;
begin
inherited HookEvents;
TViewControlItemPaint_event(Method) := ItemPaintHook;
QClxListViewHooks_hook_PaintCell(FItemHooks, Method);
TViewControlBranchPaint_event(Method) := BranchPaintHook;
QClxListViewHooks_hook_paintBranches(FItemHooks, Method);
TViewControlItemSelected_event(Method) := ItemSelectedHook;
QClxListViewHooks_hook_setSelected(FItemHooks, Method);
TViewControlItemChange_event(Method) := ItemChangeHook;
QClxListViewHooks_hook_change(FItemHooks, Method);
TViewControlItemChanging_event(Method) := ItemChangingHook;
QClxListViewHooks_hook_changing(FItemHooks, Method);
TViewControlItemExpanding_event(Method) := ItemExpandingHook;
QClxListViewHooks_hook_expanding(FItemHooks, Method);
TViewControlItemExpanded_event(Method) := ItemExpandedHook;
QClxListViewHooks_hook_expanded(FItemHooks, Method);
TViewControlItemChecked_event(Method) := ItemCheckedHook;
QClxListViewHooks_hook_checked(FItemHooks, Method);
TViewControlItemDestroyed_event(Method) := ItemDestroyedHook;
QClxListViewHooks_hook_destroyed(FItemHooks, Method);
TEventFilterMethod(Method) := MainEventFilter;
FViewportHooks := QWidget_hook_create(FViewportHandle);
Qt_hook_hook_events(FViewportHooks, Method);
FHScrollHooks := QScrollBar_hook_create(FHScrollHandle);
Qt_hook_hook_events(FHScrollHooks, Method);
FVScrollHooks := QScrollBar_hook_create(FVScrollHandle);
Qt_hook_hook_events(FVScrollHooks, Method);
QObject_destroyed_event(Method) := ViewportDestroyed;
QObject_hook_hook_destroyed(FViewportHooks, Method);
end;
function TCustomViewControl.IsCustomDrawn: Boolean;
begin
Result := IsOwnerDrawn or Assigned(FOnCustomDrawItem) or
Assigned(FOnCustomDrawSubItem) or Assigned(FOnCustomDrawBranch);
end;
function TCustomViewControl.IsOwnerDrawn: Boolean;
begin
Result := False;
end;
function TCustomViewControl.DoCustomDrawViewItem(Item: TCustomViewItem;
Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState;
Stage: TCustomDrawStage): Boolean;
begin
Result := True;
if Assigned(FOnCustomDrawItem) then FOnCustomDrawItem(Self, Item,
Canvas, Rect, State, Stage, Result);
end;
function TCustomViewControl.DoCustomDrawViewSubItem(Item: TCustomViewItem;
SubItem: Integer; Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState;
Stage: TCustomDrawStage): Boolean;
begin
Result := True;
if Assigned(FOnCustomDrawSubItem) then FOnCustomDrawSubItem(Self, Item,
SubItem, Canvas, Rect, State, Stage, Result);
end;
procedure TCustomViewControl.DoDrawItem(Item: TCustomViewItem; Canvas: TCanvas;
const Rect: TRect; State: TOwnerDrawState);
begin
{ Implemented by descendants }
end;
procedure TCustomViewControl.BeginAutoDrag;
begin
BeginDrag(False, Mouse.DragThreshold);
end;
procedure TCustomViewControl.BranchPaintHook(p: QPainterH;
item: QListViewItemH; w, y, h: Integer; style: GUIStyle;
var stage: Integer);
var
Canvas: TCanvas;
State: TCustomDrawState;
ListItem: TCustomViewItem;
R: TRect;
begin
if not IsCustomDrawn then
begin
stage := DrawStage_DefaultDraw;
Exit;
end;
try
State := [];
ListItem := TCustomViewItem(FindObject(QObjectH(item)));
if not Assigned(ListItem) then
Exit;
if ListItem.Selected then
Include(State, cdsSelected);
if not ListItem.Selectable then
Include(State, cdsDisabled);
R := Rect(0, 0, w - 1, h - 1);
Canvas := TCanvas.Create;
Canvas.Handle := p;
Canvas.Start(False);
if DoCustomDrawViewBranch(ListItem, Canvas, R, State, TCustomDrawStage(stage)) then
stage := DrawStage_DefaultDraw;
Canvas.Stop;
Canvas.ReleaseHandle;
Canvas.Free;
except
Application.HandleException(Self);
end;
end;
procedure TCustomViewControl.ItemPaintHook(p: QPainterH;
item: QListViewItemH; column, width, alignment: Integer;
var stage: Integer);
function CDSStateToODState(cds: TCustomDrawState): TOwnerDrawState;
begin
Result := [];
if cdsSelected in cds then Include(Result, odSelected);
if cdsGrayed in cds then Include(Result, odGrayed);
if cdsDisabled in cds then Include(Result, odDisabled);
if cdsChecked in cds then Include(Result, odChecked);
if cdsFocused in cds then Include(Result, odFocused);
if cdsDefault in cds then Include(Result, odDefault);
end;
var
Canvas: TCanvas;
State: TCustomDrawState;
ListItem: TCustomViewItem;
R: TRect;
I: Integer;
begin
ListItem := TCustomViewItem(FindObject(QObjectH(item)));
if not Assigned(ListItem) then
Exit;
DoGetImageIndex(ListItem);
if not IsCustomDrawn then
begin
stage := DrawStage_DefaultDraw;
Exit;
end;
try
State := [];
if ListItem.Selected then
Include(State, cdsSelected);
if not ListItem.Selectable then
Include(State, cdsDisabled);
Canvas := TCanvas.Create;
Canvas.Handle := p;
Canvas.Start(False);
if cdsSelected in State then
begin
Canvas.Brush.Color := clHighlight;
Canvas.Font.Color := clHighlightText;
end
else begin
Canvas.Brush.Color := Color;
Canvas.Font.Color := Font.Color;
end;
R := Rect(0, 0, width, ListItem.Height);
if IsOwnerDrawn then
begin
for I := 1 to Columns.Count - 1 do
Inc(R.Right, Columns[I].Width);
DoDrawItem(ListItem, Canvas, R, CDSStateToODState(State));
end
else begin
if column = 0 then
begin
if DoCustomDrawViewItem(ListItem, Canvas, R, State, TCustomDrawStage(stage)) then
stage := DrawStage_DefaultDraw;
end
else if column < Columns.Count then
begin
I := 0;
while I < column do
begin
R.Left := R.Left + Columns[I].Width;
Inc(I);
end;
R.Right := R.Left + Columns[I].Width;
QPainter_translate(p, -R.Left, 0);
try
if DoCustomDrawViewSubItem(ListItem, column, Canvas, R, State,
TCustomDrawStage(stage)) then
stage := DrawStage_DefaultDraw;
finally
QPainter_translate(p, R.Left, 0);
end;
end;
end;
Canvas.Stop;
Canvas.ReleaseHandle;
Canvas.Free;
except
Application.HandleException(Self);
end;
end;
function TCustomViewControl.GetColumnClick: Boolean;
begin
Result := FHeader.Clickable;
end;
function TCustomViewControl.GetColumnMove: Boolean;
begin
Result := FHeader.DragReorder;
end;
function TCustomViewControl.GetColumnResize: Boolean;
begin
Result := FHeader.Resizable;
end;
function TCustomViewControl.GetColumns: TListColumns;
begin
Result := TListViewHeader(FHeader).GetSections;
end;
procedure TCustomViewControl.SetColumnClick(const Value: Boolean);
begin
if ColumnClick <> Value then
FHeader.Clickable := Value;
end;
procedure TCustomViewControl.SetShowColumnHeaders(const Value: Boolean);
begin
if FShowColumnHeaders <> Value then
begin
FShowColumnHeaders := Value;
if HandleAllocated then
TListViewHeader(FHeader).Hidden := not FShowColumnHeaders;
end;
end;
procedure TCustomViewControl.SetColumnMove(const Value: Boolean);
begin
if ColumnMove <> Value then
FHeader.DragReorder := Value;
end;
procedure TCustomViewControl.SetColumnResize(const Value: Boolean);
begin
if ColumnResize <> Value then
FHeader.Resizable := Value;
end;
procedure TCustomViewControl.SetColumns(const Value: TListColumns);
begin
FHeader.SetSections(Value);
end;
procedure TCustomViewControl.SetShowColumnSortIndicators(const Value: Boolean);
begin
if FShowColumnSortIndicators <> Value then
begin
FShowColumnSortIndicators := Value;
Sorted := FShowColumnSortIndicators;
if ShowColumnHeaders and HandleAllocated then
QListView_setShowSortIndicator(Handle, FShowColumnSortIndicators);
end;
end;
procedure TCustomViewControl.RepopulateItems;
begin
{ stubbed for children }
end;
procedure TCustomViewControl.UpdateControl;
begin
if HandleAllocated then
begin
QWidget_update(FHeader.Handle);
QListView_triggerUpdate(Handle);
end;
end;
function TCustomViewControl.DoCustomDrawViewBranch(Item: TCustomViewItem;
Canvas: TCanvas; const Rect: TRect; State: TCustomDrawState;
Stage: TCustomDrawStage): Boolean;
begin
Result := True;
if Assigned(FOnCustomDrawBranch) then FOnCustomDrawBranch(Self, Item,
Canvas, Rect, State, Stage, Result);
end;
procedure TCustomViewControl.ViewportDestroyed;
begin
try
CheckRemoveEditor;
except
Application.HandleException(Self);
end;
end;
function TCustomViewControl.ViewportHandle: QWidgetH;
begin
HandleNeeded;
Result := FViewportHandle;
end;
function TCustomViewControl.GetChildHandle: QWidgetH;
begin
Result := ViewportHandle;
end;
procedure TCustomViewControl.WidgetDestroyed;
begin
CheckRemoveEditor;
QClxObjectMap_remove(FViewportHandle);
FViewportHandle := nil;
if Assigned(FViewportHooks) then
begin
QWidget_hook_destroy(FViewportHooks);
FViewportHooks := nil;
end;
QClxObjectMap_remove(FVScrollHandle);
FVScrollHandle := nil;
if Assigned(FVScrollHooks) then
begin
QScrollBar_hook_destroy(FVScrollHooks);
FVScrollHooks := nil;
end;
QClxObjectMap_remove(FHScrollHandle);
FHScrollHandle := nil;
if Assigned(FHScrollHandle) then
begin
QScrollBar_hook_destroy(FHScrollHooks);
FHScrollHooks := nil;
end;
inherited WidgetDestroyed;
end;
procedure TCustomViewControl.Sort(Column: Integer; Direction: TSortDirection);
begin
SortColumn := Column;
SortDirection := Direction;
Sorted := True;
end;
procedure TCustomViewControl.SetSorted(const Value: Boolean);
begin
FSorted := Value;
if HandleAllocated then
begin
if FSorted then
QListView_setSorting(Handle, SortColumn, cSortDirection[SortDirection])
else
QListView_setSorting(Handle, -1, cSortDirection[SortDirection]);
end;
end;
{ TItemEditor }
constructor TItemEditor.Create(AOwner: TComponent);
begin
inherited Create(nil);
if AOwner is TCustomViewControl then
FViewControl := TCustomViewControl(AOwner);
InitItem;
end;
destructor TItemEditor.Destroy;
begin
if Assigned(FViewControl) then
FViewControl.FEditor := nil;
inherited Destroy;
end;
procedure TItemEditor.CreateWidget;
begin
FFrame := QFrame_create(FViewControl.ViewportHandle, nil, 0, True);
FFrameHooks := QFrame_hook_Create(FFrame);
QFrame_setFrameStyle(FFrame,
Integer(QFrameShape_Box) or Integer(QFrameShadow_Plain));
QWidget_setBackgroundMode(FFrame, QWidgetBackgroundMode_PaletteBase);
FHandle := QClxLineEdit_create(FFrame, nil);
Hooks := QLineEdit_hook_create(Handle);
end;
procedure TItemEditor.FrameDestroyedHook;
begin
try
FFrame := nil;
QFrame_hook_destroy(FFrameHooks);
FFrameHooks := nil;
except
Application.HandleException(Self);
end;
end;
procedure TItemEditor.HookEvents;
var
Method: TMethod;
begin
inherited HookEvents;
QObject_destroyed_event(Method) := FrameDestroyedHook;
QObject_hook_hook_destroyed(FFrameHooks, Method);
end;
procedure TItemEditor.InitItem;
var
Obj: TObject;
begin
if FViewControl is TCustomViewControl then
begin
Obj := TObject(QClxObjectMap_find(QListView_currentItem(FViewControl.Handle)));
if Obj is TCustomViewItem then
FItem := TCustomViewItem(Obj);
end;
end;
procedure TItemEditor.KeyDown(var Key: Word; Shift: TShiftState);
begin
FViewControl.KeyDown(Key, Shift);
end;
procedure TItemEditor.KeyUp(var Key: Word; Shift: TShiftState);
begin
FViewControl.KeyUp(Key, Shift);
end;
procedure TItemEditor.KeyPress(var Key: Char);
begin
FViewControl.KeyPress(Key);
end;
procedure TItemEditor.KeyString(var S: WideString; var Handled: Boolean);
begin
FViewControl.KeyString(S, Handled);
end;
function TItemEditor.PopupMenuFilter(Sender: QObjectH; Event: QEventH): Boolean;
var
FocusedWidget: QWidgetH;
begin
try
case QEvent_type(Event) of
QEventType_MouseButtonPress:
begin
FocusedWidget := QApplication_focusWidget(Application.Handle);
if not ((FocusedWidget = Handle) or
(FocusedWidget = FPopup)) then
FShouldClose := True;
end;
QEventType_Destroy:
ClearMenuHook;
end;
except
Application.HandleException(Self);
end;
Result := False;
end;
procedure TItemEditor.ClearMenuHook;
begin
if Assigned(FMenuHook) then
begin
QPopupMenu_hook_destroy(FMenuHook);
FPopup := nil;
FMenuHook := nil;
end;
end;
function TItemEditor.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
var
Obj: QObjectH;
Method: TMethod;
begin
if FEditing then
begin
if FShouldClose then
EditFinished(True);
case QEvent_type(Event) of
QEventType_ChildRemoved:
begin
Result := False;
Obj := QChildEvent_child(QChildEventH(Event));
if FPopup = Obj then
ClearMenuHook;
Exit;
end;
QEventType_ChildInserted:
begin
Result := False;
Obj := QChildEvent_child(QChildEventH(Event));
if QObject_isA(Obj, 'QPopupMenu') then
begin
FPopup := QPopupMenuH(Obj);
FMenuHook := QPopupMenu_hook_create(Obj);
TEventFilterMethod(Method) := PopupMenuFilter;
Qt_hook_hook_events(FMenuHook, Method);
end;
Exit;
end;
QEventType_FocusOut:
if QFocusEvent_reason <> QFocusEventReason_Popup then
EditFinished(True);
QEventType_KeyPress:
begin
case QKeyEvent_key(QKeyEventH(Event)) of
Key_Up,
Key_Down:
begin
Result := True;
Exit;
end;
Key_Escape: EditFinished(False);
Key_Return,
Key_Enter: EditFinished(True);
end;
end;
end;
end;
Result := inherited EventFilter(Sender, Event);
end;
procedure TItemEditor.Execute;
var
Pt: TPoint;
Offset: Integer;
ListItem: QListViewItemH;
ListHandle: QListViewH;
Allow: Boolean;
Pixmap: QPixmapH;
PixmapWidth: Integer;
begin
if not Assigned(FItem) then
EditFinished(False);
FEditing := True;
Allow := True;
FViewControl.DoEditing(FItem, Allow);
if not Allow then
begin
EditFinished(False);
Exit;
end;
HandleNeeded;
ListHandle := FViewControl.Handle;
ListItem := FItem.Handle;
Pt := FItem.DisplayRect.BottomRight;
if (Pt.X = -1) and (Pt.Y = -1) then
FItem.MakeVisible(False);
Offset := 0;
PixmapWidth := 0;
Pixmap := QListViewItem_pixmap(ListItem, 0);
if Assigned(Pixmap) then
PixmapWidth := QPixmap_width(Pixmap);
while Assigned(ListItem) do
begin
ListItem := QListViewItem_parent(ListItem);
Inc(Offset);
end;
Pt.X := Offset * QListView_treeStepSize(ListHandle);
if not QListView_rootIsDecorated(ListHandle) then
Dec(Pt.X, QListView_treeStepSize(ListHandle));
Inc(Pt.X, PixmapWidth);
Pt.Y := QListViewItem_itemPos(FItem.Handle);
QScrollView_contentsToViewport(ListHandle, @Pt, @Pt);
Left := QFrame_frameWidth(FFrame);
Top := QFrame_frameWidth(FFrame);
Width := QListView_columnWidth(ListHandle, 0);
QWidget_setGeometry(FFrame, Pt.X, Pt.Y,
(QListView_columnWidth(ListHandle, 0) - Pt.X),
QListViewItem_height(FItem.Handle));
Width := (QListView_columnWidth(ListHandle, 0) - Pt.X) -
(QFrame_frameWidth(FFrame) * 2);
BorderStyle := bsNone;
Text := FItem.Caption;
SelectAll;
QWidget_show(FFrame);
QWidget_setFixedHeight(Handle, QListViewItem_height(FItem.Handle) -
(QFrame_frameWidth(FFrame) * 2));
QWidget_show(Handle);
SetFocus;
end;
procedure TItemEditor.EditFinished(Accepted: Boolean);
var
S: WideString;
begin
if Assigned(FFrame) and Visible then
begin
if FEditing then
begin
FEditing := False;
ClearMenuHook;
if Assigned(FViewControl) and not (csDestroying in FViewControl.ComponentState) then
if Accepted and (Text <> FItem.Caption) then
begin
S := Text;
FViewControl.DoEdited(FItem, S);
FItem.Caption := S;
end;
Visible := False;
if Assigned(FFrame) then
QApplication_postEvent(Application.Handle,
QCustomEvent_create(QEventType_CMDestroyWidget, FFrame));
if Assigned(FViewControl) and not (csDestroying in FViewControl.ComponentState) then
FViewControl.SetFocus;
end;
end;
end;
{ TCustomViewItem }
constructor TCustomViewItem.Create(AOwner: TCustomViewItems; AParent, After: TCustomViewItem);
begin
inherited Create;
FOwner := AOwner;
FParent := AParent;
FPrevItem := After;
if Assigned(FPrevItem) then
FPrevItem.FNextItem := Self;
FImageIndex := -1;
FSelectable := True;
FExpandable := False;
if Assigned(Owner) then
begin
DetermineCreationType;
CreateWidget(AParent, After);
end;
end;
destructor TCustomViewItem.Destroy;
begin
FDestroying := True;
if ViewControlValid and not (csDestroying in Owner.Owner.ComponentState) then
begin
Owner.BeginUpdate;
try
if HandleAllocated then
while QListViewItem_childCount(Handle) > 0 do
Owner.FindViewItem(QListViewItem_firstChild(Handle)).Free;
if not Assigned(Parent) or (Assigned(Parent) and not Parent.FDestroying) then
begin
Selected := False;
if Assigned(FNextItem) then
FNextItem.Selected := True
else if Assigned(FPrevItem) then
FPrevItem.Selected := True
else if Assigned(Parent) then
Parent.Selected := True;
end;
finally
Owner.EndUpdate;
end;
end;
Parent := nil;
if Assigned(FNextItem) then
FNextItem.FPrevItem := FPrevItem;
if Assigned(FPrevItem) then
FPrevItem.FNextItem := FNextItem;
if Assigned(Owner) then
Owner.FItems.Extract(Self);
if Assigned(FSubItems) then
FSubItems.Free;
if HandleAllocated then
DestroyWidget;
inherited Destroy;
end;
procedure TCustomViewItem.AssignTo(Dest: TPersistent);
begin
if Dest is TCustomViewItem then
begin
TCustomViewItem(Dest).Selected := Selected;
TCustomViewItem(Dest).Selectable := Selectable;
TCustomViewItem(Dest).Expanded := Expanded;
TCustomViewItem(Dest).Expandable := Expandable;
TCustomViewItem(Dest).Caption := Caption;
TCustomViewItem(Dest).Checked := Checked;
TCustomViewItem(Dest).Data := Data;
TCustomViewItem(Dest).Focused := Focused;
TCustomViewItem(Dest).ImageIndex := ImageIndex;
TCustomViewItem(Dest).ItemType := ItemType;
TCustomViewItem(Dest).SubItems.Assign(SubItems);
end
else
inherited AssignTo(Dest);
end;
procedure TCustomViewItem.Collapse;
begin
Expanded := False;
end;
procedure TCustomViewItem.CreateWidget(AParent, After: TCustomViewItem);
const
cType: array [TListViewItemType] of QCheckListItemType = (QCheckListItemtype_CheckBox,
QCheckListItemtype_CheckBox, QCheckListItemtype_RadioButton, QCheckListItemtype_Controller);
var
ParentH: QListViewItemH;
AfterH: QListViewItemH;
ParentListViewH: QListViewH;
begin
ParentH := nil;
AfterH := nil;
ParentListViewH := nil;
FHandle := nil;
if Assigned(AParent) then
ParentH := AParent.Handle
else
if ViewControlValid then
ParentListViewH := ViewControl.Handle
else
ParentListViewH := nil;
if Assigned(After) then
AfterH := After.Handle;
case FItemType of
itDefault:
begin
if Assigned(ParentListViewH) then
FHandle := QClxListViewItem_create(ParentListViewH, AfterH, ItemHook)
else
FHandle := QClxListViewItem_create(ParentH, AfterH, ItemHook);
end;
else
begin
if Assigned(ParentListViewH) then
FHandle := QClxCheckListItem_create(ParentListViewH,
PWideString(@FText), cType[FItemType], ItemHook)
else
FHandle := QClxCheckListItem_create(ParentH, PWideString(@FText),
cType[FItemType], ItemHook);
if Assigned(AfterH) then
QListViewItem_moveItem(FHandle, AfterH);
end;
end;
QClxObjectMap_add(FHandle, Integer(Self));
end;
procedure TCustomViewItem.Delete;
begin
Free;
end;
procedure TCustomViewItem.DestroyWidget;
begin
if HandleAllocated then
begin
QClxObjectMap_remove(FHandle);
if Assigned(Owner) and ViewControlValid then
QListViewItem_destroy(FHandle);
end;
FHandle := nil;
end;
procedure TCustomViewItem.DetermineCreationType;
begin
if Assigned(Owner) and (Owner.Owner is TCustomListView) then
if TCustomListView(Owner.Owner).CheckBoxes then
FItemType := itCheckBox;
end;
procedure TCustomViewItem.Expand;
begin
Expanded := True;
end;
function TCustomViewItem.GetChildCount: Integer;
begin
if ViewControlValid and HandleAllocated then
Result := QListViewItem_childCount(Handle)
else
Result := -1;
end;
function TCustomViewItem.GetFocused: Boolean;
begin
if ViewControlValid and HandleAllocated then
Result := QListView_currentItem(Owner.Owner.Handle) = Handle
else
Result := False;
end;
function TCustomViewItem.GetHeight: Integer;
begin
if ViewControlValid and HandleAllocated then
Result := QListViewItem_height(Handle)
else
Result := -1;
end;
function TCustomViewItem.GetSubItemImages(Column: Integer): Integer;
begin
if (Column >= 0) and (Column < SubItems.Count) then
Result := Integer(SubItems.Objects[Column])
else
Result := -1;
end;
function TCustomViewItem.GetExpanded: Boolean;
begin
if HandleAllocated then
Result := QListViewItem_isOpen(Handle)
else
Result := False;
end;
function TCustomViewItem.GetHandle: QListViewItemH;
begin
if not HandleAllocated then
CreateWidget(FParent, FPrevItem);
Result := FHandle;
end;
function TCustomViewItem.GetSubItems: TStrings;
begin
if not Assigned(FSubItems) then
FSubItems := TSubItems.Create(Self);
Result := FSubItems;
end;
function TCustomViewItem.GetTotalHeight: Integer;
begin
if ViewControlValid and HandleAllocated then
Result := QListViewItem_totalHeight(Handle)
else
Result := -1;
end;
function TCustomViewItem.GetIndex: Integer;
begin
if Assigned(Owner) then
Result := Owner.FItems.IndexOf(Self)
else
Result := -1;
end;
function TCustomViewItem.GetSelected: Boolean;
begin
if HandleAllocated then
Result := QListViewItem_isSelected(Handle)
else
Result := False;
end;
function TCustomViewItem.HandleAllocated: Boolean;
begin
Result := FHandle <> nil;
end;
procedure TCustomViewItem.ImageIndexChange(ColIndex, NewIndex: Integer);
var
Pixmap: QPixmapH;
begin
if ViewControlValid and HandleAllocated and Assigned(ViewControl.Images) then
begin
Pixmap := ViewControl.Images.GetPixmap(NewIndex);
if Assigned(Pixmap) then
QListViewItem_setPixmap(Handle, ColIndex, Pixmap)
else
begin
Pixmap := QPixmap_create;
try
QListViewItem_setPixmap(Handle, ColIndex, Pixmap);
finally
QPixmap_destroy(Pixmap);
end;
end;
end;
end;
procedure TCustomViewItem.InsertItem(AItem: TCustomViewItem);
begin
if Assigned(AItem) then
begin
AItem.FParent := Self;
AItem.FPrevItem := FLastChild;
AItem.FNextItem := nil;
if HandleAllocated and AItem.HandleAllocated then
QListViewItem_insertItem(Handle, AItem.Handle);
if Assigned(FLastChild) then
begin
FLastChild.FNextItem := AItem;
if HandleAllocated then
QListViewItem_moveItem(AItem.Handle, FLastChild.Handle);
end;
FLastChild := AItem;
end;
end;
function TCustomViewItem.ParentCount: Integer;
var
Temp: QListViewItemH;
begin
Result := 0;
if ViewControlValid and HandleAllocated then
begin
Temp := QListViewItem_parent(Handle);
while Assigned(Temp) do
begin
Inc(Result);
Temp := QListViewItem_parent(Temp);
end;
end;
end;
procedure TCustomViewItem.ReCreateItem;
begin
FDestroying := True;
try
DestroyWidget;
CreateWidget(FParent, FPrevItem);
ResetFields;
finally
FDestroying := False;
end;
end;
procedure TCustomViewItem.RemoveItem(AItem: TCustomViewItem);
begin
if Assigned(AItem) then
begin
if FLastChild = AItem then
FLastChild := AItem.FPrevItem;
if HandleAllocated then
begin
if AItem.HandleAllocated then
QListViewItem_takeItem(Handle, AItem.Handle);
if HandleAllocated and (QListViewItem_childCount(Handle) = 0) then
Expandable := False;
end;
AItem.FParent := nil;
end;
end;
procedure TCustomViewItem.Repaint;
begin
if HandleAllocated then
QListViewItem_repaint(Handle);
end;
procedure TCustomViewItem.ResetFields;
var
I: Integer;
Temp: WideString;
begin
if HandleAllocated then
begin
if ViewControlValid then
begin
QListViewItem_setText(Handle, 0, PWideString(@FText));
if ItemType <> itDefault then
QCheckListItem_setOn(QCheckListItemH(FHandle), FChecked);
QListViewItem_setExpandable(Handle, FExpandable);
QListViewItem_setSelectable(Handle, FSelectable);
end;
if Assigned(FSubItems) then
for I := 0 to SubItems.Count-1 do
begin
Temp := SubItems[I];
QListViewItem_setText(Handle, I + 1, PWideString(@Temp));
ImageIndexChange(I + 1, SubItemImages[I]);
end;
end;
end;
procedure TCustomViewItem.SetCaption(const Value: WideString);
begin
if Caption <> Value then
begin
if HandleAllocated then
begin
if Assigned(Owner) then
QListViewItem_setText(Handle, 0, PWideString(@Value));
QListViewItem_text(Handle, PWideString(@FText), 0);
end
else
FText := Value;
end;
end;
procedure TCustomViewItem.SetChecked(const Value: Boolean);
begin
if Checked <> Value then
begin
if ViewControlValid and HandleAllocated and (ItemType <> itDefault) then
QCheckListItem_setOn(QCheckListItemH(Handle), Value);
FChecked := Value;
end;
end;
procedure TCustomViewItem.SetSubItemImages(Column: Integer;
const Value: Integer);
begin
if (Column >= 0) and (Column < SubItems.Count) then
SubItems.Objects[Column] := Pointer(Value);
end;
procedure TCustomViewItem.SetExpandable(const Value: Boolean);
begin
if Expandable <> Value then
begin
FExpandable := Value;
if ViewControlValid and HandleAllocated then
QListViewItem_setExpandable(Handle, FExpandable);
end;
end;
procedure TCustomViewItem.SetExpanded(const Value: Boolean);
var
AItem: QListViewItemH;
ARect: TRect;
begin
if (Expanded <> Value) and HandleAllocated then
begin
QListViewItem_setOpen(Handle, Value);
if not Expanded and ViewControlValid then
begin
AItem := QListView_currentItem(ViewControl.Handle);
while Assigned(AItem) do
begin
if (AItem = Handle) then
Break;
AItem := QListViewItem_parent(AItem);
end;
if Assigned(AItem) then
begin
repeat
QListView_itemRect(ViewControl.Handle, @ARect, AItem);
if QListViewItem_isOpen(AItem) or
((ARect.Right >= 0) and (ARect.Bottom >= 0)) then
begin
QListView_setCurrentItem(ViewControl.Handle, AItem);
Exit;
end;
AItem := QListViewItem_parent(AItem);
until not Assigned(AItem);
end;
end;
end;
end;
procedure TCustomViewItem.SetFocused(const Value: Boolean);
begin
if ViewControlValid and HandleAllocated and (Value <> GetFocused) then
QListView_setCurrentItem(ViewControl.Handle, Handle);
end;
procedure TCustomViewItem.SetImageIndex(const Value: TImageIndex);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
ImageIndexChange(0, FImageIndex);
end;
end;
procedure TCustomViewItem.SetItemType(const Value: TListViewItemType);
var
ChildrenArray: array of QListViewItemH;
Temp: QListViewItemH;
I: Integer;
begin
if FItemType <> Value then
begin
if (Value = itRadioButton) then
if (not Assigned(FParent)) or (FParent.ItemType <> itController) then
raise EListViewException.Create(sListRadioItemBadParent);
if HandleAllocated then
begin
if ViewControlValid then
begin
SetLength(ChildrenArray, QListViewItem_childCount(Handle));
if Length(ChildrenArray) > 0 then
begin
I := 0;
while True do
begin
Temp := QListViewItem_firstChild(Handle);
if not Assigned(Temp) then
Break;
QListViewItem_takeItem(Handle, Temp);
ChildrenArray[I] := Temp;
Inc(I);
end;
end;
end;
FItemType := Value;
ReCreateItem;
if ViewControlValid and (Length(ChildrenArray) > 0) then
begin
I := 0;
while (I < Length(ChildrenArray)) and (Assigned(ChildrenArray[I])) do
begin
QListViewItem_insertItem(Handle, ChildrenArray[I]);
Inc(I);
end;
end;
end;
end;
end;
procedure TCustomViewItem.SetParent(const Value: TCustomViewItem);
begin
if Assigned(FPrevItem) then
FPrevItem.FNextItem := FNextItem;
if Assigned(FNextItem) then
FNextItem.FPrevItem := FPrevItem;
if Assigned(FParent) then
FParent.RemoveItem(Self);
FPrevItem := nil;
FNextItem := nil;
FParent := Value;
if Assigned(FParent) then
FParent.InsertItem(Self);
end;
procedure TCustomViewItem.SetSelectable(const Value: Boolean);
begin
if Selectable <> Value then
begin
FSelectable := Value;
if ViewControlValid and HandleAllocated then
QListViewItem_setSelectable(Handle, FSelectable);
end;
end;
procedure TCustomViewItem.SetSelected(const Value: Boolean);
begin
if (Selected <> Value) and HandleAllocated then
begin
if ViewControlValid then
QListView_setSelected(ViewControl.Handle, Handle, Value)
else
QListViewItem_setSelected(Handle, Value);
if Value and ViewControlValid and ViewControl.Visible then
MakeVisible(False);
end;
end;
function TCustomViewItem.ViewControl: TCustomViewControl;
begin
Result := nil;
if ViewControlValid then
Result := Owner.Owner;
end;
function TCustomViewItem.ViewControlValid: Boolean;
begin
Result := Assigned(FOwner) and Assigned(FOwner.FOwner) and
not (csRecreating in FOwner.FOwner.ControlState);
end;
function TCustomViewItem.ItemHook: QClxListViewHooksH;
begin
Result := nil;
if ViewControlValid then
Result := ViewControl.FItemHooks;
end;
function TCustomViewItem.DisplayRect: TRect;
begin
if ViewControlValid and HandleAllocated then
QListView_itemRect(ViewControl.Handle, @Result, Handle)
else
Result := Rect(0, 0, -1, -1);
end;
function TCustomViewItem.GetWidth: Integer;
var
R: TRect;
begin
R := DisplayRect;
Result := R.Right - R.Left;
end;
procedure TCustomViewItem.SetSubItems(const Value: TStrings);
begin
if SubItems <> Value then
SubItems.Assign(Value);
end;
procedure TCustomViewItem.UpdateImages;
var
I: Integer;
ImgList: TCustomImageList;
EmptyPix: QPixmapH;
Pixmap: QPixmapH;
begin
if HandleAllocated then
begin
ImgList := ViewControl.Images;
EmptyPix := QPixmap_create;
try
if Assigned(ImgList) then
begin
Pixmap := ImgList.GetPixmap(ImageIndex);
if not Assigned(Pixmap) then
Pixmap := EmptyPix;
QListViewItem_setPixmap(Handle, 0, Pixmap);
for I := 0 to SubItems.Count-1 do
begin
Pixmap := ImgList.GetPixmap(SubItemImages[I]);
if not Assigned(Pixmap) then
Pixmap := EmptyPix;
QListViewItem_setPixmap(Handle, I+1, Pixmap);
end;
end
else
begin
QListViewItem_setPixmap(Handle, 0, EmptyPix);
for I := 0 to SubItems.Count-1 do
QListViewItem_setPixmap(Handle, I+1, EmptyPix);
end;
finally
if Assigned(EmptyPix) then
QPixmap_destroy(EmptyPix);
end;
end;
end;
procedure TCustomViewItem.MakeVisible(PartialOK: Boolean);
var
ARect: TRect;
begin
if ViewControlValid and HandleAllocated then
begin
if PartialOK then
begin
ARect := DisplayRect;
if (ARect.Left <> -1) and (ARect.Top <> -1) and
(ARect.Right <> -1) and (ARect.Bottom <> -1) then
Exit;
end;
QListView_ensureItemVisible(ViewControl.Handle, Handle);
end;
end;
{ TCustomViewItems }
procedure TCustomViewItems.Clear;
begin
BeginUpdate;
try
while Count > 0 do
Item[0].Free;
finally
EndUpdate;
end;
end;
constructor TCustomViewItems.Create(AOwner: TCustomViewControl);
begin
inherited Create;
FOwner := AOwner;
FItems := TViewItemsList.Create;
end;
destructor TCustomViewItems.Destroy;
begin
try
BeginUpdate;
FItems.Free;
finally
EndUpdate;
end;
inherited Destroy;
end;
function TCustomViewItems.GetHandle: QListViewH;
begin
if Owner <> nil then
Result := Owner.Handle
else
Result := nil;
end;
function TCustomViewItems.GetItem(Index: Integer): TCustomViewItem;
begin
Result := FItems[Index];
end;
procedure TCustomViewItems.ChangeItemTypes(NewType: TListViewItemType);
var
I: Integer;
begin
BeginUpdate;
try
for I := 0 to Count-1 do
Item[I].ItemType := NewType;
finally
EndUpdate;
end;
end;
function TCustomViewItems.IndexOf(Value: TCustomViewItem): Integer;
begin
Result := FItems.IndexOf(Value);
end;
procedure TCustomViewItems.SetItem(Index: Integer; const Value: TCustomViewItem);
begin
if (Index < Count-1) and (Index >= 0) then
if Assigned(FItems[Index]) then
FItems[Index].Assign(Value)
else
FItems[Index] := Value;
end;
function TCustomViewItems.GetCount: Integer;
begin
Result := FItems.Count;
end;
procedure TCustomViewItems.BeginUpdate;
begin
if FUpdateCount = 0 then
SetUpdateState(True);
Inc(FUpdateCount);
end;
procedure TCustomViewItems.EndUpdate;
begin
Dec(FUpdateCount);
if FUpdateCount = 0 then
SetUpdateState(False);
end;
procedure TCustomViewItems.SetUpdateState(Updating: Boolean);
begin
if not (csDestroying in Owner.ComponentState) and Owner.HandleAllocated then
begin
if FUpdateCount = 0 then
begin
QWidget_setUpdatesEnabled(Owner.Handle, not Updating);
QWidget_setUpdatesEnabled(QScrollView_viewport(Owner.Handle), not Updating);
if not Updating then
QListView_triggerUpdate(Owner.Handle);
end;
end;
end;
{ TCustomListView }
function TCustomListView.IsOwnerDrawn: Boolean;
begin
Result := FOwnerDraw and (ViewStyle = vsReport) and Assigned(FOnDrawItem);
end;
procedure TCustomListView.ItemChange(item: QListViewItemH; _type: TItemChange);
begin
if Assigned(FOnChange) then
FOnChange(Self, FItems.FindItem(item), _type);
end;
procedure TCustomListView.ItemChanging(item: QListViewItemH; _type: TItemChange;
var Allow: Boolean);
var
AItem: TListItem;
begin
AItem := FItems.FindItem(item);
if Assigned(AItem) and not AItem.FDestroying then
begin
if Assigned(FOnChanging) then
FOnChanging(Self, AItem, _type, Allow);
if (AItem <> FSelected) and (_type = ctState) then
StartEditTimer;
end;
end;
procedure TCustomListView.ItemChecked(item: QListViewItemH; Checked: Boolean);
var
AItem: TListItem;
begin
AItem := Items.FindItem(item);
if Assigned(AItem) then
AItem.FChecked := Checked;
StartEditTimer;
end;
procedure TCustomListView.ItemDestroyed(AItem: QListViewItemH);
var
ListItem: TListItem;
begin
ListItem := FItems.FindItem(AItem);
if Assigned(ListItem) then
begin
QClxObjectMap_remove(ListItem.FHandle);
ListItem.FHandle := nil;
if not (csDestroying in ComponentState) and (FHeader is TListViewHeader) then
if (not TListViewHeader(FHeader).FHiddenChanging) and not ListItem.FDestroying then
ListItem.Free;
end;
end;
procedure TCustomListView.ItemSelected(item: QListViewItemH; wasSelected: Boolean);
const
cIncSelCount: array [Boolean] of Integer = (-1, 1);
begin
Inc(FSelCount, cIncSelCount[wasSelected]);
if FSelCount > 0 then
FSelected := FItems.FindItem(item)
else
FSelected := nil;
if Assigned(FOnSelectItem) then
FOnSelectItem(Self, FSelected, wasSelected);
end;
function TCustomListView.AlphaSort: Boolean;
begin
Result := True;
try
{ The 0th column is the one associated with the TListItem }
if HandleAllocated then
QListView_setSorting(Handle, 0, SortDirection = sdAscending);
except
Result := False;
end;
end;
procedure TCustomListView.SetTopItem(const AItem: TListItem);
var
NewTopH: Integer;
begin
if Assigned(AItem) and HandleAllocated then
begin
NewTopH := QListView_itemPos(Handle, AItem.Handle);
QListView_setContentsPos(Handle, QScrollView_contentsX(Handle), NewTopH);
end;
end;
function TCustomListView.GetTopItem: TListItem;
var
Pt: TPoint;
AItem: QListViewItemH;
begin
Result := nil;
if HandleAllocated then
begin
Pt := Point(1, 1);
AItem := QListView_itemAt(Handle, @Pt);
if not Assigned(AItem) then
Exit;
Result := FItems.FindItem(AItem);
end;
end;
function TCustomListView.GetDropTarget: TListItem;
var
Temp: TCustomViewItem;
begin
Result := nil;
Temp := FindDropTarget;
if Temp is TListItem then
Result := TListItem(Temp);
end;
function TCustomListView.FindData(StartIndex: Integer; Value: Pointer;
Inclusive, Wrap: Boolean): TListItem;
var
I: Integer;
Item: TListItem;
begin
Result := nil;
if Inclusive then Dec(StartIndex);
for I := StartIndex + 1 to Items.Count - 1 do
begin
Item := Items[I];
if (Item <> nil) and (Item.Data = Value) then
begin
Result := Item;
Exit;
end;
end;
if Wrap then
begin
if Inclusive then Inc(StartIndex);
for I := 0 to StartIndex - 1 do
begin
Item := Items[I];
if (Item <> nil) and (Item.Data = Value) then
begin
Result := Item;
Exit;
end;
end;
end;
end;
function TCustomListView.GetItemAt(X, Y: Integer): TListItem;
var
Temp: QListViewItemH;
Pt: TPoint;
begin
Result := nil;
if HandleAllocated then
begin
Pt := Types.Point(X, Y);
Temp := QListView_itemAt(Handle, @Pt);
Result := Items.FindItem(Temp);
end;
end;
function TCustomListView.GetSelected: TListItem;
begin
Result := FSelected;
end;
procedure TCustomListView.SetSelected(const Value: TListItem);
begin
if not (csDestroying in ComponentState) then
begin
if Assigned(FSelected) then
FSelected.Selected := False;
if Assigned(Value) then
Value.Selected := True;
end;
FSelected := Value;
end;
procedure TCustomListView.HookEvents;
var
Method: TMethod;
begin
inherited HookEvents;
QListView_mouseButtonClicked_Event(Method) := DoItemClick;
QListView_hook_hook_mouseButtonClicked(QListView_hookH(Hooks), Method);
end;
procedure TCustomListView.ImageListChanged;
var
I: Integer;
begin
for I := 0 to Items.Count-1 do
Items[I].UpdateImages;
end;
function TCustomListView.FindCaption(StartIndex: Integer;
const Value: WideString; Partial, Inclusive, Wrap: Boolean): TListItem;
const
cInclusive: array [Boolean] of Integer = (1, 0);
var
I: Integer;
begin
Result := nil;
if (StartIndex < 0) or (StartIndex >= Items.Count) then
Exit;
if not Partial then
begin
for I := StartIndex + cInclusive[Inclusive] to Items.Count-1 do
begin
Result := Items[I];
if WideCompareText(Value, Result.Caption) = 0 then
Exit;
end;
if Wrap then
for I := 0 to StartIndex - cInclusive[not Inclusive] do
begin
Result := Items[I];
if WideCompareText(Value, Result.Caption) = 0 then
Exit;
end;
Result := nil;
end
else
begin
for I := StartIndex + cInclusive[Inclusive] to Items.Count-1 do
begin
Result := Items[I];
if Pos(Value, Result.Caption) = 1 then
Exit;
end;
if Wrap then
for I := 0 to StartIndex - cInclusive[not Inclusive] do
begin
Result := Items[I];
if Pos(Value, Result.Caption) = 1 then
Exit;
end;
Result := nil;
end;
end;
procedure TCustomListView.Scroll(DX, DY: Integer);
begin
if HandleAllocated then
QScrollView_scrollBy(Handle, DX, DY);
end;
function TCustomListView.GetItemFocused: TListItem;
begin
if HandleAllocated then
Result := TListItem(QClxObjectMap_find(QListView_currentItem(Handle)))
else
Result := nil;
end;
procedure TCustomListView.SetItemFocused(const Value: TListItem);
begin
if Assigned(Value) and HandleAllocated then
QListView_setCurrentItem(Handle, Value.Handle);
end;
procedure TCustomListView.InitWidget;
begin
inherited InitWidget;
ShowColumnHeaders := FViewStyle = vsReport;
QListView_setRootIsDecorated(Handle, False);
end;
procedure TCustomListView.SetCheckBoxes(const Value: Boolean);
begin
if FCheckBoxes <> Value then
begin
FCheckBoxes := Value;
UpdateItemTypes;
end;
end;
procedure TCustomListView.UpdateItemTypes;
const
cNewType: array [Boolean] of TListViewItemType = (itDefault, itCheckBox);
begin
FItems.ChangeItemTypes(cNewType[FCheckBoxes]);
end;
procedure TCustomListView.UpdateItems(FirstIndex, LastIndex: Integer);
var
I: Integer;
begin
for I := FirstIndex to LastIndex do
Items[I].Repaint;
end;
constructor TCustomListView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Init(TListItem);
end;
constructor TCustomListView.Create(AOwner: TComponent;
AListItemClass: TListItemClass);
begin
inherited Create(AOwner);
Init(AListItemClass);
end;
destructor TCustomListView.Destroy;
begin
if Assigned(FMemStream) then
FreeAndNil(FMemStream);
FItems.Free;
inherited Destroy;
end;
procedure TCustomListView.Init(AListItemClass: TListItemClass);
begin
FItems := TListItems.Create(Self, AListItemClass);
FViewStyle := vsList;
ColumnClick := True;
ColumnMove := True;
ColumnResize := True;
Palette.ColorRole := crBase;
Palette.TextColorRole := crText;
end;
procedure TCustomListView.DoGetImageIndex(item: TCustomViewItem);
begin
if Assigned(FOnGetImageIndex) and (item is TListItem) then
FonGetImageIndex(Self, TListItem(item));
end;
procedure TCustomListView.DoDrawItem(Item: TCustomViewItem; Canvas: TCanvas;
const Rect: TRect; State: TOwnerDrawState);
begin
if Assigned(FOnDrawItem) then
FOnDrawItem(Self, TListItem(Item), Canvas, Rect, State);
end;
procedure TCustomListView.DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean);
begin
if Assigned(FOnEditing) and (AItem is TListItem) then
FOnEditing(Self, TListItem(AItem), AllowEdit);
end;
procedure TCustomListView.DoEdited(AItem: TCustomViewItem; var S: WideString);
begin
if Assigned(FOnEdited) and (AItem is TListItem) then
FOnEdited(Self, TListItem(AItem), S);
end;
procedure TCustomListView.SetItems(const Value: TListItems);
begin
if FItems <> Value then
FItems.Assign(Value);
end;
function TCustomListView.GetNearestItem(const Point: TPoint;
Direction: TSearchDirection): TListItem;
var
Temp: TListItem;
begin
Result := nil;
Temp := GetItemAt(Point.x, Point.y);
if Assigned(Temp) and Temp.HandleAllocated then
begin
case Direction of
sdAbove: Result := Items.FindItem(QListViewItem_itemAbove(Temp.Handle));
sdBelow: Result := Items.FindItem(QListViewItem_itemBelow(Temp.Handle));
end;
end;
end;
function TCustomListView.GetNextItem(StartItem: TListItem;
Direction: TSearchDirection; States: TItemStates): TListItem;
var
AIndex: Integer;
begin
Result := nil;
if Assigned(StartItem) and StartItem.HandleAllocated and HandleAllocated then
begin
AIndex := StartItem.Index;
while True do
begin
case Direction of
sdAbove: Result := Items.FindItem(QListViewItem_itemAbove(StartItem.Handle));
sdBelow: Result := Items.FindItem(QListViewItem_itemBelow(StartItem.Handle));
sdAll:
begin
Inc(AIndex);
if AIndex >= Items.Count then
AIndex := 0;
Result := Items[AIndex];
end;
end;
if Result = nil then
Exit;
if (Result.States * States <> []) then
Exit;
StartItem := Result;
end;
end;
end;
procedure TCustomListView.DoItemClick(Button: Integer; ListItem: QListViewItemH;
Pt: PPoint; ColIndex: Integer);
var
AItem: TListItem;
begin
try
AItem := FItems.FindItem(ListItem);
if Assigned(AItem) then
begin
if Assigned(FOnItemClick) then
FOnItemClick(Self, ButtonToMouseButton(Button), AItem, Pt^, ColIndex);
if (ColIndex = 0) and FAllowEdit then
EditItem;
end;
except
Application.HandleException(Self);
end;
end;
procedure TCustomListView.SetOnItemDoubleClick(const Value: TLVItemDoubleClickEvent);
var
Method: TMethod;
begin
FOnItemDoubleClick := Value;
if Assigned(FOnItemDoubleClick) then
QListView_doubleClicked_Event(Method) := DoItemDoubleClick
else
Method := NullHook;
QListView_hook_hook_doubleClicked(QListView_hookH(Hooks), Method);
end;
procedure TCustomListView.DoItemDoubleClick(ListItem: QListViewItemH);
var
AItem: TListItem;
begin
if Assigned(FOnItemDoubleClick) then
try
AItem := FItems.FindItem(ListItem);
FOnItemDoubleClick(Self, AItem);
except
Application.HandleException(Self);
end;
end;
procedure TCustomListView.SetOnItemEnter(const Value: TLVNotifyEvent);
var
Method: TMethod;
begin
FOnItemEnter := Value;
if Assigned(FOnItemEnter) then
QListView_onItem_Event(Method) := DoOnItemEnter
else
Method := NullHook;
QListView_hook_hook_onItem(QListView_hookH(Hooks), Method);
end;
procedure TCustomListView.SetOnItemExitViewportEnter(const Value: TLVItemExitViewportEnterEvent);
var
Method: TMethod;
begin
FOnItemExitViewportEnter := Value;
if Assigned(FOnItemExitViewportEnter) then
QListView_onViewport_Event(Method) := DoOnItemExitViewportEnter
else
Method := NullHook;
QListView_hook_hook_onViewport(QListView_hookH(Hooks), Method);
end;
procedure TCustomListView.DoOnItemEnter(ListItem: QListViewItemH);
var
AItem: TListItem;
begin
if Assigned(FOnItemEnter) then
try
AItem := FItems.FindItem(ListItem);
FOnItemEnter(Self, AItem);
except
Application.HandleException(Self);
end;
end;
procedure TCustomListView.DoOnItemExitViewportEnter;
begin
if Assigned(FOnItemExitViewportEnter) then
try
FOnItemExitViewportEnter(Self);
except
Application.HandleException(Self);
end;
end;
procedure TCustomListView.SetOnMouseDown(const Value: TLVButtonDownEvent);
begin
FOnMouseDown := Value;
HookMouseDowns;
end;
procedure TCustomListView.DoLVMouseDown(Button: Integer; ListItem: QListViewItemH; Pt: PPoint; ColIndex: Integer);
var
AItem: TListItem;
begin
try
AItem := FItems.FindItem(ListItem);
if Assigned(FOnMouseDown) and Assigned(AItem) then
FOnMouseDown(Self, ButtonToMouseButton(Button), AItem, Pt^, ColIndex)
else if Assigned(FOnViewportMouseDown) and not Assigned(AItem) then
FOnViewportMouseDown(Self, ButtonToMouseButton(Button), Pt^);
except
Application.HandleException(Self);
end;
end;
procedure TCustomListView.SetOnViewportButtonDown(const Value: TLVViewportButtonDownEvent);
begin
FOnViewportMouseDown := Value;
HookMouseDowns;
end;
procedure TCustomListView.HookMouseDowns;
var
Method: TMethod;
begin
if Assigned(FOnMouseDown) or Assigned(FOnViewportMouseDown) then
begin
if FDownsHooked then
Exit;
QListView_mouseButtonPressed_Event(Method) := DoLVMouseDown;
FDownsHooked := True;
end
else
begin
Method := NullHook;
FDownsHooked := False;
end;
QListView_hook_hook_mouseButtonPressed(QListView_hookH(Hooks), Method);
end;
procedure TCustomListView.SetViewStyle(const Value: TViewStyle);
begin
if FViewStyle <> Value then
begin
FViewStyle := Value;
ShowColumnHeaders := FViewStyle = vsReport;
end;
end;
procedure TCustomListView.RepopulateItems;
var
I: Integer;
begin
if HandleAllocated then
begin
if (QListView_childCount(Handle) = 0) and (QListView_columns(Handle) > 0) then
begin
Items.BeginUpdate;
try
for I := 0 to Items.Count-1 do
Items[I].ReCreateItem;
finally
Items.EndUpdate;
end;
end
else
begin
Items.BeginUpdate;
try
for I := 0 to Items.Count-1 do
Items[I].ResetFields;
finally
Items.EndUpdate;
end;
end;
end;
end;
procedure TCustomListView.RestoreWidgetState;
begin
inherited RestoreWidgetState;
if Assigned(FMemStream) then
begin
FMemStream.Position := 0;
FItems.ReadData(FMemStream);
FreeAndNil(FMemStream);
end;
end;
procedure TCustomListView.SaveWidgetState;
begin
inherited SaveWidgetState;
FMemStream := TMemoryStream.Create;
FItems.WriteData(FMemStream);
FItems.Clear;
end;
{ TTreeStrings }
type
TTreeStrings = class(TStrings)
private
FOwner: TTreeNodes;
protected
function Get(Index: Integer): string; override;
function GetBufStart(Buffer: PChar; var Level: Integer): PChar;
function GetCount: Integer; override;
function GetObject(Index: Integer): TObject; override;
procedure PutObject(Index: Integer; AObject: TObject); override;
public
constructor Create(AOwner: TTreeNodes);
function Add(const S: string): Integer; override;
procedure Clear; override;
procedure Delete(Index: Integer); override;
procedure Insert(Index: Integer; const S: string); override;
procedure LoadTreeFromStream(Stream: TStream);
procedure SaveTreeToStream(Stream: TStream);
property Owner: TTreeNodes read FOwner;
end;
constructor TTreeStrings.Create(AOwner: TTreeNodes);
begin
inherited Create;
FOwner := AOwner;
end;
function TTreeStrings.Get(Index: Integer): string;
const
TabChar = #9;
var
Level, I: Integer;
Node: TTreeNode;
begin
Result := '';
Node := Owner.Item[Index];
if not Assigned(Node) then
Exit;
Level := Node.Level;
for I := 0 to Level - 1 do
Result := Result + TabChar;
Result := Result + Node.Text;
end;
function TTreeStrings.GetBufStart(Buffer: PChar; var Level: Integer): PChar;
begin
Level := 0;
while True do
begin
case Buffer^ of
#32: Inc(Buffer);
#9:
begin
Inc(Buffer);
Inc(Level);
end;
else
Break;
end;
end;
Result := Buffer;
end;
function TTreeStrings.GetObject(Index: Integer): TObject;
begin
Result := Owner.Item[Index];
if Assigned(Result) then
Result := TTreeNode(Result).Data;
end;
procedure TTreeStrings.PutObject(Index: Integer; AObject: TObject);
var
Node: TTreeNode;
begin
Node := Owner.Item[Index];
if Assigned(Node) then
Node.Data := AObject;
end;
function TTreeStrings.GetCount: Integer;
begin
Result := Owner.Count;
end;
procedure TTreeStrings.Clear;
begin
Owner.Clear;
end;
procedure TTreeStrings.Delete(Index: Integer);
begin
Owner.Item[Index].Delete;
end;
function TTreeStrings.Add(const S: string): Integer;
var
Level, OldLevel, I: Integer;
NewStr: string;
Node: TTreeNode;
begin
Result := GetCount;
if (Length(S) = 1) and (S[1] = Chr($1A)) then
Exit;
Node := nil;
OldLevel := 0;
NewStr := GetBufStart(PChar(S), Level);
if Result > 0 then
begin
Node := Owner.Item[Result-1];
OldLevel := Node.Level;
end;
if (Level > OldLevel) or not Assigned(Node) then
begin
if Level - OldLevel > 1 then
TreeViewError(sInvalidLevel);
end
else begin
for I := OldLevel downto Level do
begin
Node := Node.Parent;
if not Assigned(Node) and (I - Level > 0) then
TreeViewError(sInvalidLevel);
end;
end;
Owner.AddChild(Node, NewStr);
end;
procedure TTreeStrings.Insert(Index: Integer; const S: string);
begin
Owner.Insert(Owner.Item[Index], S);
end;
procedure TTreeStrings.LoadTreeFromStream(Stream: TStream);
var
List: TStringList;
ANode, NextNode: TTreeNode;
ALevel, I: Integer;
CurrStr: string;
StartSub, EndSub: PChar;
SubItemStart: Integer;
begin
try
List := nil;
Owner.BeginUpdate;
try
List := TStringList.Create;
Clear;
List.LoadFromStream(Stream);
ANode := nil;
for I := 0 to List.Count - 1 do
begin
CurrStr := GetBufStart(PChar(List[I]), ALevel);
SubItemStart := Pos(#9, CurrStr);
if SubItemStart <> 0 then
SetLength(CurrStr, SubItemStart-1);
if ANode = nil then
ANode := Owner.AddChild(nil, CurrStr)
else if ANode.Level = ALevel then
ANode := Owner.AddChild(ANode.Parent, CurrStr)
else if ANode.Level = (ALevel - 1) then
ANode := Owner.AddChild(ANode, CurrStr)
else if ANode.Level > ALevel then
begin
NextNode := ANode.Parent;
while NextNode.Level > ALevel do
NextNode := NextNode.Parent;
ANode := Owner.AddChild(NextNode.Parent, CurrStr);
end
else
TreeViewErrorFmt(sInvalidLevelEx, [ALevel, CurrStr]);
if Assigned(ANode) and (SubItemStart <> 0) then
begin
StartSub := PChar(List[I]) + SubItemStart + ALevel;
while True do
case StartSub^ of
#9, #32: Inc(StartSub);
#10, #0: Break;
else
begin
EndSub := StartSub;
while True do
case EndSub^ of
#32, #10, #9, #0: Break;
else
Inc(EndSub);
end;
SetString(CurrStr, StartSub, EndSub-StartSub);
StartSub := EndSub;
ANode.SubItems.Add(CurrStr);
end;
end;
end;
end;
finally
List.Free;
Owner.EndUpdate;
end;
except
Owner.Owner.Invalidate; { force repaint on exception }
raise;
end;
end;
procedure TTreeStrings.SaveTreeToStream(Stream: TStream);
const
TabChar = #9;
var
I: Integer;
J: Integer;
ANode: TTreeNode;
NodeStr: string;
begin
if Count > 0 then
begin
ANode := Owner[0];
while Assigned(ANode) do
begin
NodeStr := ANode.Text;
for I := 0 to ANode.Level - 1 do
NodeStr := TabChar + NodeStr;
for J := 0 to ANode.SubItems.Count-1 do
NodeStr := NodeStr + TabChar + ANode.SubItems[J];
NodeStr := NodeStr + sLineBreak;
Stream.Write(PChar(NodeStr)^, Length(NodeStr));
ANode := ANode.GetNext;
end;
end;
end;
{ TCustomTreeView }
constructor TCustomTreeView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Init(TTreeNode);
end;
destructor TCustomTreeView.Destroy;
begin
if Assigned(FMemStream) then
FreeAndNil(FMemStream);
FTreeNodes.Free;
inherited Destroy;
end;
procedure TCustomTreeView.ItemChanging(item: QListViewItemH; _type: TItemChange;
var Allow: Boolean);
var
AItem: TTreeNode;
begin
if _type <> ctState then
Exit;
AItem := FTreeNodes.FindItem(item);
if not Assigned(AItem) or (Assigned(AItem) and AItem.FDestroying) then
Exit;
if Assigned(FOnChanging) then
FOnChanging(Self, AItem, Allow);
if AItem <> FSelectedNode then
StartEditTimer;
end;
procedure TCustomTreeView.ItemChecked(item: QListViewItemH; Checked: Boolean);
var
AItem: TTreeNode;
begin
AItem := FTreeNodes.FindItem(item);
if Assigned(AItem) then
AItem.FChecked := Checked;
StartEditTimer;
end;
procedure TCustomTreeView.ItemDestroyed(AItem: QListViewItemH);
var
ANode: TTreeNode;
begin
ANode := FTreeNodes.FindItem(AItem);
if Assigned(ANode) then
begin
QClxObjectMap_remove(ANode.FHandle);
ANode.FHandle := nil;
if not (csDestroying in ComponentState) and (FHeader is TListViewHeader) then
if (not TListViewHeader(FHeader).FHiddenChanging) and not ANode.FDestroying then
ANode.Free;
end;
end;
procedure TCustomTreeView.ItemExpanding(item: QListViewItemH; Expand: Boolean;
var Allow: Boolean);
var
Node: TTreeNode;
begin
Node := FTreeNodes.FindItem(item);
if Assigned(Node) and Node.Expanded <> Expand then
Allow := Node.DoCanExpand(Expand);
end;
procedure TCustomTreeView.ItemExpanded(item: QListViewItemH; Expand: Boolean);
var
Node: TTreeNode;
begin
Node := FTreeNodes.FindItem(item);
if not Assigned(Node) then
Exit;
if Expand then
begin
if AutoExpand and not FFullExpansion then
DoAutoExpand(Node);
if Assigned(FOnExpanded) then
FOnExpanded(Self, Node);
end
else
if Assigned(FOnCollapsed) then
FOnCollapsed(Self, Node);
end;
procedure TCustomTreeView.ItemSelected(item: QListViewItemH; wasSelected: Boolean);
const
cIncSelCount: array [Boolean] of Integer = (-1, 1);
var
AItem: TTreeNode;
begin
Inc(FSelCount, cIncSelCount[wasSelected]);
AItem := FTreeNodes.FindItem(item);
if wasSelected and Assigned(AItem) and not AItem.FDestroying then
FSelectedNode := AItem
else
FSelectedNode := nil;
if Assigned(FSelectedNode) then
Change(FSelectedNode);
end;
procedure TCustomTreeView.SetItems(const Value: TTreeNodes);
begin
FTreeNodes.Assign(Value);
end;
procedure TCustomTreeView.SetTopItem(const AItem: TTreeNode);
var
NewTopH: Integer;
begin
if Assigned(AItem) and HandleAllocated then
begin
NewTopH := QListView_itemPos(Handle, AItem.Handle);
QListView_setContentsPos(Handle, QScrollView_contentsX(Handle), NewTopH);
end;
end;
function TCustomTreeView.GetDropTarget: TTreeNode;
var
Temp: TCustomViewItem;
begin
Result := nil;
Temp := FindDropTarget;
if Temp is TTreeNode then
Result := TTreeNode(Temp);
end;
function TCustomTreeView.GetTopItem: TTreeNode;
var
Pt: TPoint;
AItem: QListViewItemH;
begin
Result := nil;
if HandleAllocated then
begin
Pt := Point(1, 1);
AItem := QListView_itemAt(Handle, @Pt);
if not Assigned(AItem) then
Exit;
Result := FTreeNodes.FindItem(AItem);
end;
end;
constructor TCustomTreeView.Create(AOwner: TComponent; ANodeClass: TTreeNodeClass);
begin
inherited Create(AOwner);
Init(ANodeClass);
end;
procedure TCustomTreeView.Init(ANodeClass: TTreeNodeClass);
begin
FTreeNodes := TTreeNodes.Create(Self);
FTreeNodes.SetNodeClass(ANodeClass);
FShowButtons := True;
FItemMargin := 1;
ColumnClick := True;
ColumnMove := True;
ColumnResize := True;
end;
function TCustomTreeView.IsCustomDrawn: Boolean;
begin
Result := Assigned(FOnCustomDrawItem) or Assigned(FOnCustomDrawSubItem) or
Assigned(FOnCustomDrawBranch);
end;
procedure TCustomTreeView.InitWidget;
begin
inherited InitWidget;
QListView_setRootIsDecorated(Handle, FShowButtons);
end;
procedure TCustomTreeView.DoGetImageIndex(item: TCustomViewItem);
var
Pixmap: QPixmapH;
begin
if item is TTreeNode then
begin
QWidget_setUpdatesEnabled(Handle, False);
try
if Assigned(FOnGetImageIndex) then
FOnGetImageIndex(Self, TTreeNode(item));
if Assigned(Images) then
begin
Pixmap := Images.GetPixmap(TTreeNode(item).ImageIndex);
if Assigned(Pixmap) then
QListViewItem_setPixmap(item.Handle, 0, Pixmap);
end;
if Item.Selected then
begin
if Assigned(FOnGetSelectedIndex) then
FOnGetSelectedIndex(Self, TTreeNode(item));
if Assigned(Images) then
begin
Pixmap := Images.GetPixmap(TTreeNode(item).SelectedIndex);
if Assigned(Pixmap) then
QListViewItem_setPixmap(item.Handle, 0, Pixmap);
end;
end;
finally
QWidget_setUpdatesEnabled(Handle, True);
end;
end;
end;
procedure TCustomTreeView.DoEditing(AItem: TCustomViewItem; var AllowEdit: Boolean);
begin
if Assigned(FOnEditing) and (AItem is TTreeNode) then
FOnEditing(Self, TTreeNode(AItem), AllowEdit);
end;
procedure TCustomTreeView.DoEdited(AItem: TCustomViewItem; var S: WideString);
begin
if Assigned(FOnEdited) and (AItem is TTreeNode) then
FOnEdited(Self, TTreeNode(AItem), S);
end;
procedure TCustomTreeView.FullCollapse;
var
Node: TTreeNode;
begin
Node := Items.GetFirstNode;
while Node <> nil do
begin
Node.Collapse(True);
Node := Node.GetNextSibling;
end;
end;
procedure TCustomTreeView.FullExpand;
var
Node: TTreeNode;
begin
Node := Items.GetFirstNode;
Items.BeginUpdate;
FFullExpansion := True;
try
while Node <> nil do
begin
Node.Expand(True);
Node := Node.GetNextSibling;
end;
finally
FFullExpansion := False;
Items.EndUpdate;
end;
end;
function TCustomTreeView.GetNodeAt(X, Y: Integer): TTreeNode;
var
Temp: QListViewItemH;
Pt: Types.TPoint;
begin
Result := nil;
if HandleAllocated then
begin
Pt := Types.Point(X, Y);
Temp := QListView_itemAt(Handle, @Pt);
Result := FTreeNodes.FindItem(Temp);
end;
end;
procedure TCustomTreeView.LoadFromFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TCustomTreeView.LoadFromStream(Stream: TStream);
begin
with TTreeStrings.Create(Items) do
try
LoadTreeFromStream(Stream);
finally
Free;
end;
end;
procedure TCustomTreeView.SaveToFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
procedure TCustomTreeView.SaveToStream(Stream: TStream);
begin
with TTreeStrings.Create(Items) do
try
SaveTreeToStream(Stream);
finally
Free;
end;
end;
function TCustomTreeView.AlphaSort: Boolean;
var
Node: TTreeNode;
begin
Result := True;
if HandleAllocated then
begin
SortColumn := 0;
Sorted := True;
Node := FTreeNodes.GetFirstNode;
while Node <> nil do
begin
if Node.HasChildren then
Node.AlphaSort(SortDirection = sdAscending);
Node := Node.GetNext;
end;
end
else
Result := False;
end;
function TCustomTreeView.CanCollapse(Node: TTreeNode): Boolean;
begin
Result := True;
if Assigned(FOnCollapsing) then
FOnCollapsing(Self, Node, Result);
end;
function TCustomTreeView.CanExpand(Node: TTreeNode): Boolean;
begin
Result := True;
if Assigned(FOnExpanding) then
FOnExpanding(Self, Node, Result);
end;
procedure TCustomTreeView.Change(Node: TTreeNode);
begin
if Assigned(FOnChange) then
FOnChange(Self, Node);
end;
procedure TCustomTreeView.Collapse(Node: TTreeNode);
begin
if Assigned(Node) then
Node.Expanded := False;
end;
procedure TCustomTreeView.Delete(Node: TTreeNode);
begin
if Assigned(Node) then
Node.Delete;
end;
function TCustomTreeView.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
if QEvent_type(Event) = QEventType_FocusIn then
if (Items.Count > 0) and not Assigned(Selected) then
QListView_setSelected(Handle, QListView_firstChild(Handle), True);
Result := inherited EventFilter(Sender, Event);
end;
procedure TCustomTreeView.Expand(Node: TTreeNode);
begin
if Assigned(Node) then
Node.Expanded := True;
end;
procedure TCustomTreeView.Loaded;
begin
inherited Loaded;
if csDesigning in ComponentState then
FullExpand;
end;
procedure TCustomTreeView.SetSortType(const Value: TSortType);
begin
if SortType <> Value then
begin
FSortType := Value;
if (SortType in [stText]) then
AlphaSort;
end;
end;
procedure TCustomTreeView.SetAutoExpand(const Value: Boolean);
begin
if FAutoExpand <> Value then
FAutoExpand := Value;
end;
function TCustomTreeView.GetSelected: TTreeNode;
begin
Result := FSelectedNode;
end;
procedure TCustomTreeView.SetSelected(const Value: TTreeNode);
begin
if not (csDestroying in ComponentState) then
begin
if Assigned(FSelectedNode) then
FSelectedNode.Selected := False;
if Assigned(Value) then
Value.Selected := True;
end;
end;
procedure TCustomTreeView.SetItemMargin(const Value: Integer);
begin
if ItemMargin <> Value then
begin
FItemMargin := Value;
if HandleAllocated then
QListView_setItemMargin(Handle, FItemMargin);
end;
end;
procedure TCustomTreeView.SelectAll(Select: Boolean);
begin
MultiSelect := True;
if HandleAllocated then
QListView_selectAll(Handle, Select);
end;
procedure TCustomTreeView.SetOnItemDoubleClick(const Value: TTVItemDoubleClickEvent);
var
Method: TMethod;
begin
FOnItemDoubleClick := Value;
if Assigned(FOnItemDoubleClick) then
QListView_doubleClicked_Event(Method) := DoItemDoubleClick
else
Method := NullHook;
QListView_hook_hook_doubleClicked(QListView_hookH(Hooks), Method);
end;
procedure TCustomTreeView.SetOnItemEnter(const Value: TTVItemEnterEvent);
var
Method: TMethod;
begin
FOnItemEnter := Value;
if Assigned(FOnItemEnter) then
QListView_onItem_Event(Method) := DoOnItemEnter
else
Method := NullHook;
QListView_hook_hook_onItem(QListView_hookH(Hooks), Method);
end;
procedure TCustomTreeView.SetOnItemExitViewportEnter(const Value: TTVItemExitViewportEnterEvent);
var
Method: TMethod;
begin
FOnItemExitViewportEnter := Value;
if Assigned(FOnItemExitViewportEnter) then
QListView_onViewport_Event(Method) := DoOnItemExitViewportEnter
else
Method := NullHook;
QListView_hook_hook_onViewport(QListView_hookH(Hooks), Method);
end;
procedure TCustomTreeView.SetOnMouseDown(const Value: TTVButtonDownEvent);
begin
FOnMouseDown := Value;
HookMouseDowns;
end;
procedure TCustomTreeView.SetOnViewportButtonDown(const Value: TTVViewportButtonDownEvent);
begin
FOnViewportMouseDown := Value;
HookMouseDowns;
end;
procedure TCustomTreeView.DoItemClick(p1: Integer; p2: QListViewItemH; p3: PPoint;
p4: Integer);
var
AItem: TTreeNode;
SelNode: TTreeNode;
begin
try
AItem := FTreeNodes.FindItem(p2);
if AutoExpand and Assigned(AItem) then
begin
SelNode := Selected;
try
DoAutoExpand(AItem);
finally
Selected := SelNode;
end;
end;
if Assigned(AItem) then
begin
if Assigned(FOnItemClick) then
FOnItemClick(Self, ButtonToMouseButton(p1), AItem, p3^);
if (p4 = 0) and FAllowEdit then
EditItem;
end;
except
Application.HandleException(Self);
end;
end;
procedure TCustomTreeView.DoItemDoubleClick(p1: QListViewItemH);
var
SelectedItem: TTreeNode;
begin
if Assigned(FOnItemDoubleClick) then
try
SelectedItem := FTreeNodes.FindItem(p1);
FOnItemDoubleClick(Self, SelectedItem);
except
Application.HandleException(Self);
end;
end;
procedure TCustomTreeView.DoOnItemEnter(item: QListViewItemH);
var
SelectedItem: TTreeNode;
begin
if Assigned(FOnItemEnter) then
try
SelectedItem := FTreeNodes.FindItem(item);
FOnItemEnter(Self, SelectedItem);
except
Application.HandleException(Self);
end;
end;
procedure TCustomTreeView.DoOnItemExitViewportEnter;
begin
if Assigned(FOnItemExitViewportEnter) then
try
FOnItemExitViewportEnter(Self);
except
Application.HandleException(Self);
end;
end;
procedure TCustomTreeView.DoOnMouseDown(p1: Integer; p2: QListViewItemH;
p3: PPoint; p4: Integer);
var
AItem: TTreeNode;
begin
try
AItem := FTreeNodes.FindItem(p2);
if Assigned(FOnMouseDown) and (p2 <> nil) then
FOnMouseDown(Self, ButtonToMouseButton(p1), AItem, p3^)
else if Assigned(FOnViewportMouseDown) and (AItem = nil) then
FOnViewportMouseDown(Self, ButtonToMouseButton(p1), p3^);
except
Application.HandleException(Self);
end;
end;
procedure TCustomTreeView.HookMouseDowns;
var
Method: TMethod;
begin
if Assigned(FOnMouseDown) or Assigned(FOnViewportMouseDown) then
QListView_mouseButtonPressed_Event(Method) := DoOnMouseDown
else
Method := NullHook;
QListView_hook_hook_mouseButtonPressed(QListView_hookH(Hooks), Method);
end;
procedure TCustomTreeView.DoAutoExpand(ExpandedNode: TTreeNode);
var
Node: TTreeNode;
ParentNode: TTreeNode;
begin
if ExpandedNode = nil then
Exit;
Items.BeginUpdate;
try
ParentNode := ExpandedNode;
if Assigned(ParentNode) then
while ParentNode.GetParent <> nil do
ParentNode := ParentNode.GetParent;
Node := Items.GetFirstNode;
if Assigned(Node) then
begin
while True do
begin
if Node = nil then
Exit;
if Node = ParentNode then
begin
Node := Node.getNextSibling;
Continue;
end;
Node.Collapse(False);
Node := Node.getNextSibling;
end;
end;
finally
if not ExpandedNode.Expanded then
ExpandedNode.Expand(False);
Items.EndUpdate;
end;
end;
procedure TCustomTreeView.SetShowButtons(const Value: Boolean);
begin
if FShowButtons <> Value then
begin
FShowButtons := Value;
if HandleAllocated then
QListView_setRootIsDecorated(Handle, FShowButtons);
end;
end;
procedure TCustomTreeView.RepopulateItems;
var
I: Integer;
begin
if HandleAllocated then
begin
if (QListView_childCount(Handle) = 0) and (QListView_columns(Handle) > 0) then
begin
Items.BeginUpdate;
try
for I := 0 to Items.Count-1 do
Items[I].ReCreateItem;
finally
Items.EndUpdate;
end;
end
else
begin
Items.BeginUpdate;
try
for I := 0 to Items.Count-1 do
Items[I].ResetFields;
finally
Items.EndUpdate;
end;
end;
end;
end;
procedure TCustomTreeView.RestoreWidgetState;
begin
inherited RestoreWidgetState;
if Assigned(FMemStream) then
begin
FMemStream.Position := 0;
FTreeNodes.ReadData(FMemStream);
FreeAndNil(FMemStream);
end;
end;
procedure TCustomTreeView.SaveWidgetState;
begin
inherited SaveWidgetState;
FMemStream := TMemoryStream.Create;
FTreeNodes.WriteData(FMemStream);
FTreeNodes.Clear;
end;
procedure TCustomTreeView.HookEvents;
var
Method: TMethod;
begin
inherited HookEvents;
QListView_mouseButtonClicked_Event(Method) := DoItemClick;
QListView_hook_hook_mouseButtonClicked(QListView_hookH(Hooks), Method);
end;
procedure TCustomTreeView.ImageListChanged;
var
I: Integer;
begin
for I := 0 to FTreeNodes.Count-1 do
FTreeNodes[i].UpdateImages;
end;
{ TTreeView }
{$IF not (defined(LINUX) and defined(VER140))}
function TTreeView.GetSelCount: Integer;
begin
Result := FSelCount;
end;
{$IFEND}
{ TViewItemsList }
function TViewItemsList.GetItem(Index: Integer): TCustomViewItem;
begin
Result := TCustomViewItem(inherited GetItem(Index));
end;
procedure TViewItemsList.SetItem(Index: Integer; AObject: TCustomViewItem);
begin
inherited SetItem(Index, AObject);
end;
{ TCustomHeaderControl }
constructor TCustomHeaderControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
FImageChanges := TChangeLink.Create;
FImageChanges.OnChange := OnImageChanges;
FOrientation := hoHorizontal;
FTracking := True;
FDragReorder := False;
Height := 19;
Align := alTop;
end;
destructor TCustomHeaderControl.Destroy;
begin
if Assigned(FMemStream) then
FreeAndNil(FMemStream);
FImageChanges.Free;
FCanvas.Free;
inherited Destroy;
end;
procedure TCustomHeaderControl.AssignTo(Dest: TPersistent);
var
I: Integer;
begin
if Dest is TCustomHeaderControl then
begin
TCustomHeaderControl(Dest).Sections.Clear;
for I := 0 to Sections.Count - 1 do
TCustomHeaderControl(Dest).Sections.Add.Assign(Sections[I]);
end
else
inherited Assign(Dest);
end;
procedure TCustomHeaderControl.ChangeBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited ChangeBounds(ALeft, ATop, AWidth, AHeight);
Invalidate;
end;
procedure TCustomHeaderControl.ColumnClicked(Section: TCustomHeaderSection);
begin
if Assigned(FOnSectionClick) then
FOnSectionClick(Self, Section);
end;
procedure TCustomHeaderControl.ColumnMoved(Section: TCustomHeaderSection);
begin
if Assigned(FOnSectionMoved) then
FOnSectionMoved(Self, Section);
end;
procedure TCustomHeaderControl.ColumnResized(Section: TCustomHeaderSection);
begin
if Assigned(FOnSectionResize) then
FOnSectionResize(Self, Section);
end;
procedure TCustomHeaderControl.CreateWidget;
begin
FHandle := QHeader_create(ParentWidget, nil);
Hooks := QHeader_hook_create(FHandle);
end;
function TCustomHeaderControl.GetHandle: QHeaderH;
begin
HandleNeeded;
Result := QHeaderH(FHandle);
end;
function TCustomHeaderControl.GetSections: TCustomHeaderSections;
begin
Result := FSections;
end;
procedure TCustomHeaderControl.HookEvents;
var
Method: TMethod;
begin
inherited HookEvents;
QHeader_sectionClicked_Event(Method) := SectionClicked;
QHeader_hook_hook_sectionClicked(QHeader_hookH(Hooks), Method);
QHeader_sizeChange_Event(Method) := SectionSizeChanged;
QHeader_hook_hook_sizeChange(QHeader_hookH(Hooks), Method);
QHeader_moved_Event(Method) := SectionMoved;
QHeader_hook_hook_moved(QHeader_hookH(Hooks), Method);
end;
procedure TCustomHeaderControl.ImageListChanged;
begin
FSections.UpdateImages;
end;
procedure TCustomHeaderControl.InitWidget;
begin
inherited InitWidget;
if FDragReorder then
FClickable := True;
QHeader_setClickEnabled(Handle, FClickable, -1);
QHeader_setResizeEnabled(Handle, FResizable, -1);
QHeader_setTracking(Handle, FTracking);
QHeader_setMovingEnabled(Handle, FDragReorder);
end;
procedure TCustomHeaderControl.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = FImages) then
begin
if (Operation = opRemove) then
FImages := nil;
ImageListChanged;
end;
end;
procedure TCustomHeaderControl.OnImageChanges(Sender: TObject);
begin
ImageListChanged;
end;
procedure TCustomHeaderControl.RestoreWidgetState;
begin
inherited RestoreWidgetState;
if Assigned(FMemStream) then
begin
FMemStream.Position := 0;
FSections.Clear;
FMemStream.ReadComponent(Self);
FreeAndNil(FMemStream);
end;
end;
procedure TCustomHeaderControl.SaveWidgetState;
begin
inherited SaveWidgetState;
if not Assigned(FMemStream) then
FMemStream := TMemoryStream.Create
else
FMemStream.Clear;
FMemStream.WriteComponent(Self);
end;
procedure TCustomHeaderControl.SectionClicked(SectionIndex: Integer);
begin
try
if (SectionIndex >= 0) and (SectionIndex < FSections.Count) then
ColumnClicked(Sections[SectionIndex]);
except
Application.HandleException(Self);
end;
end;
procedure TCustomHeaderControl.SectionMoved(FromIndex, ToIndex: Integer);
var
FromSection: TCustomHeaderSection;
begin
if (FromIndex <> ToIndex) and (FromIndex <> ToIndex-1) then
begin
try
FDontResubmit := True;
try
if ToIndex > FromIndex then
Dec(ToIndex);
FromSection := Sections[FromIndex];
FromSection.SetIndex(ToIndex);
ColumnMoved(FromSection);
except
Application.HandleException(Self);
end;
finally
FDontResubmit := False;
end;
end;
end;
procedure TCustomHeaderControl.SectionSizeChanged(SectionIndex, OldSize,
NewSize: Integer);
begin
if OldSize <> NewSize then
begin
try
{ This by-passes the MaxWidth and MinWidth. Is there a way to make Qt
happy with min/max widths on sections? }
if (SectionIndex >= 0) and (SectionIndex < FSections.Count) then
begin
FSections[SectionIndex].FWidth := NewSize;
ColumnResized(FSections[SectionIndex]);
end;
except
Application.HandleException(Self);
end;
end;
end;
procedure TCustomHeaderControl.SetClickable(const Value: Boolean);
var
I: Integer;
begin
if Clickable <> Value then
begin
FClickable := Value;
for I := 0 to Sections.Count-1 do
Sections[I].AllowClick := FClickable;
if not FClickable then
DragReorder := False;
if HandleAllocated then
QWidget_update(Handle);
end;
end;
procedure TCustomHeaderControl.SetDragReorder(const Value: Boolean);
begin
if DragReorder <> Value then
begin
FDragReorder := Value;
if HandleAllocated then
QHeader_setMovingEnabled(Handle, FDragReorder);
if FDragReorder then
Clickable := True;
end;
end;
procedure TCustomHeaderControl.SetImages(const Value: TCustomImageList);
begin
if FImages <> Value then
begin
if Assigned(FImages) then
FImages.UnRegisterChanges(FImageChanges);
FImages := Value;
if Assigned(FImages) then
FImages.RegisterChanges(FImageChanges);
ImageListChanged;
end;
end;
procedure TCustomHeaderControl.SetOrientation(const Value: THeaderOrientation);
const
cOrientation: array [THeaderOrientation] of Qt.Orientation =
(Orientation_Horizontal, Orientation_Vertical);
begin
if FOrientation <> Value then
begin
FOrientation := Value;
if Align <> alNone then
if FOrientation = hoHorizontal then
Align := alTop
else
Align := alLeft;
if HandleAllocated then
QHeader_setOrientation(Handle, cOrientation[FOrientation]);
end;
end;
procedure TCustomHeaderControl.SetResizable(const Value: Boolean);
var
I: Integer;
begin
if Resizable <> Value then
begin
FResizable := Value;
for I := 0 to Sections.Count-1 do
Sections[I].AllowResize := FResizable;
end;
end;
procedure TCustomHeaderControl.SetSections(const Value: TCustomHeaderSections);
begin
FSections.Assign(Value);
end;
procedure TCustomHeaderControl.SetTracking(const Value: Boolean);
begin
if Tracking <> Value then
begin
FTracking := Value;
if HandleAllocated then
QHeader_setTracking(Handle, FTracking);
end;
end;
{ THeaderSections }
function THeaderSections.Add: THeaderSection;
begin
Result := THeaderSection(inherited Add);
end;
function THeaderSections.GetItem(Index: Integer): THeaderSection;
begin
Result := THeaderSection(inherited GetItem(Index));
end;
procedure THeaderSections.SetItem(Index: Integer; Value: THeaderSection);
begin
inherited SetItem(Index, Value);
end;
{ TCustomHeaderSection }
procedure TCustomHeaderSection.AddSection;
begin
QHeader_addLabel(Header.Handle, nil, FWidth);
QHeader_setClickEnabled(Header.Handle, FAllowClick,
QHeader_mapToIndex(Header.Handle, Index));
QHeader_setResizeEnabled(Header.Handle, FAllowResize,
QHeader_mapToIndex(Header.Handle, Index));
end;
procedure TCustomHeaderSection.AssignTo(Dest: TPersistent);
begin
if Dest is TCustomHeaderSection then
begin
TCustomHeaderSection(Dest).AllowResize := FAllowResize;
TCustomHeaderSection(Dest).AllowClick := FAllowClick;
TCustomHeaderSection(Dest).MaxWidth := FMaxWidth;
TCustomHeaderSection(Dest).Width := FWidth;
TCustomHeaderSection(Dest).MinWidth := FMinWidth;
end
else
inherited AssignTo(Dest);
end;
constructor TCustomHeaderSection.Create(Collection: TCollection);
begin
inherited Create(Collection);
if (Collection is TCustomHeaderSections) and
(TCustomHeaderSections(Collection).GetOwner is TCustomHeaderControl) then
FHeader := TCustomHeaderControl(TCustomHeaderSections(Collection).GetOwner)
else
raise EHeaderException.CreateRes(@sOwnerNotCustomHeaderSections);
FAllowClick := True;
FAllowResize := True;
FWidth := 50;
FImageIndex := -1;
MaxWidth := 1000;
MinWidth := 0;
AddSection;
end;
function TCustomHeaderSection.CalcSize: Integer;
const
cMargin = 4 shl 1;
var
fm: QFontMetricsH;
Pixmap: QPixmapH;
ISet: QIconSetH;
begin
if not AutoSize then
begin
Result := FWidth;
Exit;
end
else
Result := 0;
if FText <> '' then
begin
fm := QFontMetrics_create(Header.Font.Handle);
try
Result := QFontMetrics_width(fm, PWideString(@FText),
Length(FText)) + cMargin;
finally
QFontMetrics_destroy(fm);
end;
end;
ISet := QHeader_iconSet(Header.Handle, QHeader_mapToIndex(Header.Handle, Index));
if Assigned(ISet) then
begin
Pixmap := QPixmap_create;
try
QIconSet_pixmap(ISet, Pixmap, QIconSetSize_Small, QIconSetMode_Normal);
Inc(Result, QPixmap_width(Pixmap) + 2 + cMargin);
finally
QPixmap_destroy(Pixmap);
end;
end;
end;
function TCustomHeaderSection.Header: TCustomHeaderControl;
begin
Result := FHeader;
end;
function TCustomHeaderSection.GetDisplayName: string;
begin
Result := FText;
if Result = '' then
Result := inherited GetDisplayName;
end;
function TCustomHeaderSection.GetLeft: Integer;
begin
if Header.HandleAllocated then
Result := QHeader_sectionPos(Header.Handle,
QHeader_mapToIndex(Header.Handle, Index))
else
Result := -1;
end;
procedure TCustomHeaderSection.Resubmit;
var
AHandle: QHeaderH;
begin
if Header = nil then
Exit;
if Header.HandleAllocated then
begin
AHandle := Header.Handle;
QWidget_setUpdatesEnabled(AHandle, False);
try
QHeader_setLabel(AHandle, QHeader_mapToIndex(Header.Handle, Index),
@FText, CalcSize);
UpdateImage;
QHeader_setClickEnabled(AHandle, FAllowClick,
QHeader_mapToIndex(Header.Handle, Index));
QHeader_setResizeEnabled(AHandle, FAllowResize,
QHeader_mapToIndex(Header.Handle, Index));
finally
QWidget_setUpdatesEnabled(AHandle, True);
end;
end;
end;
procedure TCustomHeaderSection.SetAutoSize(const Value: Boolean);
begin
if FAutoSize <> Value then
begin
FAutoSize := Value;
if Header.HandleAllocated then
QHeader_setLabel(Header.Handle, QHeader_mapToIndex(Header.Handle, Index),
PWideString(@FText), CalcSize);
end;
end;
function TCustomHeaderSection.GetRight: Integer;
begin
Result := Left + Width;
end;
function TCustomHeaderSection.GetWidth: Integer;
begin
if Header.HandleAllocated and not (csRecreating in Header.ControlState) then
FWidth := QHeader_sectionSize(Header.Handle,
QHeader_mapToIndex(Header.Handle, Index));
Result := FWidth;
end;
procedure TCustomHeaderSection.SetAllowClick(const Value: Boolean);
begin
if FAllowClick <> Value then
begin
FAllowClick := Value;
if Header.HandleAllocated then
begin
QHeader_setClickEnabled(Header.Handle, FAllowClick,
QHeader_mapToIndex(Header.Handle, Index));
QWidget_update(Header.Handle);
end;
end;
end;
procedure TCustomHeaderSection.SetAllowResize(const Value: Boolean);
begin
if FAllowResize <> Value then
begin
FAllowResize := Value;
if Header.HandleAllocated then
begin
QHeader_setResizeEnabled(Header.Handle, FAllowResize,
QHeader_mapToIndex(Header.Handle, Index));
QWidget_update(Header.Handle);
end;
end;
end;
procedure TCustomHeaderSection.SetImageIndex(const Value: TImageIndex);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
UpdateImage;
end;
end;
procedure TCustomHeaderSection.SetMaxWidth(const Value: Integer);
begin
if FMaxWidth <> Value then
begin
FMaxWidth := Value;
if FMaxWidth < FMinWidth then
FMaxWidth := FMinWidth + 1;
UpdateWidth;
end;
end;
procedure TCustomHeaderSection.SetMinWidth(const Value: Integer);
begin
if FMinWidth <> Value then
begin
FMinWidth := Value;
if FMinWidth > FMaxWidth then
FMinWidth := FMaxWidth - 1;
UpdateWidth;
end;
end;
procedure TCustomHeaderSection.SetWidth(Value: Integer);
begin
if FWidth <> Value then
begin
if ((Value < MinWidth) and (Value >= 0)) then
Value := MinWidth
else if ((MaxWidth > 0) and (Value > MaxWidth)) then
Value := MaxWidth;
SetWidthVal(Value);
end;
end;
procedure TCustomHeaderSection.SetWidthVal(const Value: Integer);
begin
FWidth := Value;
end;
procedure TCustomHeaderSection.UpdateImage;
var
Pixmap: QPixmapH;
IconSet: QIconSetH;
begin
if Header.HandleAllocated then
begin
if Assigned(Header.FImages) then
Pixmap := Header.FImages.GetPixmap(FImageIndex)
else
Pixmap := nil;
IconSet := QHeader_iconSet(Header.Handle,
QHeader_mapToIndex(Header.Handle, Index));
if not Assigned(IconSet) then
begin
IconSet := QIconset_create;
try
QHeader_setLabel(Header.Handle, QHeader_mapToIndex(Header.Handle, Index),
IconSet, PWideString(@FText), CalcSize);
finally
QIconSet_destroy(IconSet);
end;
end;
IconSet := QHeader_iconSet(Header.Handle,
QHeader_mapToIndex(Header.Handle, Index));
if not Assigned(Pixmap) then
QIconSet_reset(IconSet, QPixmap_create, QIconSetSize_Small)
else
QIconSet_setPixmap(IconSet, Pixmap, QIconSetSize_Small, QIconSetMode_Normal);
QWidget_update(Header.Handle);
end;
end;
procedure TCustomHeaderSection.UpdateWidth;
begin
if FWidth > FMaxWidth then
Width := FMaxWidth
else if FWidth < FMinWidth then
Width := FMinWidth;
end;
{ TListColumn }
procedure TListColumn.AddSection;
begin
if HeaderIsListHeader and not TListViewHeader(Header).Hidden then
begin
if Collection.Count <> QListView_columns(ViewControl.Handle) then
QListView_addColumn(ViewControl.Handle, nil, FWidth);
QHeader_setClickEnabled(Header.Handle, FAllowClick,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index));
QHeader_setResizeEnabled(Header.Handle, FAllowResize,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index));
if QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index) = 0 then { repopulate dormant items }
ViewControl.RepopulateItems;
end;
Alignment := taLeftJustify;
end;
function TListColumn.HeaderIsListHeader: Boolean;
begin
Result := Assigned(FHeader) and (Header is TListViewHeader);
end;
{$IF not (defined(LINUX) and defined(VER140))}
function TListColumn.GetCaption: WideString;
begin
Result := FText;
end;
{$IFEND}
procedure TListColumn.AssignTo(Dest: TPersistent);
begin
inherited AssignTo(Dest);
if Dest is TListColumn then
begin
TListColumn(Dest).Caption := Caption;
TListColumn(Dest).Alignment := Alignment;
TListColumn(Dest).AutoSize := AutoSize;
end;
end;
destructor TListColumn.Destroy;
var
Empty: WideString;
begin
if not (csDestroying in ViewControl.ComponentState) and HeaderIsListHeader then
if not TListViewHeader(Header).Hidden then
begin
if QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index) = 0 then
begin
if QListView_columns(ViewControl.Handle) > 1 then
begin
QListView_removeColumn(ViewControl.Handle,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index));
ViewControl.RepopulateItems;
end
else
begin
Empty := '';
QListView_setColumnText(ViewControl.Handle, 0, @Empty);
QListView_setColumnWidthMode(ViewControl.Handle, 0,
QListViewWidthMode_Maximum);
end;
end
else if QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index) <> 0 then
QListView_removeColumn(ViewControl.Handle,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index));
end;
inherited Destroy;
end;
function TListColumn.GetWidth: Integer;
begin
if Header.HandleAllocated and not (csRecreating in Header.ControlState) and
HeaderIsListHeader and (not TListViewHeader(Header).Hidden) then
FWidth := QListView_columnWidth(ViewControl.Handle,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index));
Result := FWidth;
end;
const
ColAlignmentFlags: array [TAlignment] of Integer =
(Integer(AlignmentFlags_AlignLeft), Integer(AlignmentFlags_AlignRight),
Integer(AlignmentFlags_AlignCenter));
ColAutoSize: array [Boolean] of QListViewWidthMode = (QListViewWidthMode_Manual,
QListViewWidthMode_Maximum);
procedure TListColumn.Resubmit;
var
AHandle: QHeaderH;
begin
if (Header <> nil) and Header.HandleAllocated then
begin
AHandle := Header.Handle;
if not TListViewHeader(Header).Hidden then
QWidget_setUpdatesEnabled(AHandle, False);
try
QListView_setColumnText(ViewControl.Handle,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index), PWideString(@FText));
QListView_setColumnAlignment(ViewControl.Handle,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index), ColAlignmentFlags[FAlignment]);
QListView_setColumnWidth(ViewControl.Handle,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index), Width);
QHeader_setClickEnabled(AHandle, FAllowClick,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index));
QHeader_setResizeEnabled(AHandle, FAllowResize,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index));
finally
if not TListViewHeader(Header).Hidden then
QWidget_setUpdatesEnabled(AHandle, True);
end;
end;
end;
procedure TListColumn.SetAlignment(const Value: TAlignment);
begin
if (Value <> Alignment) and
(QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index) <> 0) then
begin
FAlignment := Value;
if not TListViewHeader(Header).Hidden and ViewControl.HandleAllocated then
QListView_setColumnAlignment(ViewControl.Handle,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index),
ColAlignmentFlags[Value]);
end;
end;
procedure TListColumn.SetAutoSize(const Value: Boolean);
begin
if AutoSize <> Value then
begin
FAutoSize := Value;
if not TListViewHeader(Header).Hidden and ViewControl.HandleAllocated then
QListView_setColumnWidthMode(ViewControl.Handle,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index),
ColAutoSize[Value]);
end;
end;
procedure TListColumn.SetCaption(const Value: WideString);
begin
if FText <> Value then
begin
FText := Value;
if ViewControl.HandleAllocated and not TListViewHeader(Header).Hidden then
QListView_setColumnText(ViewControl.Handle,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index),
PWideString(@FText));
end;
end;
procedure TListColumn.SetWidthVal(const Value: Integer);
begin
FWidth := Value;
if ViewControl.HandleAllocated and not TListViewHeader(Header).Hidden then
QListView_setColumnWidth(ViewControl.Handle,
QHeader_mapToIndex(QListView_header(ViewControl.Handle), Index), FWidth);
ViewControl.UpdateControl;
end;
function TListColumn.ViewControl: TCustomViewControl;
begin
Result := TCustomViewControl(Header.Owner);
end;
{ TListViewHeader }
constructor TListViewHeader.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSections := TListColumns.Create(Self, TListColumn);
end;
destructor TListViewHeader.Destroy;
begin
FSections.Free;
inherited Destroy;
end;
procedure TListViewHeader.ColumnClicked(Section: TCustomHeaderSection);
begin
if Assigned(ViewControl.FOnColumnClick) then
ViewControl.FOnColumnClick(Owner, Section as TListColumn);
end;
procedure TListViewHeader.ColumnMoved(Section: TCustomHeaderSection);
begin
if Assigned(ViewControl.FColumnDragged) then
ViewControl.FColumnDragged(Owner, Section as TListColumn);
end;
procedure TListViewHeader.ColumnResized(Section: TCustomHeaderSection);
begin
if Assigned(ViewControl.FColumnResize) then
ViewControl.FColumnResize(Owner, Section as TListColumn);
end;
procedure TListViewHeader.CreateWidget;
begin
if Hidden then
FHandle := QHeader_create(ParentWidget, nil)
else
FHandle := QListView_header(ListViewHandle);
Hooks := QHeader_hook_create(FHandle);
end;
procedure TListViewHeader.DestroyWidget;
begin
if not (csRecreating in ControlState) then
FSections.Clear;
if Hidden and not FHiddenChanging then
inherited DestroyWidget
else
begin
if Assigned(Hooks) then
begin
QHeader_hook_destroy(QHeader_hookH(Hooks));
Hooks := nil;
end;
QClxObjectMap_remove(FHandle);
FHandle := nil;
end;
end;
function TListViewHeader.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
if Hidden then
Result := inherited EventFilter(Sender, Event)
else
Result := False;
end;
function TListViewHeader.GetHandle: QHeaderH;
begin
HandleNeeded;
if not Hidden and (FHandle <> QListView_header(ListViewHandle)) then
RecreateWidget;
Result := QHeaderH(FHandle);
end;
function TListViewHeader.GetSections: TListColumns;
begin
Result := TListColumns(inherited GetSections);
end;
procedure TListViewHeader.HookEvents;
var
Method: TMethod;
begin
inherited HookEvents;
if not Hidden then
begin
if QClxObjectMap_find(Handle) <> 0 then
QClxObjectMap_remove(Handle);
QClxObjectMap_add(Handle, Integer(Owner));
if csDesigning in ComponentState then
begin
TEventFilterMethod(Method) := ViewControl.MainEventFilter;
Qt_hook_hook_events(Hooks, Method);
end;
end;
end;
procedure TListViewHeader.InitWidget;
begin
inherited InitWidget;
Visible := not Hidden;
end;
function TListViewHeader.ListViewHandle: QListViewH;
begin
Result := TCustomViewControl(Owner).Handle;
end;
procedure TListViewHeader.SetHidden(const Value: Boolean);
begin
if FHidden <> Value then
begin
FHidden := Value;
FHiddenChanging := True;
try
while QListView_columns(ListViewHandle) > 1 do
QListView_removeColumn(ListViewHandle, 1);
RecreateWidget;
if Hidden then
begin
if QListView_columns(ListViewHandle) = 0 then
QListView_addColumn(ListViewHandle, nil, 50);
QListView_setColumnWidthMode(ListViewHandle, 0,
QListViewWidthMode_Maximum);
end
else
begin
QListView_setShowSortIndicator(ListViewHandle,
ViewControl.ShowColumnSortIndicators);
if ViewControl.Columns.Count > 0 then
QListView_setColumnWidthMode(ListViewHandle, 0,
ColAutoSize[ViewControl.Columns[0].AutoSize]);
end;
ViewControl.RepopulateItems;
finally
FHiddenChanging := False;
end;
end;
end;
procedure TListViewHeader.SetSections(const Value: TListColumns);
begin
inherited SetSections(Value);
end;
procedure TListViewHeader.Update;
begin
if (not Hidden) and not (csDestroying in ViewControl.ComponentState) and
HandleAllocated then
QWidget_update(Handle);
end;
procedure TListViewHeader.UpdateWidgetShowing;
begin
if HandleAllocated then
begin
if Hidden then
QWidget_hide(QListView_header(ListViewHandle))
else
QWidget_show(QListView_header(ListViewHandle));
QListView_triggerUpdate(ListViewHandle);
end;
end;
function TListViewHeader.ViewControl: TCustomViewControl;
begin
Result := TCustomViewControl(Owner);
end;
{ THeaderControl }
function THeaderControl.GetSections: THeaderSections;
begin
Result := THeaderSections(inherited GetSections);
end;
procedure THeaderControl.CreateWidget;
begin
FHandle := QHeader_create(ParentWidget, nil);
Hooks := QHeader_hook_create(Handle);
end;
procedure THeaderControl.SetSections(const Value: THeaderSections);
begin
inherited SetSections(Value);
end;
destructor THeaderControl.Destroy;
begin
FSections.Free;
inherited Destroy;
end;
procedure THeaderControl.InitWidget;
begin
inherited InitWidget;
QHeader_setTracking(Handle, FTracking);
end;
constructor THeaderControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Init(THeaderSection);
end;
constructor THeaderControl.Create(AOwner: TComponent; AHeaderSectionClass: THeaderSectionClass);
begin
inherited Create(AOwner);
Init(AHeaderSectionClass);
end;
procedure THeaderControl.Init(AHeaderSectionClass: THeaderSectionClass);
begin
FSections := THeaderSections.Create(Self, AHeaderSectionClass);
end;
{ TListColumns }
function TListColumns.Add: TListColumn;
begin
Result := TListColumn(inherited Add);
end;
procedure TListColumns.Added(var Item: TCollectionItem);
begin
if not (Item is TListColumn) then
Exit;
if Assigned(ViewControl) then
begin
BeginUpdate;
try
ViewControl.RepopulateItems;
finally
EndUpdate;
end;
end;
end;
function TListColumns.GetItem(Index: Integer): TListColumn;
begin
Result := TListColumn(inherited GetItem(Index));
end;
function TListColumns.GetViewControl: TCustomViewControl;
begin
if FHeaderControl is TListViewHeader then
Result := FHeaderControl.Owner as TCustomViewControl
else
Result := nil;
end;
procedure TListColumns.SetItem(Index: Integer; Value: TListColumn);
begin
inherited SetItem(Index, Value);
end;
procedure TListColumns.Update(Item: TCollectionItem);
var
I: Integer;
begin
if Assigned(ViewControl) then
if not ViewControl.FHeader.FDontResubmit then
begin
if not Assigned(Item) then
begin
for I := 0 to Count-1 do
Items[I].Resubmit;
end
else if Item is TListColumn then
TListColumn(Item).Resubmit;
if not Assigned(Item) and not (csDestroying in ViewControl.ComponentState) then
ViewControl.UpdateControl;
end;
end;
{ TCustomHeaderSections }
constructor TCustomHeaderSections.Create(HeaderControl: TCustomHeaderControl;
SectionClass: THeaderSectionClass);
begin
inherited Create(SectionClass);
FHeaderControl := HeaderControl;
end;
function TCustomHeaderSections.GetItem(Index: Integer): TCustomHeaderSection;
begin
Result := TCustomHeaderSection(inherited GetItem(Index));
end;
function TCustomHeaderSections.GetOwner: TPersistent;
begin
Result := FHeaderControl;
end;
procedure TCustomHeaderSections.SetItem(Index: Integer; Value: TCustomHeaderSection);
begin
inherited SetItem(Index, Value);
end;
procedure TCustomHeaderSections.Update(Item: TCollectionItem);
var
I: Integer;
begin
if Owner is TCustomHeaderControl then
if not TCustomHeaderControl(Owner).FDontResubmit then
begin
if not Assigned(Item) then
begin
for I := 0 to Count-1 do
Items[I].Resubmit;
end
else if Item is TCustomHeaderSection then
TCustomHeaderSection(Item).Resubmit;
if TCustomHeaderControl(Owner).HandleAllocated then
QWidget_repaint(TCustomHeaderControl(Owner).Handle);
end;
end;
procedure TCustomHeaderSections.UpdateImages;
var
I: Integer;
begin
for I := 0 to Count-1 do
Items[I].UpdateImage;
end;
{ TListItems }
function TListItems.Add: TListItem;
var
After: TListItem;
begin
if FItems.Count > 0 then
After := Item[FItems.Count-1]
else
After := nil;
Result := FListItemClass.Create(Self, nil, After);
FItems.Add(Result);
if Assigned(Owner) and Assigned(Owner.FOnInsert) then
Owner.FOnInsert(Owner, Result);
end;
function TListItems.AddItem(Item: TListItem; Index: Integer): TListItem;
begin
if Index < 0 then
Index := 0
else if Index >= Count then
Index := Count-1;
BeginUpdate;
try
if not Assigned(Item) then
Result := FListItemClass.Create(Self, FItems[Index].Parent, nil)
else
Result := Item;
FItems.Insert(Index, Result);
if (Result <> Item) and Assigned(Item) then
Result.Assign(Item);
finally
EndUpdate;
end;
end;
constructor TListItems.Create(AOwner: TCustomViewControl);
begin
inherited Create(AOwner);
SetItemClass(TListItem);
end;
constructor TListItems.Create(AOwner: TCustomViewControl;
AItemClass: TListItemClass);
begin
inherited Create(AOwner);
SetItemClass(AItemClass);
end;
procedure TListItems.DefineProperties(Filer: TFiler);
function WriteItems: Boolean;
var
I: Integer;
Items: TListItems;
begin
Items := TListItems(Filer.Ancestor);
if (Items = nil) then
Result := Count > 0
else if (Items.Count <> Count) then
Result := True
else
begin
Result := False;
for I := 0 to Count - 1 do
begin
Result := not Item[I].IsEqual(Items[I]);
if Result then Break;
end
end;
end;
begin
inherited DefineProperties(Filer);
Filer.DefineBinaryProperty('Data', ReadData, WriteData, WriteItems);
end;
function TListItems.FindItem(ItemH: QListViewItemH): TListItem;
var
Temp: TCustomViewItem;
begin
Temp := FindViewItem(ItemH);
if Temp is TListItem then
Result := TListItem(Temp)
else
Result := nil;
end;
function TListItems.GetItem(Index: Integer): TListItem;
begin
Result := TListItem(inherited GetItem(Index));
end;
function TListItems.GetItemsOwner: TCustomListView;
begin
Result := FOwner as TCustomListView;
end;
function TListItems.Insert(Index: Integer): TListItem;
begin
Result := AddItem(nil, Index);
end;
type
PItemHeader = ^TItemHeader;
TItemHeader = packed record
Size, Count: Integer;
Items: record end;
end;
PItemInfo = ^TItemInfo;
TItemInfo = packed record
ImageIndex: Integer;
StateIndex: Integer;
OverlayIndex: Integer;
SubItemCount: Integer;
Data: Pointer;
Caption: string[255];
end;
ShortStr = string[255];
PShortStr = ^ShortStr;
procedure TListItems.ReadData(Stream: TStream);
var
I, J, Size, L, Len: Integer;
ItemHeader: PItemHeader;
ItemInfo: PItemInfo;
PStr: PShortStr;
PInt: PInteger;
begin
Clear;
Stream.ReadBuffer(Size, SizeOf(Integer));
ItemHeader := AllocMem(Size);
try
Stream.ReadBuffer(ItemHeader^.Count, Size - SizeOf(Integer));
ItemInfo := @ItemHeader^.Items;
PStr := nil;
for I := 0 to ItemHeader^.Count - 1 do
begin
with Add do
begin
Caption := ItemInfo^.Caption;
ImageIndex := ItemInfo^.ImageIndex;
Data := ItemInfo^.Data;
PStr := @ItemInfo^.Caption;
Inc(Integer(PStr), Length(PStr^) + 1);
Len := 0;
for J := 0 to ItemInfo^.SubItemCount - 1 do
begin
SubItems.Add(PStr^);
L := Length(PStr^);
Inc(Len, L + 1);
Inc(Integer(PStr), L + 1);
end;
end;
Inc(Integer(ItemInfo), SizeOf(TItemInfo) - 255 +
Length(ItemInfo.Caption) + Len);
end;
//read subitem images, if present.
if PChar(PStr) - PChar(ItemHeader) < Size then
begin
PInt := Pointer(PStr);
for I := 0 to Count - 1 do
with Item[I] do
if Assigned(FSubItems) then
for J := 0 to SubItems.Count - 1 do
begin
SubItemImages[J] := PInt^;
Inc(PInt);
end;
end;
finally
FreeMem(ItemHeader, Size);
end;
end;
procedure TListItems.SetItem(Index: Integer; const Value: TListItem);
begin
inherited SetItem(Index, Value);
end;
procedure TListItems.SetItemClass(AListItemClass: TListItemClass);
begin
FListItemClass := AListItemClass;
end;
procedure TListItems.WriteData(Stream: TStream);
var
I, J, Size, L, Len: Integer;
ItemHeader: PItemHeader;
ItemInfo: PItemInfo;
PStr: PShortStr;
PInt: PInteger;
function GetLength(const S: string): Integer;
begin
Result := Length(S);
if Result > 255 then Result := 255;
end;
begin
Size := SizeOf(TItemHeader);
for I := 0 to Count - 1 do
begin
L := GetLength(Item[I].Caption) + 1;
for J := 0 to Item[I].SubItems.Count - 1 do
begin
Inc(L, GetLength(Item[I].SubItems[J]) + 1);
Inc(L, SizeOf(Integer));
end;
Inc(Size, SizeOf(TItemInfo) - 255 + L);
end;
ItemHeader := AllocMem(Size);
try
ItemHeader^.Size := Size;
ItemHeader^.Count := Count;
ItemInfo := @ItemHeader^.Items;
PStr := nil;
for I := 0 to Count - 1 do
begin
with Item[I] do
begin
ItemInfo^.Caption := Caption;
ItemInfo^.ImageIndex := ImageIndex;
ItemInfo^.OverlayIndex := -1 {OverlayIndex};
ItemInfo^.StateIndex := -1 {StateIndex};
ItemInfo^.Data := Data;
ItemInfo^.SubItemCount := SubItems.Count;
PStr := @ItemInfo^.Caption;
Inc(Integer(PStr), Length(ItemInfo^.Caption) + 1);
Len := 0;
for J := 0 to SubItems.Count - 1 do
begin
PStr^ := SubItems[J];
L := Length(PStr^);
Inc(Len, L + 1);
Inc(Integer(PStr), L + 1);
end;
end;
Inc(Integer(ItemInfo), SizeOf(TItemInfo) - 255 +
Length(ItemInfo^.Caption) + Len);
end;
//write SubItem images.
PInt := Pointer(PStr);
for I := 0 to Count - 1 do
begin
with Item[I] do
for J := 0 to SubItems.Count - 1 do
begin
PInt^ := SubItemImages[J];
Inc(PInt);
end;
end;
Stream.WriteBuffer(ItemHeader^, Size);
finally
FreeMem(ItemHeader, Size);
end;
end;
{ THeaderSection }
destructor THeaderSection.Destroy;
begin
if not (csDestroying in Header.ComponentState) and Header.HandleAllocated then
QHeader_removeLabel(Header.Handle, QHeader_mapToIndex(Header.Handle, Index));
inherited Destroy;
end;
procedure THeaderSection.AssignTo(Dest: TPersistent);
begin
inherited AssignTo(Dest);
if Dest is THeaderSection then
THeaderSection(Dest).Text := Text;
end;
{$IF not (defined(LINUX) and defined(VER140))}
function THeaderSection.GetText: WideString;
begin
Result := FText;
end;
{$IFEND}
procedure THeaderSection.SetText(const Value: WideString);
begin
if Text <> Value then
begin
FText := Value;
if Header.HandleAllocated then
QHeader_setLabel(Header.Handle, QHeader_mapToIndex(Header.Handle, Index),
PWideString(@FText), CalcSize);
end;
end;
procedure THeaderSection.SetWidthVal(const Value: Integer);
begin
FWidth := Value;
if Header.HandleAllocated then
QHeader_setLabel(Header.Handle, QHeader_mapToIndex(Header.Handle, Index),
PWideString(@FText), CalcSize);
end;
{ TTreeNode }
constructor TTreeNode.Create(AOwner: TCustomViewItems; AParent:
TCustomViewItem = nil; After: TCustomViewItem = nil);
begin
inherited Create(AOwner, AParent, After);
FSelectedIndex := -1;
end;
destructor TTreeNode.Destroy;
begin
if ViewControlValid then
begin
if TreeView.FLastNode = Self then
TreeView.FLastNode := TTreeNode(FPrevItem);
if Assigned(TreeView.FOnDeletion) then
TreeView.FOnDeletion(TreeView, Self);
end;
inherited Destroy;
end;
function TTreeNode.AlphaSort(Ascending: Boolean): Boolean;
procedure UpdateNodes(ANode: TCustomViewItem);
var
TempNext: TCustomViewItem;
TempPrev: TCustomViewItem;
TempItem: QListViewItemH;
begin
if Assigned(Owner) then
begin
TempItem := QListViewItem_firstChild(ANode.Handle);
if Assigned(TempItem) then
begin
TempPrev := Owner.FindItem(TempItem);
if Assigned(TempPrev) then
begin
TempPrev.FPrevItem := nil;
while Assigned(TempItem) do
begin
UpdateNodes(TempPrev);
TempItem := QListViewItem_nextSibling(TempItem);
if not Assigned(TempItem) then
Break;
TempNext := Owner.FindItem(TempItem);
TempPrev.FNextItem := TempNext;
if Assigned(TempNext) then
TempNext.FPrevItem := TempPrev;
TempPrev := TempNext;
end;
ANode.FLastChild := TempPrev;
end;
end;
end;
end;
begin
Result := HandleAllocated;
if Result then
begin
QListViewItem_sortChildItems(Handle, 0, Ascending);
UpdateNodes(Self);
if ViewControlValid then
ViewControl.UpdateControl;
end;
end;
procedure TTreeNode.AssignTo(Dest: TPersistent);
var
Node: TTreeNode;
begin
inherited AssignTo(Dest);
if Dest is TTreeNode then
begin
Node := TTreeNode(Dest);
Node.Text := Text;
Node.HasChildren := HasChildren;
Node.SelectedIndex := SelectedIndex;
end;
end;
procedure TTreeNode.Collapse(Recurse: Boolean);
begin
ExpandItem(False, Recurse);
end;
function TTreeNode.CompareCount(CompareMe: Integer): Boolean;
var
Count: integer;
Node: TTreeNode;
Begin
Count := 0;
Result := False;
Node := GetFirstChild;
while Node <> nil do
begin
Inc(Count);
Node := Node.GetNextChild(Node);
if Count > CompareMe then
Exit;
end;
if Count = CompareMe then
Result := True;
end;
procedure TTreeNode.Delete;
begin
if not Deleting then
Free;
end;
procedure TTreeNode.DeleteChildren;
var
Node: TTreeNode;
begin
Node := getFirstChild;
while Node <> nil do
begin
Node.Free;
Node := getFirstChild;
end;
end;
function TTreeNode.DoCanExpand(Expand: Boolean): Boolean;
begin
Result := False;
if HasChildren then
begin
if Expand then
Result := TreeView.CanExpand(Self)
else
Result := TreeView.CanCollapse(Self);
end;
end;
function TTreeNode.EditText: Boolean;
begin
if ViewControlValid then
begin
Selected := True;
ViewControl.EditItem;
end;
Result := Assigned(ViewControl.FEditor) and ViewControl.FEditor.FEditing;
end;
procedure TTreeNode.Expand(Recurse: Boolean);
begin
ExpandItem(True, Recurse);
end;
procedure TTreeNode.ExpandItem(Expand, Recurse: Boolean);
var
Node: TTreeNode;
begin
if Recurse then
begin
Node := Self;
repeat
Node.ExpandItem(Expand, False);
Node := Node.GetNext;
until (Node = nil) or (not Node.HasAsParent(Self));
end
else
Expanded := Expand;
end;
function TTreeNode.GetAbsoluteIndex: Integer;
var
Node: TTreeNode;
begin
Result := -1;
Node := Self;
while Node <> nil do
begin
Inc(Result);
Node := Node.GetPrev;
end;
end;
function TTreeNode.GetCount: Integer;
var
Node: TTreeNode;
begin
Result := 0;
Node := GetFirstChild;
while Node <> nil do
begin
Inc(Result);
Node := Node.GetNextChild(Node);
end;
end;
{$IF not (defined(LINUX) and defined(VER140))}
function TTreeNode.GetSelected: Boolean;
begin
Result := inherited GetSelected;
end;
procedure TTreeNode.SetSelected(const Value: Boolean);
begin
inherited SetSelected(Value);
end;
function TTreeNode.GetExpandable: Boolean;
begin
Result := FExpandable;
end;
procedure TTreeNode.SetExpandable(const Value: Boolean);
begin
inherited SetExpandable(Value);
end;
function TTreeNode.GetCaption: WideString;
begin
Result := FText;
end;
procedure TTreeNode.SetCaption(const Value: WideString);
begin
inherited SetCaption(Value);
end;
{$IFEND}
function TTreeNode.GetDropTarget: Boolean;
begin
if ViewControlValid then
Result := TreeView.DropTarget = Self
else
Result := False;
end;
function TTreeNode.getFirstChild: TTreeNode;
begin
if HandleAllocated then
Result := Owner.FindItem(QListViewItem_firstChild(Handle))
else
Result := nil;
end;
function TTreeNode.GetIndex: Integer;
var
Node: TTreeNode;
begin
Result := -1;
Node := Self;
while Node <> nil do
begin
Inc(Result);
Node := Node.GetPrevSibling;
end;
end;
function TTreeNode.GetItem(Index: Integer): TTreeNode;
begin
Result := GetFirstChild;
while Assigned(Result) and (Index > 0) do
begin
Result := GetNextChild(Result);
Dec(Index);
end;
if Result = nil then
TreeViewError(Format(SListIndexError,[Index]));
end;
function TTreeNode.GetLastChild: TTreeNode;
begin
if FLastChild is TTreeNode then
Result := TTreeNode(FLastChild)
else
Result := nil;
end;
function TTreeNode.GetLevel: Integer;
begin
if HandleAllocated then
Result := QListViewItem_Depth(Handle)
else
Result := -1;
end;
function TTreeNode.GetNext: TTreeNode;
var
ChildNodeID, ParentID: QListViewItemH;
begin
Result := nil;
if HandleAllocated then
begin
ChildNodeID := QListViewItem_firstChild(Handle);
if ChildNodeID = nil then
ChildNodeID := QListViewItem_nextSibling(Handle);
ParentID := Handle;
while (ChildNodeID = nil) and (ParentID <> nil) do
begin
ParentID := QListViewItem_parent(ParentID);
if ParentID = nil then
Break;
ChildNodeID := QListViewItem_nextSibling(ParentID);
end;
Result := TTreeNodes(FOwner).FindItem(ChildNodeID);
end;
end;
function TTreeNode.GetNextChild(Value: TTreeNode): TTreeNode;
begin
if Value <> nil then
Result := Value.GetNextSibling
else
Result := nil;
end;
function TTreeNode.getNextSibling: TTreeNode;
begin
if HandleAllocated then
Result := Owner.FindItem(QListViewItem_nextSibling(Handle))
else
Result := nil;
end;
function TTreeNode.GetNextVisible: TTreeNode;
begin
Result := GetNext;
while Assigned(Result) and not Result.IsNodeVisible do
Result := Result.GetNext;
end;
function TTreeNode.GetNodeOwner: TTreeNodes;
begin
Result := FOwner as TTreeNodes;
end;
function TTreeNode.GetParent: TTreeNode;
begin
Result := FParent as TTreeNode;
end;
function TTreeNode.GetPrev: TTreeNode;
var
Node: TTreeNode;
begin
Result := GetPrevSibling;
if Result <> nil then
begin
Node := Result;
repeat
Result := Node;
Node := Result.GetLastChild;
until Node = nil;
end else
Result := Parent;
end;
function TTreeNode.GetPrevChild(Value: TTreeNode): TTreeNode;
begin
if Value <> nil then
Result := Value.GetPrevSibling
else
Result := nil;
end;
function TTreeNode.getPrevSibling: TTreeNode;
begin
Result := nil;
if Assigned(Owner) then
Result := Owner.FindPrevSibling(Self);
end;
function TTreeNode.GetPrevVisible: TTreeNode;
begin
Result := GetPrev;
while Assigned(Result) and not Result.IsNodeVisible do
Result := Result.GetPrev;
end;
function TTreeNode.GetTreeView: TCustomTreeView;
begin
Result := FOwner.FOwner as TCustomTreeView;
end;
function TTreeNode.HasAsParent(Value: TTreeNode): Boolean;
begin
if Value <> nil then
begin
if Parent = nil then
Result := False
else if Parent = Value then
Result := True
else
Result := Parent.HasAsParent(Value);
end
else
Result := True;
end;
function TTreeNode.IndexOf(Value: TTreeNode): Integer;
var
Node: TTreeNode;
begin
Result := -1;
Node := GetFirstChild;
while Node <> nil do
begin
Inc(Result);
if Node = Value then
Break;
Node := GetNextChild(Node);
end;
if Node = nil then
Result := -1;
end;
procedure TTreeNode.ImageIndexChange(ColIndex: Integer; NewIndex: Integer);
var
Pixmap: QPixmapH;
begin
if HandleAllocated and ViewControlValid and Assigned(ViewControl.Images) then
begin
if Selected then
begin
Pixmap := ViewControl.Images.GetPixmap(SelectedIndex);
if Assigned(Pixmap) then
begin
QListViewItem_setPixmap(Handle, 0, Pixmap);
Exit;
end;
end;
inherited ImageIndexChange(ColIndex, NewIndex);
end;
end;
function TTreeNode.IsEqual(Node: TTreeNode): Boolean;
begin
Result := (Text = Node.Text) and (Data = Node.Data);
end;
function TTreeNode.IsNodeVisible: Boolean;
var
R: TRect;
begin
if HandleAllocated then
begin
QListView_itemRect(Owner.Owner.Handle, @R, Handle);
Result := not ((R.Right = -1) and (R.Bottom = -1));
end
else
Result := False;
end;
procedure TTreeNode.MoveTo(Destination: TTreeNode; Mode: TNodeAttachMode);
var
OldOnChange: TTVChangedEvent;
NextSib: TTreeNode;
begin
OldOnChange := TreeView.OnChange;
TreeView.OnChange := nil;
Owner.BeginUpdate;
try
if not Assigned(Destination) or
(Assigned(Destination) and Destination.HasAsParent(Self))
and (Destination <> Self) then
Exit;
case Mode of
naAdd:
begin
Parent := Destination.Parent;
if not Assigned(Parent) then
begin
if ViewControlValid then
begin
QListView_insertItem(ViewControl.Handle, Handle);
if Assigned(TreeView.FLastNode) then
begin
QListViewItem_moveItem(Handle, TreeView.FLastNode.Handle);
if Assigned(FPrevItem) then
FPrevItem.FNextItem := FNextItem;
if Assigned(FNextItem) then
FNextItem.FPrevItem := FPrevItem;
FPrevItem := TreeView.FLastNode;
TreeView.FLastNode.FNextItem := Self;
end;
FNextItem := nil;
TreeView.FLastNode := Self;
end;
end;
end;
naAddFirst:
begin
Parent := Destination.Parent;
if not Assigned(Parent) then
begin
if ViewControlValid then
begin
QListView_insertItem(ViewControl.Handle, Handle);
NextSib := TreeView.Items.FindItem(QListView_firstChild(ViewControl.Handle));
end
else
NextSib := nil;
end
else
NextSib := Parent.getFirstChild;
if Assigned(NextSib) then
begin
QListViewItem_moveItem(Handle, NextSib.Handle);
QListViewItem_moveItem(NextSib.Handle, Handle);
if Assigned(FPrevItem) then
FPrevItem.FNextItem := FNextItem;
if Assigned(FNextItem) then
FNextItem.FPrevItem := FPrevItem;
FPrevItem := nil;
FNextItem := NextSib;
NextSib.FPrevItem := Self;
end;
end;
naAddChild:
Parent := Destination;
naAddChildFirst:
begin
Parent := Destination;
if Parent.FLastChild = Self then
Parent.FLastChild := FPrevItem;
if Assigned(FPrevItem) then
FPrevItem.FNextItem := FNextItem;
if Assigned(FNextItem) then
FNextItem.FPrevItem := FPrevItem;
FPrevItem := nil;
FNextItem := Parent.getFirstChild;
if Assigned(FNextItem) then
begin
FNextItem.FPrevItem := Self;
QListViewItem_moveItem(Handle, FNextItem.Handle);
QListViewItem_moveItem(FNextItem.Handle, Handle);
end
else
Parent.FLastChild := Self;
end;
naInsert:
begin
Parent := Destination.Parent;
if Assigned(FPrevItem) then
FPrevItem.FNextItem := FNextItem;
if Assigned(FNextItem) then
FNextItem.FPrevItem := FPrevItem;
FPrevItem := Destination.FPrevItem;
FNextItem := Destination;
FNextItem.FPrevItem := Self;
if Assigned(FPrevItem) then
FPrevItem.FNextItem := Self;
if not Assigned(Parent) and ViewControlValid then
QListView_insertItem(ViewControl.Handle, Handle);
if Assigned(FNextItem) then
begin
QListViewItem_moveItem(Handle, FNextItem.Handle);
QListViewItem_moveItem(FNextItem.Handle, Handle);
end;
end;
end;
if Assigned(Parent) then
begin
Parent.HasChildren := True;
Parent.Expanded := True;
end;
finally
TreeView.OnChange := OldOnChange;
Owner.EndUpdate;
end;
end;
procedure TTreeNode.ReadData(Stream: TStream; Info: PNodeInfo);
var
I, Size, ItemCount: Integer;
PStr: PShortStr;
PInt: PInteger;
begin
Stream.ReadBuffer(Size, SizeOf(Size));
Stream.ReadBuffer(Info^, Size);
Text := Info^.Text;
ImageIndex := Info^.ImageIndex;
SelectedIndex := Info^.SelectedIndex;
Data := Info^.Data;
ItemCount := Info^.Count;
PStr := @Info^.Text;
Inc(Integer(PStr), Length(PStr^) + 1);
for I := 0 to Info^.SubItemCount - 1 do
begin
SubItems.Add(PStr^);
Integer(PStr) := Integer(PStr) + (Length(PStr^) + 1);
end;
if (Size - (Integer(@PStr^[0]) - Integer(Info))) <> 0 then
begin
PInt := Pointer(PStr);
for I := 0 to SubItems.Count - 1 do
begin
SubItemImages[I] := PInt^;
Inc(PInt);
end;
end;
for I := 0 to ItemCount - 1 do
Owner.AddChild(Self, '').ReadData(Stream, Info);
end;
procedure TTreeNode.SetItem(Index: Integer; const Value: TTreeNode);
begin
Item[Index].Assign(Value);
end;
procedure TTreeNode.SetNodeParent(const Value: TTreeNode);
begin
if Parent <> Value then
SetParent(Value);
end;
procedure TTreeNode.SetSelectedIndex(const Value: Integer);
begin
if FSelectedIndex <> Value then
begin
FSelectedIndex := Value;
if Selected then
ImageIndexChange(0, ImageIndex);
end;
end;
procedure TTreeNode.WriteData(Stream: TStream; Info: PNodeInfo);
function GetLength(const S: string): Integer;
begin
Result := Length(S);
if Result > 255 then Result := 255;
end;
var
I, Size, L, ItemCount: Integer;
PStr: PShortStr;
PInt: PInteger;
begin
L := GetLength(Text);
for I := 0 to SubItems.Count - 1 do
begin
Inc(L, GetLength(SubItems[I]) + 1);
Inc(L, SizeOf(Integer));
end;
Size := SizeOf(TNodeInfo) + L - 255;
Info^.Text := Text;
Info^.ImageIndex := ImageIndex;
Info^.SelectedIndex := SelectedIndex;
Info^.Data := Data;
ItemCount := Count;
Info^.Count := ItemCount;
Info^.SubItemCount := SubItems.Count;
PStr := @Info^.Text;
Inc(Integer(PStr), Length(Info^.Text) + 1);
for I := 0 to SubItems.Count - 1 do
begin
PStr^ := SubItems[I];
Integer(PStr) := Integer(PStr) + (Length(PStr^) + 1);
end;
//write SubItem images.
PInt := Pointer(PStr);
for I := 0 to SubItems.Count - 1 do
begin
PInt^ := SubItemImages[I];
Inc(PInt);
end;
Stream.WriteBuffer(Size, SizeOf(Size));
Stream.WriteBuffer(Info^, Size);
for I := 0 to ItemCount - 1 do
Item[I].WriteData(Stream, Info);
end;
{ TTreeNodes }
function TTreeNodes.Add(Node: TTreeNode; const S: WideString): TTreeNode;
begin
Result := AddObject(Node, S, nil);
end;
function TTreeNodes.AddChild(Node: TTreeNode; const S: WideString): TTreeNode;
begin
Result := AddChildObject(Node, S, nil);
end;
function TTreeNodes.AddChildFirst(Node: TTreeNode;
const S: WideString): TTreeNode;
begin
Result := AddChildObjectFirst(Node, S, nil);
end;
function TTreeNodes.AddChildObject(Node: TTreeNode; const S: WideString;
Ptr: Pointer): TTreeNode;
begin
Result := InternalAddObject(Node, S, Ptr, taAdd);
end;
function TTreeNodes.AddChildObjectFirst(Node: TTreeNode; const S: WideString;
Ptr: Pointer): TTreeNode;
begin
Result := InternalAddObject(Node, S, Ptr, taAddFirst);
end;
function TTreeNodes.AddFirst(Node: TTreeNode; const S: WideString): TTreeNode;
begin
Result := AddObjectFirst(Node, S, nil);
end;
function TTreeNodes.AddObject(Node: TTreeNode; const S: WideString;
Ptr: Pointer): TTreeNode;
begin
if Assigned(Node) then
Node := Node.Parent;
Result := InternalAddObject(Node, S, Ptr, taAdd);
end;
function TTreeNodes.AddObjectFirst(Node: TTreeNode; const S: WideString;
Ptr: Pointer): TTreeNode;
begin
if Assigned(Node) then
Node := Node.Parent;
Result := InternalAddObject(Node, S, Ptr, taAddFirst);
end;
procedure TTreeNodes.Assign(Dest: TPersistent);
var
TreeNodes: TTreeNodes;
MemStream: TMemoryStream;
begin
if Dest is TTreeNodes then
begin
TreeNodes := TTreeNodes(Dest);
Clear;
MemStream := TMemoryStream.Create;
try
TreeNodes.WriteData(MemStream);
MemStream.Position := 0;
ReadData(MemStream);
finally
MemStream.Free;
end;
end
else
inherited Assign(Dest);
end;
procedure TTreeNodes.Clear;
begin
BeginUpdate;
try
FItems.Clear;
if Owner.HandleAllocated then
QListView_clear(Owner.Handle);
finally
EndUpdate;
end;
end;
function TTreeNodes.CreateNode(ParentNode, AfterNode: TTreeNode): TTreeNode;
begin
Result := FNodeClass.Create(Self, ParentNode, AfterNode);
end;
procedure TTreeNodes.DefineProperties(Filer: TFiler);
function WriteNodes: Boolean;
var
I: Integer;
Nodes: TTreeNodes;
begin
Nodes := TTreeNodes(Filer.Ancestor);
if Nodes = nil then
Result := Count > 0
else if Nodes.Count <> Count then
Result := True
else
begin
Result := False;
for I := 0 to Count - 1 do
begin
Result := not Item[I].IsEqual(Nodes[I]);
if Result then Break;
end
end;
end;
begin
inherited DefineProperties(Filer);
Filer.DefineBinaryProperty('Data', ReadData, WriteData, WriteNodes);
end;
procedure TTreeNodes.Delete(Node: TTreeNode);
begin
if Assigned(Node) then
Node.Delete;
end;
function TTreeNodes.FindItem(ItemH: QListViewItemH): TTreeNode;
var
Temp: TCustomViewItem;
begin
Temp := FindViewItem(ItemH);
if Temp is TTreeNode then
Result := TTreeNode(Temp)
else
Result := nil;
end;
function TTreeNodes.FindPrevSibling(ANode: TTreeNode): TTreeNode;
var
Node: TTreeNode;
Node2: TTreeNode;
begin
Result := nil;
if ANode.FPrevItem is TTreeNode then
Result := TTreeNode(ANode.FPrevItem);
if not Assigned(Result) then
begin
if Assigned(ANode.Parent) then
Node := ANode.Parent.getFirstChild
else
Node := GetFirstNode;
if Node <> ANode then
begin
while Assigned(Node) do
begin
Node2 := Node;
Node := Node.getNextSibling;
if Node = ANode then
begin
Result := Node2;
Exit;
end;
end;
end;
end;
end;
function TTreeNodes.GetFirstNode: TTreeNode;
begin
if Owner.HandleAllocated then
Result := FindItem(QListView_firstChild(Handle))
else if Count > 0 then
Result := Item[0]
else
Result := nil;
end;
function TTreeNodes.GetItem(Index: Integer): TTreeNode;
begin
Result := TTreeNode(inherited GetItem(Index));
end;
function TTreeNodes.GetNode(ItemH: QListViewItemH): TTreeNode;
begin
Result := FindItem(ItemH);
end;
function TTreeNodes.GetNodesOwner: TCustomTreeView;
begin
Result := FOwner as TCustomTreeView;
end;
function TTreeNodes.Insert(Node: TTreeNode; const S: WideString): TTreeNode;
begin
Result := InternalAddObject(Node, S, nil, taInsert);
end;
function TTreeNodes.InsertObject(Node: TTreeNode; const S: WideString;
Ptr: Pointer): TTreeNode;
begin
if Node <> nil then
Node := Node.Parent;
Result := InternalAddObject(Node, S, Ptr, taInsert);
end;
function TTreeNodes.InternalAddObject(Node: TTreeNode; const S: WideString;
Ptr: Pointer; AddMode: TAddMode): TTreeNode;
var
ParentNode, AfterNode: TTreeNode;
begin
Result := nil;
ParentNode := Node;
AfterNode := nil;
try
case AddMode of
taAdd:
if Assigned(ParentNode) then
AfterNode := ParentNode.GetLastChild
else if Assigned(Owner) then
AfterNode := Owner.FLastNode;
taInsert:
begin
if Assigned(Node) then
ParentNode := Node.Parent
else
ParentNode := nil;
if Assigned(Node) then
AfterNode := Node.getPrevSibling;
end;
end;
Result := CreateNode(ParentNode, AfterNode);
FItems.Add(Result);
if (AddMode = taAdd) then
if not Assigned(Result.Parent) and Assigned(Owner) then
Owner.FLastNode := Result
else if Assigned(Result.Parent) then
Result.Parent.FLastChild := Result;
if Assigned(Result.Parent) then
begin
if not Assigned(Result.Parent.FLastChild) then
Result.Parent.FLastChild := Result;
Result.Parent.HasChildren := True;
end;
Result.Data := Ptr;
Result.Text := S;
if Assigned(Owner) and Owner.Visible and (FUpdateCount = 0) then
if not Assigned(Result.Parent) or
(Assigned(Result.Parent) and Result.Parent.Expanded) then
Result.MakeVisible(False);
if Assigned(Owner.FOnInsert) then
Owner.FOnInsert(Owner, Result);
except
Result.Free;
raise;
end;
end;
procedure TTreeNodes.ReadData(Stream: TStream);
var
I, Count: Integer;
NodeInfo: TNodeInfo;
begin
if Owner.HandleAllocated then BeginUpdate;
try
Clear;
Stream.ReadBuffer(Count, SizeOf(Count));
for I := 0 to Count - 1 do
Add(nil, '').ReadData(Stream, @NodeInfo);
finally
if Owner.HandleAllocated then EndUpdate;
end;
end;
procedure TTreeNodes.WriteData(Stream: TStream);
var
I: Integer;
Node: TTreeNode;
NodeInfo: TNodeInfo;
begin
I := 0;
Node := GetFirstNode;
while Node <> nil do
begin
Inc(I);
Node := Node.GetNextSibling;
end;
Stream.WriteBuffer(I, SizeOf(I));
Node := GetFirstNode;
while Node <> nil do
begin
Node.WriteData(Stream, @NodeInfo);
Node := Node.GetNextSibling;
end;
Stream.Position := 0;
end;
procedure TTreeNodes.SetNodeClass(NewNodeClass: TTreeNodeClass);
begin
FNodeClass := NewNodeClass;
end;
{ TListItem }
destructor TListItem.Destroy;
begin
if ViewControlValid and Assigned(ListView.FOnDeletion) then
ListView.FOnDeletion(ListView, Self);
inherited Destroy;
end;
function TListItem.IsEqual(Item: TListItem): Boolean;
begin
Result := (Caption = Item.Caption) and (Data = Item.Data);
end;
{$IF not (defined(LINUX) and defined(VER140))}
function TListItem.GetCaption: WideString;
begin
Result := FText;
end;
procedure TListItem.SetCaption(Value: WideString);
begin
inherited SetCaption(Value);
end;
{$IFEND}
function TListItem.GetListView: TCustomListView;
begin
Result := Owner.FOwner as TCustomListView;
end;
function TListItem.GetOwnerlist: TListItems;
begin
Result := FOwner as TListItems;
end;
{ TCustomSpinEdit }
constructor TCustomSpinEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
TabStop := True;
Palette.ColorRole := crBase;
Palette.TextColorRole := crText;
Color := clBase;
Height := 23;
InputKeys := [ikArrows];
end;
procedure TCustomSpinEdit.StepUp;
begin
QSpinBox_stepUp(Handle);
end;
procedure TCustomSpinEdit.StepDown;
begin
QSpinBox_stepDown(Handle);
end;
function TCustomSpinEdit.GetHandle: QClxSpinBoxH;
begin
HandleNeeded;
Result := QClxSpinBoxH(FHandle);
end;
function TCustomSpinEdit.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
var
R: TRect;
P: TPoint;
begin
{ Since Qt is not sending any messages for the up or down button when disabled
we decided to only show any popup menu if a right click happens to the left
of the buttons. }
if (QEvent_type(Event) = QEventType_MouseButtonPress) and
(QMouseEvent_button(QMouseEventH(Event)) = ButtonState_RightButton) then
begin
QWidget_geometry(QWidgetH(FUpButtonHandle), @R);
P.X := QMouseEvent_x(QMouseEventH(Event));
P.Y := QMouseEvent_y(QMouseEventH(Event));
if Sender <> Handle then
QWidget_mapToParent(QWidgetH(Sender), @P, @P);
if P.X >= R.Left then
begin
Result := False;
Exit;
end;
end;
if (Sender = FEditHandle) or
(Sender = FUpButtonHandle) or
(Sender = FDownButtonHandle) then
begin
Result := inherited EventFilter(Sender, Event);
{ Internal Qt aggregated controls should return False (not handled) at this
point but there are a few exceptions:
1. The right mouse press: This is handled in EventFilter depending
on whether the PopupMenu was activated.
2. Enter and Leave messages should only come from the container. }
if ((QEvent_type(Event) = QEventType_MouseButtonPress) and
(QMouseEvent_button(QMouseEventH(Event)) = ButtonState_RightButton)) then
Exit
else
if (QEvent_type(Event) = QEventType_Enter) or
(QEvent_type(Event) = QEventType_Leave) then
begin
{ When the focus leaves we force the button up. There is the very likely
chance that if the OnClick event displays a modal form and the mouse
click was on a button then it would keep incrementing the value }
if (Sender = FUpButtonHandle) or (Sender = FDownButtonHandle) then
QButton_setDown(QButtonH(Sender), False);
Result := True;
end else
Result := False;
end
else
Result := inherited EventFilter(Sender, Event);
end;
procedure TCustomSpinEdit.CreateWidget;
var
Method: TMethod;
begin
FHandle := QClxSpinBox_create(0, 100, 1, ParentWidget, nil);
Hooks := QSpinBox_hook_create(FHandle);
FEditHandle := QClxSpinBox_editor(Handle);
FUpButtonHandle := QClxSpinBox_upButton(Handle);
FDownButtonHandle := QClxSpinBox_downButton(Handle);
FEditHook := QWidget_hook_create(FEditHandle);
FButtonUpHook := QWidget_hook_create(FUpButtonHandle);
FButtonDownHook := QWidget_hook_create(FDownButtonHandle);
{ How to handle Qt aggregated internal controls:
1. Hook each internal control to point to the MainEventFilter.
( You get events first so squash ones you don't want QT to process
and let the others through. )
2. Call QClxObjectMap_add for each control passing in the handle and a
reference to the host control cast as an Integer.
3. Call QWidget_setMouseTracking for each control with the handle and True.
( Qt has this off by default. This allows us to get mouse move messages
even when the mouse button is not pressed. ) }
TEventFilterMethod(Method) := MainEventFilter;
Qt_hook_hook_events(FEditHook, Method);
Qt_hook_hook_events(FButtonUpHook, Method);
Qt_hook_hook_events(FButtonDownHook, Method);
QClxObjectMap_add(FEditHandle, Integer(Self));
QClxObjectMap_add(FUpButtonHandle, Integer(Self));
QClxObjectMap_add(FDownButtonHandle, Integer(Self));
QWidget_setMouseTracking(FEditHandle, True);
QWidget_setMouseTracking(FUpButtonHandle, True);
QWidget_setMouseTracking(FDownButtonHandle, True);
end;
procedure TCustomSpinEdit.WidgetDestroyed;
begin
QClxObjectMap_remove(FEditHandle);
QClxObjectMap_remove(FUpButtonHandle);
QClxObjectMap_remove(FDownButtonHandle);
QWidget_hook_destroy(FEditHook);
QWidget_hook_destroy(FButtonUpHook);
QWidget_hook_destroy(FButtonDownHook);
inherited WidgetDestroyed;
end;
function TCustomSpinEdit.GetButtonStyle: TSEButtonStyle;
begin
Result := TSEButtonStyle(QSpinBox_buttonSymbols(Handle));
end;
function TCustomSpinEdit.GetCleanText: WideString;
begin
QSpinBox_cleanText(Handle, PWideString(@Result));
end;
function TCustomSpinEdit.GetIncrement: Integer;
begin
Result := QSpinBox_lineStep(Handle);
end;
function TCustomSpinEdit.GetMax: Integer;
begin
Result := QSpinBox_maxValue(Handle);
end;
function TCustomSpinEdit.GetMin: Integer;
begin
Result := QSpinBox_minValue(Handle);
end;
function TCustomSpinEdit.GetPrefix: WideString;
begin
QSpinBox_prefix(Handle, PWideString(@Result));
end;
function TCustomSpinEdit.GetRangeControl: QRangeControlH;
begin
Result := QSpinBox_to_QRangeControl(Handle);
end;
function TCustomSpinEdit.GetSuffix: WideString;
begin
QSpinBox_suffix(Handle, PWideString(@Result));
end;
function TCustomSpinEdit.GetSpecialText: WideString;
begin
QSpinBox_specialValueText(Handle, PWideString(@Result));
end;
procedure TCustomSpinEdit.Change(AValue: Integer);
begin
if Assigned(FOnChanged) then
FOnChanged(Self, AValue);
end;
function TCustomSpinEdit.GetText: TCaption;
begin
QSpinBox_text(Handle, PWideString(@Result));
end;
procedure TCustomSpinEdit.InitWidget;
begin
inherited InitWidget;
SetRange(Min, Max);
end;
procedure TCustomSpinEdit.Loaded;
begin
inherited Loaded;
SetRange(FMin, FMax);
end;
procedure TCustomSpinEdit.PaletteChanged(Sender: TObject);
begin
inherited;
QWidget_setPalette(FEditHandle, (Sender as TPalette).Handle, True);
end;
function TCustomSpinEdit.GetWrap: Boolean;
begin
Result := QSpinBox_wrapping(Handle);
end;
procedure TCustomSpinEdit.SetMin(AValue: Integer);
begin
if (csLoading in ComponentState) then
SetRange(AValue, FMax)
else
SetRange(AValue, Max);
end;
procedure TCustomSpinEdit.SetMax(AValue: Integer);
begin
if (csLoading in ComponentState) then
SetRange(FMin, AValue)
else
SetRange(Min, AValue);
end;
procedure TCustomSpinEdit.SetButtonStyle(AValue: TSEButtonStyle);
begin
QSpinBox_setButtonSymbols(Handle, QSpinBoxButtonSymbols(AValue));
end;
procedure TCustomSpinEdit.SetIncrement(AValue: Integer);
begin
QSpinBox_setLineStep(Handle, AValue);
end;
procedure TCustomSpinEdit.SetPrefix(const AValue: WideString);
begin
QSpinBox_setPrefix(Handle, PWideString(@AValue));
end;
procedure TCustomSpinEdit.SetRange(const AMin, AMax: Integer);
begin
FMin := AMin;
FMax := AMax;
if not HandleAllocated or (csLoading in ComponentState) then
Exit;
try
CheckRange(AMin, AMax);
except
FMin := Min;
FMax := Max;
raise;
end;
QRangeControl_setRange(RangeControl, FMin, FMax);
if Value < Min then
Value := Min
else if Value > Max then Value := Max;
end;
procedure TCustomSpinEdit.SetSuffix(const AValue: WideString);
begin
QSpinBox_setSuffix(Handle, PWideString(@AValue));
end;
procedure TCustomSpinEdit.SetSpecialText(const AValue: WideString);
begin
QSpinBox_setSpecialValueText(Handle, PWideString(@AValue));
end;
procedure TCustomSpinEdit.SetWrap(AValue: Boolean);
begin
QSpinBox_setWrapping(Handle, AValue);
end;
procedure TCustomSpinEdit.HookEvents;
var
Method: TMethod;
begin
inherited HookEvents;
QSpinBox_valueChanged_Event(Method) := ValueChangedHook;
QSpinBox_hook_hook_valueChanged(QSpinBox_hookH(Hooks), Method);
end;
procedure TCustomSpinEdit.ValueChangedHook(AValue: Integer);
begin
try
Change(AValue);
except
Application.HandleException(Self);
end;
end;
function TCustomSpinEdit.GetValue: Integer;
begin
Result := StrToIntDef(CleanText, Min);
end;
{ wrapper for the default Mime Factory }
type
TDefaultFactory = class(TMimeSourceFactory)
protected
procedure CreateHandle; override;
procedure DestroyWidget; override;
end;
var
PrivateFactory: TMimeSourceFactory;
type
TMimeFactoryStrings = class(TStringList)
private
FOwner: TMimeSourceFactory;
protected
function Add(const S: string): Integer; override;
procedure Delete(Index: Integer); override;
procedure Put(Index: Integer; const S: string); override;
procedure ResetFilePath;
public
constructor Create(AOwner: TMimeSourceFactory);
procedure Insert(Index: Integer; const S: string); override;
procedure Assign(Source: TPersistent); override;
end;
{ global routines for the Default Factory }
function DefaultMimeFactory: TMimeSourceFactory;
begin
if PrivateFactory = nil then
PrivateFactory := TDefaultFactory.Create;
Result := PrivateFactory;
end;
procedure SetDefaultMimeFactory(Value: TMimeSourceFactory);
begin
if Assigned(Value) then
begin
PrivateFactory := Value;
QMimeSourceFactory_setDefaultFactory(Value.Handle);
end;
end;
{ TBrowserStrings }
function TMimeFactoryStrings.Add(const S: string): Integer;
var
Temp: WideString;
begin
Result := inherited Add(S);
if Assigned(FOwner) then
begin
Temp := S;
QMimeSourceFactory_addFilePath(FOwner.Handle, PWideString(@Temp));
end;
end;
procedure TMimeFactoryStrings.Assign(Source: TPersistent);
begin
inherited Assign(Source);
ResetFilePath;
end;
constructor TMimeFactoryStrings.Create(AOwner: TMimeSourceFactory);
begin
inherited Create;
FOwner := AOwner;
end;
procedure TMimeFactoryStrings.Delete(Index: Integer);
begin
inherited Delete(Index);
ResetFilePath;
end;
procedure TMimeFactoryStrings.Insert(Index: Integer; const S: string);
begin
inherited Insert(Index, S);
ResetFilePath;
end;
procedure TMimeFactoryStrings.Put(Index: Integer; const S: string);
begin
inherited Put(Index, S);
ResetFilePath;
end;
procedure TMimeFactoryStrings.ResetFilePath;
var
Temp: QStringListH;
begin
if Assigned(FOwner) then
begin
Temp := TStringsToQStringList(Self);
try
QMimeSourceFactory_setFilePath(FOwner.Handle, Temp);
finally
QStringList_destroy(Temp);
end;
end;
end;
procedure TCustomSpinEdit.SetValue(const AValue: Integer);
begin
QSpinBox_setValue(Handle, AValue);
end;
{ TMimeSourceFactory }
constructor TMimeSourceFactory.Create;
begin
inherited Create;
FFilePath := TMimeFactoryStrings.Create(Self);
end;
destructor TMimeSourceFactory.Destroy;
begin
DestroyWidget;
FFilePath.Free;
inherited Destroy;
end;
type
TMimeSourceFactory_datacallback = procedure (AbsoluteName: PWideString;
var ResolvedData: QMimeSourceH) of object cdecl;
procedure TMimeSourceFactory.CreateHandle;
var
Method: TMethod;
begin
FHandle := QClxMimeSourceFactory_create;
TMimeSourceFactory_datacallback(Method) := DoGetDataHook;
QClxMimeSourceFactory_setDataCallBack(QClxMimeSourceFactoryH(FHandle), Method);
end;
procedure TMimeSourceFactory.DoGetDataHook(AbsoluteName: PWideString;
var ResolvedData: QMimeSourceH);
begin
try
GetData(AbsoluteName^, ResolvedData);
except
Application.HandleException(Self);
end;
end;
procedure TMimeSourceFactory.GetData(const AbsoluteName: string;
var ResolvedData: QMimeSourceH);
begin
{ stubbed for children }
end;
function TMimeSourceFactory.GetHandle: QMimeSourceFactoryH;
begin
HandleNeeded;
Result := FHandle;
end;
function TMimeSourceFactory.HandleAllocated: Boolean;
begin
Result := FHandle <> nil;
end;
procedure TMimeSourceFactory.HandleNeeded;
begin
if not HandleAllocated then
CreateHandle;
end;
procedure TMimeSourceFactory.SetFilePath(const Value: TStrings);
begin
FFilePath.Assign(Value);
end;
procedure TMimeSourceFactory.RegisterMimeType(const FileExt: WideString;
const MimeType: string);
begin
QMimeSourceFactory_setExtensionType(Handle, PWideString(@FileExt),
PChar(MimeType));
end;
procedure TMimeSourceFactory.AddTextToFactory(const Name: WideString;
const Data: string);
begin
QMimeSourceFactory_setText(Handle, PWideString(@Name), @Data);
end;
procedure TMimeSourceFactory.AddImageToFactory(const Name: WideString;
Data: QImageH);
begin
QMimeSourceFactory_setImage(Handle, PWideString(@Name), Data);
end;
procedure TMimeSourceFactory.AddPixmapToFactory(const Name: WideString;
Data: QPixmapH);
begin
QMimeSourceFactory_setPixmap(Handle, PWideString(@Name), Data);
end;
procedure TMimeSourceFactory.AddDataToFactory(const Name: WideString;
Data: QMimeSourceH);
begin
QMimeSourceFactory_setData(Handle, PWideString(@Name), Data);
end;
procedure TMimeSourceFactory.DestroyWidget;
begin
QMimeSourceFactory_destroy(FHandle);
end;
function TMimeSourceFactory.GetMimeSource(const MimeType: WideString): QMimeSourceH;
begin
Result := QMimeSourceFactory_data(Handle, PWideString(@MimeType));
end;
{ TDefaultFactory }
procedure TDefaultFactory.DestroyWidget;
begin
FHandle := nil;
end;
procedure TDefaultFactory.CreateHandle;
begin
FHandle := QMimeSourceFactory_defaultFactory;
end;
{ TCustomTextViewer }
procedure TCustomTextViewer.CopyToClipboard;
begin
QTextView_copy(Handle);
end;
constructor TCustomTextViewer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBrush := TBrush.Create;
FBrush.OnChange := PaperChanged;
InputKeys := [ikArrows, ikNav];
Width := 200;
Height := 150;
FLinkColor := clBlue;
FTextColor := clBlack;
FTextFormat := tfAutoText;
FUnderlineLink := True;
Color := clWhite;
BorderStyle := bsSunken3d;
end;
procedure TCustomTextViewer.CreateWidget;
begin
FHandle := QTextView_create(ParentWidget, PChar(Name));
Hooks := QTextView_hook_create(FHandle);
end;
destructor TCustomTextViewer.Destroy;
begin
FBrush.Free;
inherited Destroy;
end;
function TCustomTextViewer.GetBrush: TBrush;
var
Temp: QBrushH;
begin
if HandleAllocated then
begin
Temp := QTextView_paper(Handle);
if FBrush.Handle <> Temp then
FBrush.Handle := Temp;
end;
Result := FBrush;
end;
function TCustomTextViewer.GetDocumentTitle: WideString;
begin
if HandleAllocated then
QTextView_documentTitle(Handle, PWideString(@Result))
else
Result := '';
end;
function TCustomTextViewer.GetHandle: QTextViewH;
begin
HandleNeeded;
Result := QTextViewH(FHandle);
end;
function TCustomTextViewer.GetIsTextSelected: Boolean;
begin
if HandleAllocated then
Result := QTextView_hasSelectedText(Handle)
else
Result := False;
end;
function TCustomTextViewer.GetSelectedText: WideString;
begin
if HandleAllocated then
QTextView_selectedText(Handle, PWideString(@Result))
else
Result := '';
end;
function TCustomTextViewer.GetDocumentText: WideString;
begin
if HandleAllocated then
QTextView_text(Handle, PWideString(@Result))
else
Result := '';
end;
const
cQtTextFormat: array [TTextFormat] of Qt.TextFormat = (TextFormat_PlainText,
TextFormat_RichText, TextFormat_AutoText);
procedure TCustomTextViewer.LoadFromFile(const AFileName: string);
var
Stream: TStream;
begin
if AFileName = '' then
begin
Text := '';
FFileName := '';
Exit;
end;
Stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream);
FFileName := AFileName;
finally
Stream.Free;
end;
end;
procedure TCustomTextViewer.LoadFromStream(Stream: TStream);
var
Temp: string;
begin
if Stream.Size > 0 then
begin
Stream.Position := 0;
SetLength(Temp, Stream.Size);
Stream.Read(PChar(Temp)^, Length(Temp));
end
else
Temp := '';
Text := Temp;
end;
procedure TCustomTextViewer.SelectAll;
begin
if HandleAllocated then
QTextView_selectAll(Handle);
end;
procedure TCustomTextViewer.SetBrush(const Value: TBrush);
begin
if FBrush <> Value then
begin
FBrush.Handle := Value.Handle;
if HandleAllocated then
QTextView_setPaper(Handle, FBrush.Handle);
end;
end;
procedure TCustomTextViewer.SetLinkColor(const Value: TColor);
begin
if LinkColor <> Value then
begin
FLinkColor := Value;
if HandleAllocated then
begin
QTextView_setLinkColor(Handle, QColor(FLinkColor));
UpdateViewableContents;
end;
end;
end;
procedure TCustomTextViewer.SetDocumentText(const Value: WideString);
var
PaperRecall: TBrushRecall;
begin
PaperRecall := TBrushRecall.Create(Paper);
try
if HandleAllocated then
QTextView_setText(Handle, @Value);
SubmitTextColor;
finally
PaperRecall.Free;
end;
end;
procedure TCustomTextViewer.SetTextColor(const Value: TColor);
begin
if FTextColor <> Value then
begin
FTextColor := Value;
SubmitTextColor;
end;
end;
procedure TCustomTextViewer.SetTextFormat(const Value: TTextFormat);
begin
if TextFormat <> Value then
begin
FTextFormat := Value;
if HandleAllocated then
QTextView_setTextFormat(Handle, cQtTextFormat[FTextFormat]);
end;
end;
procedure TCustomTextViewer.SetUnderlineLink(const Value: Boolean);
begin
if UnderlineLink <> Value then
begin
FUnderlineLink := Value;
if HandleAllocated then
begin
QTextView_setLinkUnderline(Handle, FUnderlineLink);
UpdateViewableContents;
end;
end;
end;
function TCustomTextViewer.GetFactory: TMimeSourceFactory;
begin
if FUseDefaultFactory then
begin
Result := DefaultMimeFactory;
Exit;
end;
if FFactory = nil then
Factory := TMimeSourceFactory.Create;
Result := FFactory;
end;
procedure TCustomTextViewer.SetFactory(const Value: TMimeSourceFactory);
begin
if Value = nil then
UseDefaultFactory := True
else
begin
FFactory := Value;
FUseDefaultFactory := False;
QTextView_setMimeSourceFactory(Handle, FFactory.Handle);
end;
end;
procedure TCustomTextViewer.SetDefaultFactory(const Value: Boolean);
begin
if not FUseDefaultFactory and Assigned(FFactory) then
FreeAndNil(FFactory);
FUseDefaultFactory := Value;
QTextView_setMimeSourceFactory(Handle, DefaultMimeFactory.Handle);
end;
procedure TCustomTextViewer.WidgetDestroyed;
begin
QClxObjectMap_remove(FViewportHandle);
QClxObjectMap_remove(FVScrollHandle);
QClxObjectMap_remove(FHScrollHandle);
if Assigned(FViewportHook) then
begin
QWidget_hook_destroy(FViewportHook);
FViewportHook := nil;
end;
if Assigned(FVScrollHook) then
begin
QScrollbar_hook_destroy(FVScrollHook);
FVScrollHook := nil;
end;
if Assigned(FHScrollHook) then
begin
QScrollbar_hook_destroy(FHScrollHook);
FHScrollHook := nil;
end;
FViewportHandle := nil;
inherited WidgetDestroyed;
end;
function TCustomTextViewer.ViewportHandle: QWidgetH;
begin
HandleNeeded;
Result := FViewportHandle;
end;
function TCustomTextViewer.GetChildHandle: QWidgetH;
begin
Result := ViewportHandle;
end;
procedure TCustomTextViewer.InitWidget;
var
Method: TMethod;
begin
inherited InitWidget;
FViewportHandle := QScrollView_viewport(QScrollViewH(FHandle));
FVScrollHandle := QScrollView_verticalScrollBar(Handle);
FHScrollHandle := QScrollView_horizontalScrollBar(Handle);
QClxObjectMap_add(FViewportHandle, Integer(Self));
QClxObjectMap_add(FVScrollHandle, Integer(Self));
QClxObjectMap_add(FHScrollHandle, Integer(Self));
TEventFilterMethod(Method) := MainEventFilter;
FViewportHook := QWidget_hook_create(FViewportHandle);
Qt_hook_hook_events(FViewportHook, Method);
FVScrollHook := QScrollBar_hook_create(FVScrollHandle);
Qt_hook_hook_events(FVScrollHook, Method);
FHScrollHook := QScrollBar_hook_create(FHScrollHandle);
Qt_hook_hook_events(FHScrollHook, Method);
QWidget_setMouseTracking(FViewportHandle, True);
QWidget_setAcceptDrops(FViewportHandle, True);
SubmitTextColor;
QTextView_setLinkColor(Handle, QColor(FLinkColor));
QTextView_setTextFormat(Handle, cQtTextFormat[FTextFormat]);
QTextView_setLinkUnderline(Handle, FUnderlineLink);
end;
procedure TCustomTextViewer.PaperChanged(Sender: TObject);
begin
if HandleAllocated then
begin
QWidget_update(ViewportHandle);
Repaint;
end;
end;
procedure TCustomTextViewer.SubmitTextColor;
var
QC: QColorH;
begin
if HandleAllocated then
begin
QC := QColor_create(QColor(FTextColor));
try
QColorGroup_setColor(QTextView_paperColorGroup(Handle), QColorGroupColorRole(crText), QC);
UpdateViewableContents;
finally
QColor_destroy(QC);
end;
end;
end;
procedure TCustomTextViewer.SetFileName(const Value: TFileName);
begin
LoadFromFile(Value);
end;
procedure TCustomTextViewer.UpdateViewableContents;
begin
if HandleAllocated then
begin
QScrollView_updateContents(Handle, 0,0, QScrollView_visibleWidth(Handle),
QScrollView_visibleHeight(Handle));
end;
end;
{ TCustomTextBrowser }
procedure TCustomTextBrowser.Backward;
begin
if HandleAllocated then
QTextBrowser_backward(Handle);
end;
function TCustomTextBrowser.CanGoBackward: Boolean;
begin
Result := FBackwardAvailable;
end;
function TCustomTextBrowser.CanGoForward: Boolean;
begin
Result := FForwardAvailable;
end;
procedure TCustomTextBrowser.CreateWidget;
begin
FHandle := QTextBrowser_create(ParentWidget, nil);
Hooks := QTextBrowser_hook_create(FHandle);
end;
procedure TCustomTextBrowser.Forward;
begin
if HandleAllocated then
QTextBrowser_Forward(Handle);
end;
function TCustomTextBrowser.GetHandle: QTextBrowserH;
begin
HandleNeeded;
Result := QTextBrowserH(FHandle);
end;
procedure TCustomTextBrowser.Home;
begin
if HandleAllocated then
QTextBrowser_Home(Handle);
end;
procedure TCustomTextBrowser.HookBackwardAvailable(p1: Boolean);
begin
try
FBackwardAvailable := p1;
except
Application.HandleException(Self);
end;
end;
procedure TCustomTextBrowser.HookEvents;
var
Method: TMethod;
begin
inherited HookEvents;
QTextBrowser_backwardAvailable_Event(Method) := HookBackwardAvailable;
QTextBrowser_hook_hook_backwardAvailable(QTextBrowser_hookH(Hooks), Method);
QTextBrowser_forwardAvailable_Event(Method) := HookForwardAvailable;
QTextBrowser_hook_hook_forwardAvailable(QTextBrowser_hookH(Hooks), Method);
end;
procedure TCustomTextBrowser.HookForwardAvailable(p1: Boolean);
begin
try
FForwardAvailable := p1;
except
Application.HandleException(Self);
end;
end;
procedure TCustomTextBrowser.HookHighlightText(p1: PWideString);
begin
if Assigned(FRTBHighlightText) then
try
FRTBHighlightText(Self, p1^);
except
Application.HandleException(Self);
end;
end;
procedure TCustomTextBrowser.HookTextChanged;
begin
if Assigned(FTextChanged) then
try
FTextChanged(Self);
except
Application.HandleException(Self);
end;
end;
procedure TCustomTextBrowser.LoadFromFile(const AFileName: string);
var
WFileName: WideString;
begin
FFileName := AFileName;
if HandleAllocated then
begin
if FFileName = '' then
QTextView_setText(Handle, nil)
else
begin
WFileName := AFileName;
QTextBrowser_setSource(Handle, PWideString(@WFileName));
end;
end;
end;
procedure TCustomTextBrowser.ScrollToAnchor(const AnchorName: WideString);
begin
if HandleAllocated then
QTextBrowser_scrollToAnchor(Handle, PWideString(@AnchorName));
end;
procedure TCustomTextBrowser.SetDocumentText(const Value: WideString);
begin
QTextBrowser_setText(Handle, PWideString(@Value), nil);
SubmitTextColor;
end;
procedure TCustomTextBrowser.SetHighlightText(const Value: TRTBHighlightTextEvent);
var
Method: TMethod;
begin
FRTBHighlightText := Value;
if Assigned(FRTBHighlightText) then
QTextBrowser_highlighted_Event(Method) := HookHighlightText
else
Method := NullHook;
QTextBrowser_hook_hook_highlighted(QTextBrowser_hookH(Hooks), Method);
end;
procedure TCustomTextBrowser.SetTextChanged(const Value: TNotifyEvent);
var
Method: TMethod;
begin
FTextChanged := Value;
if Assigned(FTextChanged) then
QTextBrowser_textChanged_Event(Method) := HookTextChanged
else
Method := NullHook;
QTextBrowser_hook_hook_textChanged(QTextBrowser_hookH(Hooks), Method);
end;
procedure TCustomTextBrowser.WidgetDestroyed;
begin
QClxObjectMap_remove(FViewportHandle);
FViewportHandle := nil;
inherited WidgetDestroyed;
end;
{ TCustomIconView }
const
cIVQtSelect: array [Boolean] of QIconViewSelectionMode =
(QIconViewSelectionMode_Single, QIconViewSelectionMode_Extended);
cIVQtResizeMode: array [TResizeMode] of QIconViewResizeMode =
(QIconViewResizeMode_Fixed, QIconViewResizeMode_Adjust);
cIVResizeMode: array [Boolean] of TResizeMode = (rmAdjust, rmFixed);
cIVTextPos: array [Boolean] of TItemTextPos = (itpRight, itpBottom);
cIVQtTextPos: array [TItemTextPos] of QIconViewItemTextPos =
(QIconViewItemTextPos_Bottom, QIconViewItemTextPos_Right);
cIVQtArrangement: array [TIconArrangement] of QIconViewArrangement =
(QIconViewArrangement_TopToBottom, QIconViewArrangement_LeftToRight);
constructor TCustomIconView.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIconViewItems := TIconViewItems.Create(Self);
FIconOptions := TIconOptions.Create(Self);
FImageChanges := TChangeLink.Create;
FImageChanges.OnChange := OnImageChanges;
FItemsMovable := True;
FResizeMode := rmAdjust;
FShowToolTips := True;
FSpacing := 5;
FSortDirection := sdAscending;
ParentColor := False;
Width := 121;
Height := 97;
TabStop := True;
InputKeys := [ikArrows, ikReturns, ikNav];
BorderStyle := bsSunken3d;
end;
procedure TCustomIconView.BeginAutoDrag;
begin
BeginDrag(False, Mouse.DragThreshold);
end;
procedure TCustomIconView.ChangeHook(item: QIconViewItemH; _type: TItemChange);
var
AItem: TIconViewItem;
begin
try
AItem := Items.FindItem(item);
if Assigned(AItem) then
DoChange(AItem, _type);
except
Application.HandleException(Self);
end;
end;
procedure TCustomIconView.ChangingHook(item: QIconViewItemH; _type: TItemChange;
var Allow: Boolean);
var
AItem: TIconViewItem;
begin
try
AItem := Items.FindItem(item);
if Assigned(AItem) then
DoChanging(AItem, _type, Allow);
except
Application.HandleException(Self);
end;
end;
procedure TCustomIconView.ColorChanged;
begin
inherited ColorChanged;
UpdateControl;
end;
procedure TCustomIconView.CreateWidget;
begin
FHandle := QIconView_create(ParentWidget, nil, WidgetFlags);
Hooks := QIconView_hook_create(FHandle);
FItemHooks := QClxIconViewHooks_create;
FViewportHandle := QScrollView_viewport(QScrollViewH(FHandle));
QClxObjectMap_add(FViewportHandle, Integer(Self));
end;
destructor TCustomIconView.Destroy;
begin
FIconViewItems.Free;
FIconOptions.Free;
FImageChanges.Free;
inherited Destroy;
end;
procedure TCustomIconView.Clear;
begin
FIconViewItems.Clear;
end;
procedure TCustomIconView.DoChange(Item: TIconViewItem; Change: TItemChange);
begin
if Assigned(FOnItemChange) then
FOnItemChange(Self, Item, Change);
end;
procedure TCustomIconView.DoChanging(Item: TIconViewItem; Change: TItemChange;
var AllowChange: Boolean);
begin
if Assigned(FOnItemChanging) then
FOnItemChanging(Self, Item, Change, AllowChange);
end;
procedure TCustomIconView.DoItemDoubleClicked(item: QIconViewItemH);
begin
if Assigned(FOnItemDoubleClick) then
try
FOnItemDoubleClick(Self, Items.FindItem(item));
except
Application.HandleException(Self);
end;
end;
procedure TCustomIconView.DoItemEnter(item: QIconViewItemH);
begin
if Assigned(FOnItemEnter) then
try
FOnItemEnter(Self, Items.FindItem(item));
except
Application.HandleException(Self);
end;
end;
procedure TCustomIconView.DoEdited(item: QIconViewItemH; p2: PWideString);
var
AItem: TIconViewItem;
begin
if Assigned(FOnEdited) then
try
AItem := Items.FindItem(item);
if Assigned(AItem) then
FOnEdited(Self, AItem, p2^);
except
Application.HandleException(Self);
end;
end;
procedure TCustomIconView.DoItemClicked(item: QIconViewItemH);
var
AItem: TIconViewItem;
begin
if Assigned(FOnItemClicked) then
try
AItem := Items.FindItem(item);
if Assigned(AItem) then
FOnItemClicked(Self, AItem);
except
Application.HandleException(Self);
end;
end;
procedure TCustomIconView.DoViewportEnter;
begin
if Assigned(FOnItemExitViewportEnter) then
try
FOnItemExitViewportEnter(Self);
except
Application.HandleException(Self);
end;
end;
procedure TCustomIconView.EnsureItemVisible(AItem: TIconViewItem);
begin
if Assigned(AItem) and HandleAllocated then
QIconView_ensureItemVisible(Handle, AItem.Handle);
end;
function TCustomIconView.FindItemByPoint(const Pt: TPoint): TIconViewItem;
begin
if HandleAllocated then
Result := Items.FindItem(QIconView_findItem(Handle, PPoint(@Pt)))
else
Result := nil;
end;
function TCustomIconView.FindItemByText(const Str: WideString): TIconViewItem;
var
I: Integer;
begin
for I := 0 to Items.Count-1 do
begin
Result := Items[I];
if Result.Caption = Str then
Exit;
end;
Result := nil;
end;
function TCustomIconView.FindVisibleItem(First: Boolean;
const ARect: TRect): TIconViewItem;
begin
if HandleAllocated then
begin
if First then { find the first visible item }
Result := Items.FindItem(QIconView_findFirstVisibleItem(Handle, @ARect))
else { find the last visible item }
Result := Items.FindItem(QIconView_findLastVisibleItem(Handle, @ARect));
end
else
Result := nil;
end;
function TCustomIconView.GetHandle: QIconViewH;
begin
HandleNeeded;
Result := QIconViewH(FHandle);
end;
function TCustomIconView.GetNextItem(StartItem: TIconViewItem;
Direction: TSearchDirection; States: TItemStates): TIconViewItem;
var
AIndex: Integer;
begin
Result := nil;
if HandleAllocated and Assigned(StartItem) then
begin
if Direction = sdAbove then
Result := Items.FindItem(QIconViewItem_prevItem(StartItem.Handle))
else if Direction = sdBelow then
Result := Items.FindItem(QIconViewItem_nextItem(StartItem.Handle))
else
begin
AIndex := StartItem.Index;
while True do
begin
Inc(AIndex);
if AIndex < Items.Count then
begin
Result := Items[AIndex];
if Result = StartItem then
Result := nil;
if Result = nil then
Exit;
if (Result.States * States <> []) then
Exit;
end
else
begin
Result := nil;
Exit;
end;
end;
end;
end;
end;
type
TIconView_ChangingEvent = procedure(item: QIconViewItemH; _type: TItemChange;
var Allow: Boolean) of object cdecl;
TIconView_ChangeEvent = procedure(item: QIconViewItemH;
_type: TItemChange) of object cdecl;
TIconView_DestroyedEvent = procedure(item: QIconViewItemH) of object cdecl;
TIconView_SelectedEvent = procedure(item: QIconViewItemH;
Value: Boolean) of object cdecl;
TIconView_PaintCellEvent = procedure(p: QPainterH;
item: QIconViewItemH; cg: QColorGroupH; var stage: Integer) of object cdecl;
TIconView_PaintFocusEvent = procedure(p: QPainterH; item: QIconViewItemH;
cg: QColorGroupH; var stage: Integer) of object cdecl;
procedure TCustomIconView.HookEvents;
var
Method: TMethod;
begin
inherited HookEvents;
TEventFilterMethod(Method) := MainEventFilter;
FViewportHooks := QWidget_hook_create(FViewportHandle);
Qt_hook_hook_events(FViewportHooks, Method);
TIconView_ChangingEvent(Method) := ChangingHook;
QClxIconViewHooks_hook_changing(FItemHooks, Method);
TIconView_ChangeEvent(Method) := ChangeHook;
QClxIconViewHooks_hook_change(FItemHooks, Method);
TIconView_DestroyedEvent(Method) := ItemDestroyedHook;
QClxIconViewHooks_hook_destroyed(FItemHooks, Method);
TIconView_SelectedEvent(Method) := SelectedHook;
QClxIconViewHooks_hook_setSelected(FItemHooks, Method);
TIconView_PaintCellEvent(Method) := PaintCellHook;
QClxIconViewHooks_hook_PaintItem(FItemHooks, Method);
TIconView_PaintFocusEvent(Method) := PaintFocusHook;
QClxIconViewHooks_hook_PaintFocus(FItemHooks, Method);
end;
procedure TCustomIconView.ImageListChanged;
begin
FIconViewItems.UpdateImages;
end;
procedure TCustomIconView.ItemDestroyedHook(item: QIconViewItemH);
var
AItem: TIconViewItem;
begin
try
AItem := Items.FindItem(item);
if Assigned(Item) then
begin
QClxObjectMap_remove(item);
AItem.FHandle := nil;
if not AItem.FDestroying then
AItem.Free;
end;
except
Application.HandleException(Self);
end;
end;
procedure TCustomIconView.InitWidget;
begin
inherited InitWidget;
QIconView_setWordWrapIconText(Handle, IconOptions.WrapText);
QIconView_setItemsMovable(Handle, FItemsMovable);
QIconView_setSorting(Handle, FSort, FSortDirection = sdAscending);
QIconView_setShowToolTips(Handle, FShowToolTips);
QIconView_setAutoArrange(Handle, IconOptions.AutoArrange);
QIconView_setResizeMode(Handle, cIVQtResizeMode[FResizeMode]);
QIconView_setArrangement(Handle, cIVQtArrangement[IconOptions.Arrangement]);
QIconView_setItemTextPos(Handle, cIVQtTextPos[FTextPosition]);
QIconView_setSpacing(Handle, FSpacing);
QIconView_setGridX(Handle, -1);
QIconView_setGridY(Handle, -1);
QIconView_setSelectionMode(Handle, cIVQtSelect[FMultiSelect]);
QWidget_setMouseTracking(Handle, True);
QWidget_setAcceptDrops(Handle, True);
QWidget_setMouseTracking(FViewportHandle, True);
QWidget_setAcceptDrops(FViewportHandle, True);
end;
procedure TCustomIconView.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (AComponent = FImages) then
begin
if (Operation = opRemove) then
FImages := nil;
ImageListChanged;
end;
end;
procedure TCustomIconView.OnImageChanges(Sender: TObject);
begin
ImageListChanged;
end;
procedure TCustomIconView.PaintCellHook(p: QPainterH; item: QIconViewItemH;
cg: QColorGroupH; var stage: Integer);
begin
try
stage := DrawStage_DefaultDraw;
except
Application.HandleException(Self);
end;
end;
procedure TCustomIconView.PaintFocusHook(p: QPainterH; item: QIconViewItemH;
cg: QColorGroupH; var stage: Integer);
begin
try
stage := DrawStage_DefaultDraw;
except
Application.HandleException(Self);
end;
end;
procedure TCustomIconView.RepaintItem(AItem: TIconViewItem);
begin
if Assigned(AItem) and HandleAllocated then
QIconView_repaintItem(Handle, AItem.Handle);
end;
procedure TCustomIconView.SelectAll(Select: Boolean);
begin
if HandleAllocated then
QIconView_selectAll(Handle, Select);
end;
procedure TCustomIconView.SelectedHook(item: QIconViewItemH; Value: Boolean);
const
cIncSelCount: array [Boolean] of Integer = (-1, 1);
var
AItem: TIconViewItem;
begin
try
Inc(FSelCount, cIncSelCount[Value]);
if FSelCount < 0 then
FSelCount := 0;
AItem := Items.FindItem(item);
if FSelCount > 0 then
FSelected := AItem
else
FSelected := nil;
if Assigned(AItem) then
begin
if Value then
AItem.FStates := [isSelected, isFocused]
else
AItem.FStates := [isNone];
if Assigned(FOnSelectItem) then
FOnSelectItem(Self, AItem, AItem.Selected);
end;
except
Application.HandleException(Self);
end;
end;
procedure TCustomIconView.SetIconOptions(const Value: TIconOptions);
begin
if (FIconOptions <> Value) and Assigned(Value) then
begin
FIconOptions.Arrangement := Value.Arrangement;
FIconOptions.AutoArrange := Value.AutoArrange;
FIconOptions.WrapText := Value.WrapText;
end;
end;
procedure TCustomIconView.SetIconViewItems(const Value: TIconViewItems);
begin
if FIconViewItems <> Value then
FIconViewItems.Assign(Value);
end;
procedure TCustomIconView.SetImages(const Value: TCustomImageList);
begin
if Value <> FImages then
begin
if Assigned(FImages) then
FImages.UnRegisterChanges(FImageChanges);
FImages := Value;
if Assigned(FImages) then
FImages.RegisterChanges(FImageChanges);
ImageListChanged;
end;
end;
procedure TCustomIconView.SetItemsMovable(const Value: Boolean);
begin
if FItemsMovable <> Value then
begin
FItemsMovable := Value;
if HandleAllocated then
QIconView_setItemsMovable(Handle, FItemsMovable);
end;
end;
procedure TCustomIconView.SetMultiSelect(const Value: Boolean);
begin
if (FMultiSelect <> Value) then
begin
FMultiSelect := Value;
if HandleAllocated then
QIconView_setSelectionMode(Handle, cIVQtSelect[FMultiSelect]);
end;
end;
procedure TCustomIconView.SetOnItemClicked(const Value: TIVItemClickEvent);
var
Method: TMethod;
begin
FOnItemClicked := Value;
if Assigned(FOnItemClicked) then
QIconView_clicked_Event(Method) := DoItemClicked
else
Method := NullHook;
QIconView_hook_hook_clicked(QIconView_hookH(Hooks), Method);
end;
procedure TCustomIconView.SetOnItemDoubleClick(const Value: TIVItemDoubleClickEvent);
var
Method: TMethod;
begin
FOnItemDoubleClick := Value;
if Assigned(FOnItemDoubleClick) then
QIconView_doubleClicked_Event(Method) := DoItemDoubleClicked
else
Method := NullHook;
QIconView_hook_hook_doubleClicked(QIconView_hookH(Hooks), Method);
end;
procedure TCustomIconView.SetOnItemEnter(const Value: TIVItemEnterEvent);
var
Method: TMethod;
begin
FOnItemEnter := Value;
if Assigned(FOnItemEnter) then
QIconView_onItem_Event(Method) := DoItemEnter
else
Method := NullHook;
QIconView_hook_hook_onItem(QIconView_hookH(Hooks), Method);
end;
procedure TCustomIconView.SetOnItemExitViewportEnter(const Value: TIVItemExitViewportEnterEvent);
var
Method: TMethod;
begin
FOnItemExitViewportEnter := Value;
if Assigned(FOnItemExitViewportEnter) then
QIconView_onViewport_Event(Method) := DoViewportEnter
else
Method := NullHook;
QIconView_hook_hook_onItem(QIconView_hookH(Hooks), Method);
end;
procedure TCustomIconView.SetOnEdited(const Value: TIVEditedEvent);
var
Method: TMethod;
begin
FOnEdited := Value;
if Assigned(FOnEdited) then
QIconView_itemRenamed_Event(Method) := DoEdited
else
Method := NullHook;
QIconView_hook_hook_itemRenamed(QIconView_hookH(Hooks), Method);
end;
procedure TCustomIconView.SetResizeMode(const Value: TResizeMode);
begin
if (FResizeMode <> Value) then
begin
FResizeMode := Value;
if HandleAllocated then
QIconView_setResizeMode(Handle, cIVQtResizeMode[FResizeMode]);
end;
end;
procedure TCustomIconView.SetSelected(const Value: TIconViewItem);
begin
if not (csDestroying in ComponentState) then
if Assigned(Value) then
Value.Selected := True;
FSelected := Value;
end;
procedure TCustomIconView.SetShowToolTips(const Value: Boolean);
begin
if (FShowToolTips <> Value) then
begin
FShowToolTips := Value;
if HandleAllocated then
QIconView_setShowToolTips(Handle, FShowToolTips);
end;
end;
procedure TCustomIconView.SetSort(const Value: Boolean);
begin
if FSort <> Value then
begin
FSort := Value;
if HandleAllocated then
begin
QIconView_setSorting(Handle, FSort, FSortDirection = sdAscending);
if FSort then
QIconView_sort(Handle, FSortDirection = sdAscending);
end;
end;
end;
procedure TCustomIconView.SetSortDirection(const Value: TSortDirection);
begin
if FSortDirection <> Value then
begin
FSortDirection := Value;
if Sort then
begin
if HandleAllocated then
QIconView_sort(Handle, FSortDirection = sdAscending);
end
else
Sort := True;
end;
end;
procedure TCustomIconView.SetSpacing(const Value: Integer);
begin
if (FSpacing <> Value) then
begin
FSpacing := Value;
if HandleAllocated then
QIconView_setSpacing(Handle, FSpacing);
end;
end;
procedure TCustomIconView.SetTextPos(const Value: TItemTextPos);
begin
if (FTextPosition <> Value) then
begin
FTextPosition := Value;
if HandleAllocated then
QIconView_setItemTextPos(Handle, cIVQtTextPos[FTextPosition]);
end;
end;
function TCustomIconView.ViewportHandle: QWidgetH;
begin
HandleNeeded;
Result := FViewportHandle;
end;
procedure TCustomIconView.WidgetDestroyed;
begin
QClxIconViewHooks_hook_destroyed(FItemHooks, NullHook);
QClxIconViewHooks_destroy(FItemHooks);
FItemHooks := nil;
QClxObjectMap_remove(FViewportHandle);
FViewportHandle := nil;
inherited WidgetDestroyed;
end;
procedure TCustomIconView.UpdateItems(FirstIndex, LastIndex: Integer);
var
I: Integer;
begin
if HandleAllocated then
begin
Items.BeginUpdate;
try
for I := FirstIndex to LastIndex do
QIconViewItem_repaint(Items[I].Handle);
finally
Items.EndUpdate;
end;
end;
end;
procedure TCustomIconView.UpdateControl;
begin
if HandleAllocated then
QIconView_updateContents(Handle);
end;
{ TIconViewItems }
constructor TIconViewItems.Create(AOwner: TCustomIconView);
begin
inherited Create;
FOwner := AOwner;
FItems := TObjectList.Create;
SetItemClass(TIconViewItem);
end;
constructor TIconViewItems.Create(AOwner: TCustomIconView;
AItemClass: TIconViewItemClass);
begin
inherited Create;
FOwner := AOwner;
FItems := TObjectList.Create;
SetItemClass(AItemClass);
end;
destructor TIconViewItems.Destroy;
begin
FItems.Free;
inherited Destroy;
end;
type
PIconItemHeader = ^TIconItemHeader;
TIconItemHeader = packed record
Size: Integer;
Count: Integer;
Items: record end;
end;
PIconItemInfo = ^TIconItemInfo;
TIconItemInfo = packed record
ImageIndex: Integer;
Caption: string[255];
end;
function TIconViewItems.Add: TIconViewItem;
begin
BeginUpdate;
try
Result := TIconViewItem.Create(Self);
FItems.Add(Result);
finally
EndUpdate;
end;
end;
procedure TIconViewItems.BeginUpdate;
begin
if FUpdateCount = 0 then
SetUpdateState(True);
Inc(FUpdateCount);
end;
procedure TIconViewItems.Clear;
begin
FItems.Clear;
end;
procedure TIconViewItems.DefineProperties(Filer: TFiler);
function WriteItems: Boolean;
var
I: Integer;
Items: TIconViewItems;
begin
Items := TIconViewItems(Filer.Ancestor);
if (Items = nil) then
Result := Count > 0
else if (Items.Count <> Count) then
Result := True
else
begin
Result := False;
for I := 0 to Count - 1 do
begin
Result := not Item[I].IsEqual(Items[I]);
if Result then Break;
end
end;
end;
begin
inherited DefineProperties(Filer);
Filer.DefineBinaryProperty('Data', ReadData, WriteData, WriteItems);
end;
procedure TIconViewItems.Delete(Index: Integer);
begin
FItems.Delete(Index);
end;
procedure TIconViewItems.EndUpdate;
begin
Dec(FUpdateCount);
if FUpdateCount = 0 then
SetUpdateState(False);
end;
procedure TIconViewItems.ReadData(Stream: TStream);
var
I, Size: Integer;
ItemHeader: PIconItemHeader;
ItemInfo: PIconItemInfo;
begin
Clear;
Stream.ReadBuffer(Size, SizeOf(Integer));
ItemHeader := AllocMem(Size);
try
Stream.ReadBuffer(ItemHeader^.Count, Size - SizeOf(Integer));
ItemInfo := @ItemHeader^.Items;
for I := 0 to ItemHeader^.Count - 1 do
begin
with Add do
begin
Caption := ItemInfo^.Caption;
ImageIndex := ItemInfo^.ImageIndex;
end;
Inc(Integer(ItemInfo), SizeOf(TIconItemInfo) - 255 +
Length(ItemInfo.Caption));
end;
finally
FreeMem(ItemHeader, Size);
end;
end;
procedure TIconViewItems.WriteData(Stream: TStream);
var
I, Size, L: Integer;
ItemHeader: PIconItemHeader;
ItemInfo: PIconItemInfo;
PStr: PShortStr;
function GetLength(const S: string): Integer;
begin
Result := Length(S);
if Result > 255 then Result := 255;
end;
begin
Size := SizeOf(TIconItemHeader);
for I := 0 to Count - 1 do
begin
L := GetLength(Item[I].Caption);
Inc(Size, SizeOf(TIconItemInfo) - 255 + L);
end;
ItemHeader := AllocMem(Size);
try
ItemHeader^.Size := Size;
ItemHeader^.Count := Count;
ItemInfo := @ItemHeader^.Items;
for I := 0 to Count - 1 do
begin
with Item[I] do
begin
ItemInfo^.Caption := Caption;
ItemInfo^.ImageIndex := ImageIndex;
PStr := @ItemInfo^.Caption;
Inc(Integer(PStr), Length(ItemInfo^.Caption) + 1);
end;
Inc(Integer(ItemInfo), SizeOf(TIconItemInfo) - 255 +
Length(ItemInfo^.Caption));
end;
Stream.WriteBuffer(ItemHeader^, Size);
finally
FreeMem(ItemHeader, Size);
end;
end;
function TIconViewItems.FindItem(ItemH: QIconViewItemH): TIconViewItem;
var
I: Integer;
begin
Result := nil;
if not Assigned(ItemH) then
Exit;
Result := TIconViewItem(QClxObjectMap_find(ItemH));
if Result is TIconViewItem then
Exit;
for I := 0 to Count-1 do
begin
Result := Item[I];
if Result.Handle = ItemH then
Exit;
end;
Result := nil;
end;
function TIconViewItems.GetCount: Integer;
begin
Result := FItems.Count;
end;
function TIconViewItems.GetItem(Index: Integer): TIconViewItem;
begin
Result := TIconViewItem(FItems[Index]);
end;
function TIconViewItems.IndexOf(Value: TIconViewItem): Integer;
begin
Result := FItems.IndexOf(Value);
end;
function TIconViewItems.Insert(Index: Integer): TIconViewItem;
begin
Result := Add;
FItems.Move(Result.Index, Index);
end;
function TIconViewItems.IconViewHandle: QIconViewH;
begin
if Assigned(FOwner) then
Result := FOwner.Handle
else
Result := nil;
end;
procedure TIconViewItems.SetItem(Index: Integer; AObject: TIconViewItem);
begin
FItems[Index] := AObject;
end;
procedure TIconViewItems.SetItemClass(AItemClass: TIconViewItemClass);
begin
FIconViewItemClass := AItemClass;
end;
procedure TIconViewItems.SetUpdateState(Updating: Boolean);
begin
if not (csDestroying in Owner.ComponentState) and Owner.HandleAllocated then
begin
if (FUpdateCount = 0) then
begin
QWidget_setUpdatesEnabled(IconViewHandle, not Updating);
QWidget_setUpdatesEnabled(QScrollView_viewport(IconViewHandle), not Updating);
if not Updating then
QIconView_updateContents(IconViewHandle);
end;
end;
end;
procedure TIconViewItems.UpdateImages;
var
I: Integer;
begin
for I := 0 to Count-1 do
Item[I].UpdateImage;
end;
{ TIconViewItem }
constructor TIconViewItem.Create(AOwner: TIconViewItems; AfterItem: TIconViewItem = nil);
begin
inherited Create;
FOwner := AOwner;
FImageIndex := -1;
FAllowRename := True;
FSelectable := True;
States := [isNone];
CreateWidget(AfterItem);
end;
procedure TIconViewItem.CreateWidget(AfterItem: TIconViewItem);
var
AfterH: QIconViewItemH;
ParentH: QIconViewH;
begin
if IconViewValid then
begin
IconView.HandleNeeded;
if Assigned(AfterItem) then
AfterH := AfterItem.Handle
else
AfterH := nil;
ParentH := IconView.Handle;
FHandle := QClxIconViewItem_create(ParentH, AfterH, IconView.FItemHooks);
QClxObjectMap_add(FHandle, Integer(Self));
InitWidget;
end;
end;
destructor TIconViewItem.Destroy;
begin
FDestroying := True;
if Assigned(FOwner) then
FOwner.FItems.Extract(Self);
if IconViewValid then
if IconView.FSelected = Self then
IconView.FSelected := nil;
DestroyWidget;
inherited Destroy;
end;
procedure TIconViewItem.DestroyWidget;
begin
if HandleAllocated then
QIconViewItem_destroy(FHandle);
end;
function TIconViewItem.HandleAllocated: Boolean;
begin
Result := FHandle <> nil;
end;
procedure TIconViewItem.InitWidget;
begin
QIconViewItem_setDragEnabled(Handle, False);
QIconViewItem_setDropEnabled(Handle, True);
QIconViewItem_setRenameEnabled(Handle, FAllowRename);
QIconViewItem_setText(Handle, @FCaption);
QIconViewItem_setSelectable(Handle, FSelectable);
if Assigned(FOwner) and (FOwner.FUpdateCount = 0) then
QIconView_ensureItemVisible(IconView.Handle, Handle);
end;
function TIconViewItem.IsEqual(AItem: TIconViewItem): Boolean;
begin
if Assigned(AItem) then
Result := (Caption = AItem.Caption) and (ImageIndex = AItem.ImageIndex)
else
Result := False;
end;
function TIconViewItem.BoundingRect: TRect;
begin
if HandleAllocated then
QIconViewItem_rect(Handle, @Result)
else
Result := Rect(-1, -1, -1, -1);
end;
function TIconViewItem.GetHandle: QIconViewItemH;
begin
Result := FHandle;
end;
function TIconViewItem.GetHeight: Integer;
begin
if HandleAllocated then
Result := QIconViewItem_height(Handle)
else
Result := -1;
end;
function TIconViewItem.GetIconView: TCustomIconView;
begin
if FOwner.FOwner is TCustomIconView then
Result := TCustomIconView(FOwner.FOwner)
else
Result := nil;
end;
function TIconViewItem.GetIndex;
begin
Result := FOwner.IndexOf(Self);
end;
function TIconViewItem.GetLeft: Integer;
begin
if HandleAllocated then
Result := QIconViewItem_x(Handle)
else
Result := -1;
end;
function TIconViewItem.GetSelected: Boolean;
begin
if HandleAllocated then
Result := QIconViewItem_isSelected(Handle)
else
Result := False;
end;
function TIconViewItem.GetTop: Integer;
begin
if HandleAllocated then
Result := QIconViewItem_y(Handle)
else
Result := -1;
end;
function TIconViewItem.GetWidth: Integer;
begin
if HandleAllocated then
Result := QIconViewItem_width(Handle)
else
Result := -1;
end;
function TIconViewItem.IconRect: TRect;
begin
if HandleAllocated then
QIconViewItem_pixmapRect(Handle, @Result, False)
else
Result := Rect(-1, -1, -1, -1);
end;
function TIconViewItem.IconViewValid: Boolean;
begin
Result := Assigned(FOwner) and Assigned(FOwner.FOwner);
end;
procedure TIconViewItem.MakeVisible;
begin
if HandleAllocated then
QIconView_ensureItemVisible(IconView.Handle, Handle);
end;
procedure TIconViewItem.Move(const Pt: TPoint);
begin
if HandleAllocated then
begin
QIconViewItem_move(Handle, @Pt);
if IconViewValid then
IconView.UpdateControl;
end;
end;
procedure TIconViewItem.MoveBy(const Pt: TPoint);
begin
if HandleAllocated then
begin
QIconViewItem_moveBy(Handle, @Pt);
if IconViewValid then
IconView.UpdateControl;
end;
end;
procedure TIconViewItem.Repaint;
begin
if HandleAllocated then
QIconViewItem_repaint(Handle);
end;
procedure TIconViewItem.SetAllowRename(const Value: Boolean);
begin
if (FAllowRename <> Value) then
begin
FAllowRename := Value;
if HandleAllocated then
QIconViewItem_setRenameEnabled(Handle, FAllowRename);
end;
end;
procedure TIconViewItem.SetCaption(const Value: WideString);
begin
FCaption := Value;
if HandleAllocated then
QIconViewItem_setText(Handle, @FCaption);
end;
procedure TIconViewItem.SetImageIndex(const Value: TImageIndex);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
UpdateImage;
end;
end;
procedure TIconViewItem.SetSelectable(const Value: Boolean);
begin
if (FSelectable <> Value) then
begin
FSelectable := Value;
if HandleAllocated then
QIconViewItem_setSelectable(Handle, FSelectable);
end;
end;
procedure TIconViewItem.SetSelected(const Value: Boolean);
begin
if (Selected <> Value) and HandleAllocated then
QIconViewItem_setSelected(Handle, Value, True);
end;
procedure TIconViewItem.SetStates(const Value: TItemStates);
begin
if FStates <> Value then
begin
FStates := Value;
if not (isNone in FStates) then
begin
Selected := True;
FStates := FStates - [isNone];
end
else
begin
Selected := False;
FStates := [isNone];
end;
end;
end;
function TIconViewItem.TextRect: TRect;
begin
if HandleAllocated then
QIconViewItem_textRect(Handle, @Result, False)
else
Result := Rect(-1, -1, -1, -1);
end;
procedure TIconViewItem.UpdateImage;
var
Imgs: TCustomImageList;
EmptyPix: QPixmapH;
Pixmap: QPixmapH;
begin
if IconViewValid and FOwner.FOwner.HandleAllocated then
begin
EmptyPix := QPixmap_create;
try
Imgs := FOwner.FOwner.FImages;
if Assigned(Imgs) then
begin
Pixmap := Imgs.GetPixmap(FImageIndex);
if Assigned(Pixmap) then
QIconViewItem_setPixmap(Handle, Pixmap)
else
QIconViewItem_setPixmap(Handle, EmptyPix);
end
else
QIconViewItem_setPixmap(Handle, EmptyPix);
finally
QPixmap_destroy(EmptyPix);
end;
end;
end;
{ TToolButton }
const
TBSpacing = 3;
constructor TToolButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csCaptureMouse, csSetCaption, csClickEvents];
FWidth := 23;
FHeight := 22;
FImageIndex := -1;
FDown := False;
FGrouped := False;
FStyle := tbsButton;
FAutoSize := False;
FAllowAllUp := False;
FIndeterminate := False;
FMarked := False;
FWrap := False;
end;
procedure TToolButton.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
PopupPt: TPoint;
begin
if (Style in [tbsDropDown, tbsButton, tbsCheck]) and (Button = mbLeft) and IsEnabled then
begin
if Down and Grouped and not AllowAllUp then
ControlState := ControlState - [csClicked];
FJustChecked := (Style = tbsCheck) and not Down;
Down := True;
if (Style = tbsDropDown) then
begin
if FMenuDropped then
begin
if Assigned(FDropDownMenu) then
QWidget_hide(FDropDownMenu.Handle);
FMenuDropped := False;
Down := False;
end else
begin
if PtInRect(DropDownRect, Types.Point(X, Y)) then
begin
PopupPt := ClientToScreen(Types.Point(0, Height));
FMenuDropped := True;
try
if Assigned(FDropDownMenu) then
QPopupMenu_exec(FDropDownMenu.Handle, @PopupPt, 0);
finally
FMenuDropped := False;
Down := False;
if GetMouseGrabControl = Self then
SetMouseGrabControl(nil);
end;
Exit;
end;
end;
end;
end;
inherited MouseDown(Button, Shift, X, Y);
end;
procedure TToolButton.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited MouseMove(Shift, X, Y);
if (Style = tbsDropDown) and MouseCapture then
Down := (X >= 0) and (X < ClientWidth) and (Y >= 0) and (Y <= ClientHeight);
end;
procedure TToolButton.Click;
begin
if not (Style in [tbsSeparator, tbsDivider]) then
inherited Click;
end;
procedure TToolButton.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
begin
if AComponent = DropDownMenu then
DropDownMenu := nil;
end;
end;
procedure TToolButton.ChangeBounds(ALeft, ATop, AWidth, AHeight: Integer);
var
ResizeWidth,
ResizeHeight: Boolean;
NeedsUpdate: Boolean;
begin
if ((AWidth <> Width) or (AHeight <> Height)) and
(FToolBar <> nil) and (FToolBar.FResizeCount = 0)
and not (csLoading in ComponentState) then
begin
NeedsUpdate := (Style in [tbsSeparator, tbsDivider]) and (AWidth <> Width) and
not FToolBar.ShowCaptions;
if Style = tbsDropDown then
AWidth := FToolBar.ButtonWidth + AWidth - Width;
ResizeWidth := not (Style in [tbsSeparator, tbsDivider]) and
(AWidth <> FToolBar.ButtonWidth);
ResizeHeight := AHeight <> FToolBar.ButtonHeight;
if NeedsUpdate then inherited ChangeBounds(ALeft, ATop, AWidth, AHeight);
if csDesigning in ComponentState then
begin
if ResizeWidth then FToolBar.ButtonWidth := AWidth;
if ResizeHeight then FToolBar.ButtonHeight := AHeight;
end;
end else
inherited ChangeBounds(ALeft, ATop, AWidth, AHeight);
end;
procedure TToolButton.Paint;
begin
DoPaint(Canvas);
end;
procedure TToolButton.DoPaint(Canvas: TCanvas);
function CaptionRect(var R: TRect): TRect;
begin
{ R -> image rect. Result -> Text rect. }
R.Right := R.Right - DropDownWidth;
Result := R;
if FToolBar.HasImages then
begin
if FToolBar.List then
begin
R.Left := R.Left + TBSpacing;
R.Right := R.Left + FToolBar.FImageWidth;
R.Top := ((R.Bottom - R.Top) div 2) - (FToolBar.FImageHeight div 2);
R.Bottom := R.Top + FToolBar.FImageHeight;
Result.Left := R.Right;
end
else begin
R.Left := ((R.Right - R.Left) div 2) - (FToolBar.FImageWidth div 2);
R.Top := R.Top + TBSpacing;
R.Right := R.Left + FToolBar.FImageWidth;
R.Bottom := R.Top + FToolBar.FImageHeight;
end;
end;
if FToolBar.List then
Result.Top := Result.Top + TBSpacing
else if FToolBar.HasImages then
Result.Top := R.Bottom + TBSpacing
else
Result.Top := R.Top + TBSpacing;
Result.Left := Result.Left + TBSpacing;
Result.Right := Result.Right - TBSpacing;
Result.Bottom := Result.Bottom - TBSpacing;
end;
procedure DrawDropDown;
var
R: TRect;
MidX,
MidY: Integer;
Pts: array of TPoint;
begin
R := DropDownRect;
if Down and not FMenuDropped then
OffsetRect(R, 2, 2);
Canvas.Pen.Color := clButtonText;
Canvas.Brush.Color := clButtonText;
MidX := R.Left + (R.Right - R.Left) div 2;
MidY := R.Top + (R.Bottom - R.Top) div 2;
if FMenuDropped then
begin
MidX := MidX + 1;
MidY := MidY + 1;
end;
SetLength(Pts, 4);
Pts[0] := Types.Point(MidX - 2, MidY - 1);
Pts[1] := Types.Point(MidX + 2, MidY - 1);
Pts[2] := Types.Point(MidX, MidY + 1);
Pts[3] := Pts[0];
Canvas.Polygon(Pts);
if FMenuDropped then
begin
if FToolBar.Flat then
begin
Dec(R.Top);
Inc(R.Bottom);
DrawEdge(Canvas, R, esNone, esLowered, ebRect);
end
else begin
Dec(R.Top, 1);
Inc(R.Bottom);
DrawEdge(Canvas, R, esLowered, esLowered, ebRect);
end
end else
if not FToolBar.Flat or (FToolBar.Flat and FMouseIn) then
DrawEdge(Canvas, R, esRaised, esLowered, [ebLeft]);
end;
var
R: TRect;
CR: TRect;
DrawFlags: Integer;
TBColor: TColor;
BrushColor,
PenColor,
PatternColor: TColor;
BrushStyle: TBrushStyle;
PenStyle: TPenStyle;
Ind: Boolean;
begin
if FToolBar = nil then Exit;
BrushStyle := Canvas.Brush.Style;
PenStyle := Canvas.Pen.Style;
BrushColor := Canvas.Brush.Color;
PenColor := Canvas.Pen.Color;
Ind := FIndeterminate and not Down;
if Ind then
PatternColor := clBtnHighlight
else
PatternColor := clHighlight;
try
if FToolBar.Flat then
TBColor := FToolBar.Color
else
TBColor := clBtnFace;
if Style in [tbsDropDown, tbsButton, tbsCheck] then
begin
DrawFlags := Integer(AlignmentFlags_ShowPrefix) or Integer(AlignmentFlags_AlignVCenter);
if FToolBar.List then
DrawFlags := DrawFlags or Integer(AlignmentFlags_AlignLeft)
else
DrawFlags := DrawFlags or Integer(AlignmentFlags_AlignHCenter);
R := Types.Rect(0, 0, Width, Height);
Canvas.Brush.Color := TBColor;
if ((Down and (Style = tbsCheck)) or Ind or Marked) and IsEnabled then
begin
Canvas.TiledDraw(Rect(R.Left, R.Top, R.Right - DropDownWidth, R.Bottom),
AllocPatternBitmap(clBtnFace, PatternColor));
Canvas.FillRect(Rect(R.Right - DropDownWidth, R.Top, R.Right, R.Bottom));
end
else begin
Canvas.Brush.Color := TBColor;
Canvas.FillRect(R);
end;
if not FToolBar.Flat then
begin
DrawButtonFace(Canvas, R, 1, Down and not FMenuDropped, False,
False, clNone);
if Style = tbsDropDown then DrawDropDown;
end
else begin
if not Down or FMenuDropped then
begin
if ((FMouseIn or FMenuDropped) and IsEnabled)
or (csDesigning in ComponentState) then
DrawEdge(Canvas, R, esNone, esRaised, [ebTop, ebLeft, ebRight, ebBottom])
else if not (Ind or Marked) or not IsEnabled then
begin
Canvas.Brush.Color := TBColor;
Canvas.FillRect(R);
end;
end
else
if not FMenuDropped then
DrawEdge(Canvas, R, esNone, esLowered, [ebTop, ebLeft, ebRight, ebBottom]);
if Style = tbsDropDown then DrawDropDown;
end;
R := ClientRect;
CR := CaptionRect(R);
if Down and not FMenuDropped then
begin
OffsetRect(R, 2, 2);
OffsetRect(CR, 2, 2);
end;
//draw image
Canvas.Brush.Style := bsSolid;
if (FImageIndex > -1) and FToolBar.HasImages then
begin
Canvas.Brush.Color := TBColor;
if not (Ind or Marked) or not IsEnabled then Canvas.FillRect(R);
if Assigned(FToolBar.HotImages) and (FMouseIn or FMenuDropped) and IsEnabled
and (FImageIndex < FToolBar.HotImages.Count) then
FToolbar.HotImages.Draw(Canvas, R.Left, R.Top, FImageIndex, itImage, not Ind)
else if Assigned(FToolBar.DisabledImages) and not IsEnabled and
(FImageIndex < FToolBar.DisabledImages.Count) then
FToolbar.DisabledImages.Draw(Canvas, R.Left, R.Top, FImageIndex,
itImage, not Ind)
else if Assigned(FToolBar.Images) and
(FImageIndex < FToolBar.Images.Count) then
FToolBar.Images.Draw(Canvas, R.Left, R.Top, FImageIndex, itImage,
IsEnabled and not Ind);
end;
{ draw caption }
if (FCaption <> '') and FToolBar.FShowCaptions then
begin
Canvas.Font := FToolBar.Font;
if not IsEnabled then
Canvas.Font.Color := clDisabledText;
Canvas.TextRect(CR, CR.Left, CR.Top, FCaption, DrawFlags);
end;
end;
if (Style = tbsSeparator) and FToolBar.Flat then
begin
R := Types.Rect(Width div 2, 3, Width, Height - 3);
DrawEdge(Canvas, R, esRaised, esLowered, [ebLeft]);
end;
if Style = tbsDivider then
begin
R := Types.Rect(Width div 2, 1, Width, Height - 2);
DrawEdge(Canvas, R, esRaised, esLowered, [ebLeft]);
end;
if (Style in [tbsSeparator, tbsDivider]) and (csDesigning in ComponentState) then
begin
Canvas.Pen.Style := psDot;
Canvas.Pen.Color := clBlack;
Canvas.Brush.Style := bsClear;
Canvas.Rectangle(ClientRect);
end;
finally
Canvas.Brush.Style := BrushStyle;
Canvas.Pen.Style := PenStyle;
Canvas.Brush.Color := BrushColor;
Canvas.Pen.Color := PenColor;
end;
end;
procedure TToolButton.SetAutoSize(Value: Boolean);
begin
if Value <> AutoSize then
begin
FAutoSize := Value;
if not (csLoading in ComponentState) and (FToolBar <> nil) and
FToolBar.ShowCaptions then
begin
FToolBar.ResizeButtons(Self);
end;
end;
end;
procedure TToolButton.SetName(const Value: TComponentName);
var
ChangeText: Boolean;
begin
ChangeText := Name = Caption;
inherited SetName(Value);
if ChangeText then Caption := Value;
end;
procedure TToolButton.SetParent(const Value: TWidgetControl);
begin
inherited SetParent(Value);
if Value is TToolBar then FToolBar := TToolBar(Value);
end;
procedure TToolButton.SetToolBar(AToolBar: TToolBar);
begin
if FToolBar <> AToolBar then
begin
FToolBar := AToolBar;
Parent := FToolBar;
FToolBar.ResizeButtons(Self);
end;
end;
procedure TToolButton.SetDown(Value: Boolean);
begin
if Value <> FDown then
begin
FDown := Value;
Invalidate;
if FToolBar <> nil then
begin
if Grouped and (Style = tbsCheck) and (FToolBar <> nil) then
FToolBar.GroupChange(Self, gcDownState);
end;
end;
end;
procedure TToolButton.SetDropDownMenu(Value: TPopupMenu);
begin
if Value <> FDropDownMenu then
begin
FDropDownMenu := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
end;
procedure TToolButton.SetGrouped(Value: Boolean);
begin
if FGrouped <> Value then
begin
FGrouped := Value;
end;
end;
procedure TToolButton.SetImageIndex(Value: TImageIndex);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
Invalidate;
end;
end;
procedure TToolButton.SetMarked(Value: Boolean);
begin
if FMarked <> Value then
begin
FMarked := Value;
Invalidate;
end;
end;
procedure TToolButton.SetIndeterminate(Value: Boolean);
begin
if FIndeterminate <> Value then
begin
if Value then SetDown(False);
FIndeterminate := Value;
Invalidate;
end;
end;
procedure TToolButton.SetStyle(Value: TToolButtonStyle);
var
ResizeNeeded: Boolean;
begin
if FStyle <> Value then
begin
ResizeNeeded := (Value = tbsDropDown) or
(Style in [tbsDropDown, tbsSeparator, tbsDivider]);
FStyle := Value;
if not (csLoading in ComponentState) and (FToolBar <> nil) then
begin
if FToolBar.ShowCaptions then
begin
// FToolBar.FButtonWidth := 0;
// FToolBar.FButtonHeight := 0;
FToolBar.ResizeButtons(nil);
end;
if ResizeNeeded then
FToolBar.ResizeButtons(Self);
end;
// if Style in [tbsSeparator, tbsDivider] then
// Wrap := True;
if ResizeNeeded then
FToolBar.Realign
else
Invalidate;
end;
end;
procedure TToolButton.SetWrap(Value: Boolean);
begin
if FWrap <> Value then
begin
FWrap := Value;
if FToolBar <> nil then
FToolBar.Realign;
end;
end;
procedure TToolButton.BeginUpdate;
begin
Inc(FUpdateCount);
end;
function TToolButton.DropDownWidth: Integer;
begin
if Style = tbsDropDown then
Result := 14
else
Result := 0;
end;
procedure TToolButton.EndUpdate;
begin
Dec(FUpdateCount);
end;
function TToolButton.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
if QEvent_type(Event) = QEventType_MouseButtonRelease then
begin
if (Style in [tbsDropDown, tbsButton])
and (QMouseEvent_button(QMouseEventH(Event)) = ButtonState_LeftButton) and IsEnabled then
Down := False;
if (Style = tbsCheck) and not FJustChecked and (not Grouped or AllowAllUp) then
Down := False;
FJustChecked := False;
end;
Result := inherited EventFilter(Sender, Event);
end;
procedure TToolButton.InitWidget;
begin
QWidget_setFocusPolicy(Handle, QWidgetFocusPolicy_NoFocus);
end;
function TToolButton.IsEnabled: Boolean;
begin
Result := Enabled;
if FToolBar <> nil then Result := Result and FToolBar.Enabled;
end;
function TToolButton.GetIndex: Integer;
begin
Result := -1;
if FToolBar <> nil then
Result := FToolBar.FControls.IndexOf(Self);
end;
function TToolButton.IsWidthStored: Boolean;
begin
Result := Style in [tbsSeparator, tbsDivider];
end;
function TToolButton.CheckMenuDropDown: Boolean;
begin
Result := False;
{ Result := not (csDesigning in ComponentState) and ((DropdownMenu <> nil) and
DropdownMenu.AutoPopup or (MenuItem <> nil)) and (FToolBar <> nil) and
FToolBar.CheckMenuDropdown(Self);}
end;
function TToolButton.IsCheckedStored: Boolean;
begin
Result := (ActionLink = nil) or not TToolButtonActionLink(ActionLink).IsCheckedLinked;
end;
function TToolButton.IsImageIndexStored: Boolean;
begin
Result := (ActionLink = nil) or not TToolButtonActionLink(ActionLink).IsImageIndexLinked;
end;
procedure TToolButton.ActionChange(Sender: TObject; CheckDefaults: Boolean);
begin
inherited ActionChange(Sender, CheckDefaults);
if Sender is TCustomAction then
with TCustomAction(Sender) do
begin
if not CheckDefaults or (Self.Down = False) then
Self.Down := Checked;
if not CheckDefaults or (Self.ImageIndex = -1) then
Self.ImageIndex := ImageIndex;
end;
end;
function TToolButton.GetActionLinkClass: TControlActionLinkClass;
begin
Result := TToolButtonActionLink;
end;
procedure TToolButton.AssignTo(Dest: TPersistent);
begin
inherited AssignTo(Dest);
if Dest is TCustomAction then
with TCustomAction(Dest) do
begin
Checked := Self.Down;
ImageIndex := Self.ImageIndex;
end;
end;
procedure TToolButton.ValidateContainer(AComponent: TComponent);
var
W: Integer;
begin
inherited ValidateContainer(AComponent);
{ Update non-stored Width and Height if inserting into TToolBar }
if (csLoading in ComponentState) and (AComponent is TToolBar) then
begin
if Style in [tbsDivider, tbsSeparator] then
W := Width else
W := TToolBar(AComponent).ButtonWidth;
SetBounds(Left, Top, W, TToolBar(AComponent).ButtonHeight);
end;
end;
function TToolButton.GetText: TCaption;
begin
Result := FCaption;
end;
procedure TToolButton.SetText(const Value: TCaption);
begin
if FCaption <> Value then
begin
FCaption := Value;
if Assigned(FToolBar) then FToolBar.ResizeButtons(nil);
Invalidate;
end;
end;
procedure TToolButton.SetAllowAllUp(const Value: Boolean);
begin
if FAllowAllUp <> Value then
begin
FAllowAllUp := Value;
if FToolBar <> nil then
FToolBar.GroupChange(Self, gcAllowAllUp);
end;
end;
procedure TToolButton.MouseEnter(AControl: TControl);
begin
inherited MouseEnter(AControl);
FMouseIn := True;
Paint;
end;
procedure TToolButton.MouseLeave(AControl: TControl);
begin
inherited MouseLeave(AControl);
FMouseIn := False;
Paint;
end;
function TToolButton.DropDownRect: TRect;
begin
Result := Types.Rect(Width - DropDownWidth, 1, Width, Height - 1);
end;
function TToolButton.WantKey(Key: Integer; Shift: TShiftState;
const KeyText: WideString): Boolean;
begin
if IsAccel(Key, Caption) and (ssAlt in Shift) then
begin
Click;
Result := True;
end else
Result := inherited WantKey(Key, Shift, KeyText);
end;
{ TToolBar }
function TBControlSort(Item1, Item2: Pointer): Integer;
var
C1, C2: TControl;
begin
Result := 0;
C1 := TControl(Item1);
C2 := TControl(Item2);
if C1 = C2 then Exit;
if C1.Top = C2.Top then
begin
if C1.Left <= C2.Left then
Result := -1
else
Result := 1
end
else begin
if C1.Top < C2.Top then
Result := -1
else
Result := 1;
end;
end;
function TToolBar.ButtonCount: Integer;
var
I: Integer;
begin
Result := 0;
for I := 0 to ControlCount - 1 do
if (Controls[I] is TToolButton) then Inc(Result);
end;
procedure TToolBar.ControlsAligned;
begin
inherited ControlsAligned;
FControls.Sort(@TBControlSort);
DoResize;
end;
procedure TToolBar.ControlsListChanged(Control: TControl;
Inserting: Boolean);
begin
inherited ControlsListChanged(Control, Inserting);
if Inserting then
begin
if LastControl <> nil then
begin
Control.Left := LastControl.Left + LastControl.Width;
Control.Top := LastControl.Top;
end
else begin
Control.Left := ClientRect.Left;
Control.Top := ClientRect.Top;
end;
Control.Height := FButtonHeight;
if Control is TWidgetControl then
TWidgetControl(Control).HandleNeeded;
if (Control is TToolButton)
and not (TToolButton(Control).Style in [tbsSeparator, tbsDivider])
and not TToolButton(Control).AutoSize then
begin
Inc(FResizeCount);
try
Control.Width := FButtonWidth;
finally
Dec(FResizeCount);
end;
end;
Control.Align := alCustom;
FControls.Add(Control);
end
else
FControls.Remove(Control);
Realign;
if AutoSize then AdjustSize;
end;
constructor TToolBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FControls := TList.Create;
ControlStyle := [csAcceptsControls, csCaptureMouse, csClickEvents,
csDoubleClicks, csMenuEvents, csSetCaption, csNoFocus];
FResizeCount := 0;
Width := 150;
Height := 29;
Align := alTop;
FButtonWidth := 23;
FButtonHeight := 22;
FBorderWidth := 0;
FIndent := 1;
FAutoSize := False;
FList := False;
FEdgeBorders := [ebTop];
FEdgeInner := esRaised;
FEdgeOuter := esLowered;
Wrapable := True;
FImageChangeLink := TChangeLink.Create;
FImageChangeLink.OnChange := ImageListChange;
end;
procedure TToolBar.AdjustClientRect(var Rect: TRect);
begin
Rect.Left := FIndent + FBorderWidth + EdgeSpacing(ebLeft);
Rect.Right := Width - 2 - FBorderWidth + EdgeSpacing(ebRight);
Rect.Top := 2 + FBorderWidth + EdgeSpacing(ebTop);
Rect.Bottom := Height - 3 - FBorderWidth + EdgeSpacing(ebBottom);
end;
function TToolBar.GetControl(Index: Integer): TControl;
begin
Result := TControl(FControls[Index]);
end;
procedure TToolBar.Paint;
begin
inherited Paint;
DoPaint(Canvas);
end;
procedure TToolBar.DoResize;
begin
if not AutoSize then Exit;
AdjustSize;
end;
procedure TToolBar.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
begin
if AComponent = FImages then
begin
FImages := nil;
Repaint;
end;
if AComponent = FDisabledImages then
begin
FDisabledImages := nil;
Repaint;
end;
if AComponent = FHotImages then
begin
FHotImages := nil;
Repaint;
end;
end;
end;
procedure TToolBar.SetAutoSize(const Value: Boolean);
begin
if FAutoSize <> Value then
begin
FAutoSize := Value;
DoResize;
end;
end;
procedure TToolBar.SetButtonHeight(const Value: Integer);
var
I: Integer;
begin
if FButtonHeight <> Value then
begin
Inc(FResizeCount);
try
ControlState := ControlState + [csAlignDisabled];
try
FButtonHeight := Value;
for I := 0 to ControlCount - 1 do
Controls[I].Height := FButtonHeight;
finally
ControlState := ControlState - [csAlignDisabled];
Realign;
end;
finally
Dec(FResizeCount);
end;
end;
end;
procedure TToolBar.InternalSetButtonWidth(const Value: Integer; RestrictSize: Boolean);
var
I: Integer;
begin
if RestrictSize and ShowCaptions then Exit;
ControlState := ControlState + [csAlignDisabled];
Inc(FResizeCount);
try
FButtonWidth := Value;
for I := 0 to ControlCount - 1 do
if Controls[I] is TToolButton then
with TToolButton(Controls[I]) do
begin
if not AutoSize and not (Style in [tbsSeparator, tbsDivider]) then
Width := FButtonWidth + DropDownWidth
else
Width := Width + DropDownWidth;
end;
finally
Dec(FResizeCount);
ControlState := ControlState - [csAlignDisabled];
ReAlign;
end;
end;
procedure TToolBar.SetButtonWidth(const Value: Integer);
begin
InternalSetButtonWidth(Value, True);
end;
procedure TToolBar.SetWrapable(const Value: Boolean);
begin
if FWrapable <> Value then
begin
FWrapable := Value;
Realign;
end;
end;
function TToolBar.LastControl: TControl;
begin
Result := nil;
if ControlCount > 0 then
Result := Controls[ControlCount - 1];
end;
procedure TToolBar.Loaded;
begin
inherited Loaded;
SetButtonWidth(FButtonWidth);
end;
procedure TToolBar.SetBorderWidth(const Value: TBorderWidth);
begin
if FBorderWidth <> Value then
begin
FBorderWidth := Value;
Realign;
end;
end;
procedure TToolBar.SetEdgeBorders(const Value: TEdgeBorders);
begin
FEdgeBorders := Value;
DoResize;
Invalidate;
end;
procedure TToolBar.SetEdgeInner(const Value: TEdgeStyle);
begin
FEdgeInner := Value;
DoResize;
Invalidate;
end;
procedure TToolBar.SetEdgeOuter(const Value: TEdgeStyle);
begin
FEdgeOuter := Value;
DoResize;
Invalidate;
end;
function TToolBar.EdgeSpacing(Edge: TEdgeBorder): Integer;
begin
Result := 0;
if (Edge in FEdgeBorders) then
begin
if FEdgeInner in [esRaised, esLowered] then Inc(Result);
if FEdgeOuter in [esRaised, esLowered] then Inc(Result);
end;
end;
procedure TToolBar.AdjustSize;
var
NewHeight: Integer;
begin
if FAutoSize and (FControls.Count > 0) then
begin
NewHeight := 0;
case Align of
alTop, alBottom:
begin
if LastControl <> nil then
NewHeight := LastControl.Top + LastControl.Height;
NewHeight := NewHeight + FBorderWidth + EdgeSpacing(ebBottom);
Height := NewHeight;
end;
alLeft, alRight:
Width := FRightEdge + FBorderWidth + EdgeSpacing(ebLeft)
+ EdgeSpacing(ebRight);
end;
end;
end;
procedure TToolBar.SetIndent(const Value: Integer);
begin
if FIndent <> Value then
begin
FIndent := Value;
DoResize;
Realign;
end;
end;
procedure TToolBar.SetFlat(const Value: Boolean);
begin
FFlat := Value;
Invalidate;
end;
procedure TToolBar.SetShowCaptions(const Value: Boolean);
begin
if FShowCaptions <> Value then
begin
FShowCaptions := Value;
FButtonHeight := 0;
FButtonWidth := 0;
ResizeButtons(nil);
end;
end;
procedure TToolBar.SetDisabledImages(const Value: TCustomImageList);
begin
if FDisabledImages <> nil then FDisabledImages.UnRegisterChanges(FImageChangeLink);
FDisabledImages := Value;
if FDisabledImages <> nil then
begin
FDisabledImages.RegisterChanges(FImageChangeLink);
FDisabledImages.FreeNotification(Self);
end;
ImageListChange(Value);
end;
procedure TToolBar.SetHotImages(const Value: TCustomImageList);
begin
if FHotImages <> nil then FHotImages.UnRegisterChanges(FImageChangeLink);
FHotImages := Value;
if FHotImages <> nil then
begin
FHotImages.RegisterChanges(FImageChangeLink);
FHotImages.FreeNotification(Self);
end;
ImageListChange(Value);
end;
procedure TToolBar.SetImages(const Value: TCustomImageList);
begin
if FImages <> nil then FImages.UnRegisterChanges(FImageChangeLink);
FImages := Value;
if FImages <> nil then
begin
FImages.RegisterChanges(FImageChangeLink);
FImages.FreeNotification(Self);
end;
ImageListChange(Value);
end;
procedure TToolBar.ImageListChange(Sender: TObject);
begin
FImageWidth := 0;
FImageHeight := 0;
if Assigned(FImages) then
begin
FImageWidth := FImages.Width;
FImageHeight := FImages.Height;
end
else if Assigned(FHotImages) then
begin
FImageWidth := FHotImages.Width;
FImageHeight := FHotImages.Height;
end
else if Assigned(FDisabledImages) then
begin
FImageWidth := FDisabledImages.Width;
FImageHeight := FDisabledImages.Height;
end;
ResizeButtons(nil);
Invalidate;
end;
procedure TToolBar.ResizeButtons(Button: TToolButton);
var
BtnIndex,
I: Integer;
NewWidth,
NewHeight,
AWidth,
AHeight: Integer;
ABtn: TToolButton;
ASize: TSize;
AImageList: TCustomImageList;
begin
Inc(FResizeCount);
ControlState := ControlState + [csAlignDisabled];
ABtn := nil;
AWidth := 0;
try
if Button <> nil then
BtnIndex := FControls.IndexOf(Button)
else
BtnIndex := 0;
if not ShowCaptions then
begin
NewWidth := ButtonWidth; //is this necessary??
NewHeight := ButtonHeight;
end else
begin
NewWidth := 0;
NewHeight := 0;
end;
for I := BtnIndex to ControlCount - 1 do
begin
if Controls[I] is TToolButton then
begin
ABtn := TToolButton(Controls[I]);
if ABtn.Style in [tbsSeparator, tbsDivider] then Continue;
AWidth := 23;
AHeight := 22;
if not FShowCaptions and HasImages then
begin
if Assigned(Images) then
AImageList := Images
else if Assigned(DisabledImages) then
AImageList := DisabledImages
else if Assigned(HotImages) then
AImageList := HotImages
else
AImageList := nil;
if AImageList <> nil then
begin
AWidth := AImageList.Width + (TBSpacing *2) + 1;
AHeight := AImageList.Height + (TBSpacing *2) + 1;
end;
end;
if (ABtn.Caption <> '') and (ABtn.Style in [tbsButton, tbsCheck, tbsDropDown])
and FShowCaptions then
begin
ASize := Canvas.TextExtent(ABtn.Caption, Integer(AlignmentFlags_ShowPrefix) or
Integer(AlignmentFlags_AlignCenter));
AWidth := ASize.cx + (TBSpacing * 3);
AHeight := ASize.cy + (TBSpacing * 2) + 1;
if HasImages then
begin
if FList then
AWidth := AWidth + TBSpacing + FImageWidth
else
AHeight := AHeight + TBSpacing + FImageHeight;
if AHeight < (FImageHeight + (TBSpacing * 2) + 1) then
AHeight := FImageHeight + (TBSpacing *2) + 1;
end;
end;
if AHeight > NewHeight then NewHeight := AHeight;
if AWidth > NewWidth then NewWidth := AWidth;
if ABtn.AutoSize then
ABtn.Width := AWidth;
end;
if ABtn <> nil then
if ABtn.AutoSize then
ABtn.Width := AWidth + ABtn.DropDownWidth
// else if not ShowCaptions then
// ABtn.Width := ButtonWidth + ABtn.DropDownWidth;
end;
finally
Dec(FResizeCount);
ControlState := ControlState - [csAlignDisabled];
end;
if NewHeight = 0 then
ButtonHeight := 22
else
ButtonHeight := NewHeight;
if NewWidth = 0 then
InternalSetButtonWidth(23, False)
else
InternalSetButtonWidth(NewWidth, False);
AdjustSize;
Invalidate;
end;
procedure TToolBar.SetList(const Value: Boolean);
begin
FList := Value;
ResizeButtons(nil);
end;
destructor TToolBar.Destroy;
begin
FControls.Free;
FImageChangeLink.Free;
inherited Destroy;
end;
procedure TToolBar.GroupChange(Requestor: TToolButton; Reason: TGroupChangeReason);
procedure ApplyToGroup(Index: Integer; Dir: SmallInt;
Reason: TGroupChangeReason);
var
Control: TControl;
begin
Inc(Index, Dir);
while (Index >= 0) and (Index < ControlCount) do
begin
Control := Controls[Index];
if (Control is TToolButton) and TToolButton(Control).Grouped then
case Reason of
gcAllowAllUp:
TToolButton(Control).FAllowAllUp := Requestor.AllowAllUp;
gcDownState:
begin
TToolButton(Control).FDown := False;
Control.Invalidate;
end;
end
else Break;
Inc(Index, Dir);
end;
end;
begin
ApplyToGroup(FControls.IndexOf(Requestor), -1, Reason);
ApplyToGroup(FControls.IndexOf(Requestor), 1, Reason);
end;
function TToolBar.CustomAlignInsertBefore(C1, C2: TControl): Boolean;
begin
Result := False;
case Align of
alTop, alBottom, alNone, alClient:
if C1.Top = C2.Top then
Result := C1.Left < C2.Left
else
Result := C1.Top < C2.Top;
alLeft, alRight:
if C1.Left = C2.Left then
Result := C1.Top < C2.Top
else
Result := C1.Left < C2.Left;
end;
FRightEdge := 0;
end;
procedure TToolBar.CustomAlignPosition(Control: TControl; var NewLeft, NewTop, NewWidth,
NewHeight: Integer; var AlignRect: TRect);
begin
if Wrapable then
begin
case Align of
alTop, alBottom, alNone, alClient:
if (((AlignRect.Left + Control.Width) > AlignRect.Right)
and (AlignRect.Left > ClientRect.Left)) then
begin
Inc(AlignRect.Top, NewHeight);
NewLeft := ClientRect.Left;
AlignRect.Left := NewLeft + Control.Width;
NewTop := AlignRect.Top;
end else
Inc(AlignRect.Left, NewWidth);
alLeft, alRight:
begin
if (((AlignRect.Top + Control.Height) > AlignRect.Bottom)
and (AlignRect.Top > ClientRect.Top)) then
begin
AlignRect.Left := FRightEdge;
NewTop := ClientRect.Top;
AlignRect.Top := NewTop + Control.Height;
NewLeft := AlignRect.Left;
end else
Inc(AlignRect.Top, NewHeight);
if AlignRect.Left + Control.Width > FRightEdge then
FRightEdge := AlignRect.Left + Control.Width;
end;
end
end else
begin
case Align of
alTop, alBottom, alNone, alClient:
begin
NewLeft := AlignRect.Left;
NewTop := AlignRect.Top;
if (Control is TToolButton)
and TToolButton(Control).Wrap then
begin
Inc(AlignRect.Top, ButtonHeight);
AlignRect.Left := ClientRect.Left;
end else
Inc(AlignRect.Left, NewWidth);
end;
alLeft, alRight:
begin
NewLeft := AlignRect.Left;
NewTop := AlignRect.Top;
if (Control is TToolButton)
and TToolButton(Control).Wrap then
begin
Inc(AlignRect.Left, ButtonWidth);
AlignRect.Top := ClientRect.Top;
end else
Inc(AlignRect.Top, NewHeight);
if AlignRect.Left + Control.Width > FRightEdge then
FRightEdge := AlignRect.Left + Control.Width;
end;
end;
end;
end;
function TToolBar.HasImages: Boolean;
begin
Result := (FImages <> nil) or (FDisabledImages <> nil) or
(FHotImages <> nil);
end;
procedure TToolBar.Invalidate;
var
I: Integer;
begin
inherited Invalidate;
for I := 0 to ControlCount - 1 do
Controls[I].Invalidate;
end;
function TToolBar.ControlCount: Integer;
begin
Result := FControls.Count;
end;
procedure TToolBar.DoPaint(ACanvas: TCanvas);
var
R: TRect;
begin
if not Masked and not Assigned(Bitmap) then
begin
ACanvas.Brush.Color := Color;
ACanvas.FillRect(BoundsRect);
end;
R := Types.Rect(0, 0, Width, Height);
DrawEdge(ACanvas, R, FEdgeInner, FEdgeOuter, FEdgeBorders);
end;
procedure TToolBar.FontChanged;
begin
inherited FontChanged;
Canvas.Font := Font;
ResizeButtons(nil);
end;
procedure TToolBar.InitWidget;
begin
inherited;
TabStop := False;
end;
function TToolBar.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
if (QEvent_type(Event) = QEventType_Resize) then
Result := True
else
Result := inherited EventFilter(Sender, Event);
end;
{ TToolButtonActionLink }
procedure TToolButtonActionLink.AssignClient(AClient: TObject);
begin
inherited AssignClient(AClient);
FClient := AClient as TToolButton;
end;
function TToolButtonActionLink.IsCheckedLinked: Boolean;
begin
Result := inherited IsCheckedLinked and
(FClient.Down = (Action as TCustomAction).Checked);
end;
function TToolButtonActionLink.IsImageIndexLinked: Boolean;
begin
Result := inherited IsImageIndexLinked and
(FClient.ImageIndex = (Action as TCustomAction).ImageIndex);
end;
procedure TToolButtonActionLink.SetChecked(Value: Boolean);
begin
if IsCheckedLinked then FClient.Down := Value;
end;
procedure TToolButtonActionLink.SetImageIndex(Value: Integer);
begin
if IsImageIndexLinked then FClient.ImageIndex := Value;
end;
{ TIconOptions }
constructor TIconOptions.Create(AOwner: TCustomIconView);
begin
inherited Create;
FIconView := AOwner;
FArrangement := iaLeft;
FAutoArrange := True;
FWrapText := True;
end;
procedure TIconOptions.SetArrangement(Value: TIconArrangement);
begin
if (FArrangement <> Value) then
begin
FArrangement := Value;
if FIconView.HandleAllocated then
QIconView_setArrangement(FIconView.Handle, cIVQtArrangement[FArrangement]);
end;
end;
procedure TIconOptions.SetAutoArrange(Value: Boolean);
begin
if (FAutoArrange <> Value) then
begin
FAutoArrange := Value;
if FIconView.HandleAllocated then
QIconView_setAutoArrange(FIconView.Handle, FAutoArrange);
end;
end;
procedure TIconOptions.SetWrapText(Value: Boolean);
begin
if (FWrapText <> Value) then
begin
FWrapText := Value;
if FIconView.HandleAllocated then
QIconView_setWordWrapIconText(FIconView.Handle, FWrapText);
end;
end;
end.
|
unit parser;
interface
uses scanner;
type Contents = string[255];
type Node = record
child : ^Node;
next : ^Node;
content : Contents;
end;
type Tree = record
root : ^Node;
end;
type nodePtr = ^Node;
type treePtr = ^Tree;
var parseTree : Tree;
var cellWidth : integer;
var rowWidth : integer;
procedure Parse;
function ConstructNode : nodePtr;
function ConstructParseTree : treePtr;
implementation
type State = (Outside, ParseTable, ParseRow, ParseCell);
var parseState : State;
var error : boolean;
function ConstructNode : nodePtr;
var
newNode : nodePtr;
begin
New(newNode);
newNode^.child := nil;
newNode^.next := nil;
newNode^.content := '';
ConstructNode := newNode;
end;
function ConstructParseTree : treePtr;
var
newTree : treePtr;
begin
New(newTree);
newTree^.root := ConstructNode;
ConstructParseTree := newTree;
end;
procedure addChild(parent, node : nodePtr);
var
iter : nodePtr;
begin
if (parent = nil) or (node = nil) then
begin
writeln('Error: nil pointer passed to addChild.');
error := true;
exit;
end;
iter := parent^.child;
if (iter = nil) then
parent^.child := node
else
begin
while (not(iter^.next = nil)) do
iter := iter^.next;
iter^.next := node;
end;
end;
procedure parseError(msg : string);
begin
writeln('Parse error: ' + msg);
error := true;
end;
procedure Parse;
var
currentTable : nodePtr;
currentRow : nodePtr;
currentCell : nodePtr;
rowWidthCounter : integer;
begin
currentTable := nil;
currentRow := nil;
currentCell := nil;
rowWidthCounter := 0;
error := false;
parseState := Outside;
GetSym;
while (not(sym = EofSym)) and (not error) do
begin
case sym of
TableStartSym:
begin
if (parseState = Outside) then
begin
parseState := ParseTable;
currentTable := ConstructNode;
addChild(parseTree.root, currentTable);
end
else
parseError('Unexpected tag: <TABLE>');
end;
TableEndSym:
begin
if (parseState = ParseTable) then
parseState := Outside
else
parseError('Unexpected tag: </TABLE>');
end;
RowStartSym:
begin
if (parseState = ParseTable) then
begin
rowWidthCounter := 0;
parseState := ParseRow;
currentRow := ConstructNode;
addChild(currentTable, currentRow);
end
else
parseError('Unexpected tag: <TR>');
end;
RowEndSym:
begin
if (parseState = ParseRow) then
begin
if (rowWidthCounter > rowWidth) then
rowWidth := rowWidthCounter;
parseState := ParseTable;
end
else
parseError('Unexpected tag: </TR>');
end;
CellStartSym:
begin
if (parseState = ParseRow) then
begin
rowWidthCounter := rowWidthCounter + 1;
parseState := ParseCell;
currentCell := ConstructNode;
addChild(CurrentRow, CurrentCell);
end
else
parseError('Unexpected tag: <TD>');
end;
CellEndSym:
begin
if (parseState = ParseCell) then
parseState := ParseRow
else
parseError('Unexpected tag: </TD>');
end;
ContentsSym:
begin
if (parseState = ParseCell) then
currentCell^.content := cont;
if (length(cont) > cellWidth) then
cellWidth := length(cont) - 1;
end;
end;
GetSym;
end;
end;
begin
parseTree := ConstructParseTree^;
cellWidth := 0;
rowWidth := 0;
end.
|
unit PropTxtEditor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TPropertyTextEditor = class(TForm)
Panel1: TPanel;
mEditor: TMemo;
btnCancel: TButton;
btnOk: TButton;
procedure FormResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
procedure CheckControlsPosition;
{ Private declarations }
public
{ Public declarations }
function ShowModal(const ACaption, AValue: string): TModalResult; reintroduce;
end;
implementation
{$R *.dfm}
procedure TPropertyTextEditor.CheckControlsPosition();
begin
Panel1.Width := self.ClientWidth;
btnCancel.Left := btnCancel.Parent.Width - btnCancel.Width - 8;
btnOk.Left := btnCancel.Left - btnOk.Width - 8;
end;
procedure TPropertyTextEditor.FormResize(Sender: TObject);
begin
CheckControlsPosition();
end;
procedure TPropertyTextEditor.FormCreate(Sender: TObject);
begin
CheckControlsPosition();
end;
function TPropertyTextEditor.ShowModal(const ACaption, AValue: string): TModalResult;
begin
Caption := ACaption;
mEditor.Lines.Text := AValue;
Result := inherited ShowModal();
end;
end.
|
{
Mystix
Copyright (C) 2005 Piotr Jura
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
You can contact with me by e-mail: pjura@o2.pl
}
unit uMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, JvDockControlForm, JvDockVIDStyle,
JvComponent, JvMouseGesture, SynEditPrint, JvTabBar, SynEditRegexSearch,
SynEditMiscClasses, SynEditSearch, Menus, ImgList, ActnList,
ComCtrls, ToolWin, uMyIniFiles, uMRU, uUtils, SynEditTypes, uDocuments,
SynEdit, JvDockTree, JvComponentBase;
type
TMainForm = class(TForm)
actlMain: TActionList;
mnuMain: TMainMenu;
StatusBar: TStatusBar;
tbMain: TToolBar;
tbDocuments: TJvTabBar;
miFile: TMenuItem;
miEdit: TMenuItem;
miSearch: TMenuItem;
miView: TMenuItem;
miHelp: TMenuItem;
ToolButton1: TToolButton;
FileNew: TAction;
miNew: TMenuItem;
FileOpen: TAction;
FileSave: TAction;
FileSaveAs: TAction;
FileSaveAll: TAction;
FileClose: TAction;
FileCloseAll: TAction;
FilePrint: TAction;
FileExit: TAction;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
ToolButton7: TToolButton;
ToolButton8: TToolButton;
ToolButton9: TToolButton;
FileOpen1: TMenuItem;
N1: TMenuItem;
Save1: TMenuItem;
SaveAs1: TMenuItem;
SaveAll1: TMenuItem;
N2: TMenuItem;
Close1: TMenuItem;
CloseAll1: TMenuItem;
N3: TMenuItem;
Print1: TMenuItem;
Exit1: TMenuItem;
imglMain: TImageList;
ToolButton10: TToolButton;
ToolButton11: TToolButton;
ToolButton12: TToolButton;
ToolButton13: TToolButton;
ToolButton14: TToolButton;
ToolButton15: TToolButton;
ToolButton16: TToolButton;
ToolButton17: TToolButton;
EditUndo: TAction;
EditRedo: TAction;
EditCut: TAction;
EditPaste: TAction;
EditCopy: TAction;
EditDelete: TAction;
EditSelectAll: TAction;
Undo1: TMenuItem;
Redo1: TMenuItem;
N5: TMenuItem;
Cut1: TMenuItem;
Copy1: TMenuItem;
Paste1: TMenuItem;
Delete1: TMenuItem;
SelectAll1: TMenuItem;
EditIndent: TAction;
EditUnindent: TAction;
N6: TMenuItem;
EditIndent1: TMenuItem;
EditUnindent1: TMenuItem;
ToolButton18: TToolButton;
ToolButton19: TToolButton;
ToolButton20: TToolButton;
SearchFind: TAction;
SearchFindNext: TAction;
SearchReplace: TAction;
SearchGoToLine: TAction;
ToolButton21: TToolButton;
ToolButton22: TToolButton;
ToolButton23: TToolButton;
ToolButton24: TToolButton;
ToolButton26: TToolButton;
SearchFind1: TMenuItem;
SearchReplace1: TMenuItem;
SearchFindNext1: TMenuItem;
SearchGoToLine1: TMenuItem;
HelpTopics: TAction;
ToolButton25: TToolButton;
ToolButton27: TToolButton;
New1: TMenuItem;
N7: TMenuItem;
ViewCollapseAll: TAction;
ViewUncollapseAll: TAction;
oolbar1: TMenuItem;
StatusBar1: TMenuItem;
N8: TMenuItem;
CollapseAll1: TMenuItem;
UncollapseAll1: TMenuItem;
miViewCollapseLevel: TMenuItem;
miViewUncollapseLevel: TMenuItem;
tbtnUncollapse: TToolButton;
tbtnCollapse: TToolButton;
ToolButton30: TToolButton;
N9: TMenuItem;
LineNumbers1: TMenuItem;
ShowGutter1: TMenuItem;
ShowIndentGuides1: TMenuItem;
WordWrap1: TMenuItem;
ShowRightMargin1: TMenuItem;
miViewFont: TMenuItem;
miEditorFont1: TMenuItem;
miEditorFont2: TMenuItem;
miEditorFont3: TMenuItem;
miEditorFont4: TMenuItem;
miEditorFont5: TMenuItem;
miEditorFontSep: TMenuItem;
ViewFont: TAction;
Font2: TMenuItem;
ViewToolbar: TAction;
ViewStatusBar: TAction;
ViewShowGutter: TAction;
ViewShowLineNumbers: TAction;
ViewShowRightMargin: TAction;
ViewWordWrap: TAction;
ViewShowIndentGuides: TAction;
ViewSettings: TAction;
ToolButton31: TToolButton;
ToolButton32: TToolButton;
N11: TMenuItem;
Settings1: TMenuItem;
HelpAbout: TAction;
N12: TMenuItem;
About1: TMenuItem;
ViewCollapseLevel0: TAction;
ViewCollapseLevel1: TAction;
ViewCollapseLevel2: TAction;
ViewCollapseLevel3: TAction;
ViewCollapseLevel4: TAction;
ViewCollapseLevel5: TAction;
ViewCollapseLevel6: TAction;
ViewCollapseLevel7: TAction;
ViewCollapseLevel8: TAction;
ViewCollapseLevel9: TAction;
CollapseLevel01: TMenuItem;
CollapseLevel11: TMenuItem;
CollapseLevel21: TMenuItem;
CollapseLevel31: TMenuItem;
CollapseLevel41: TMenuItem;
CollapseLevel51: TMenuItem;
CollapseLevel61: TMenuItem;
CollapseLevel71: TMenuItem;
CollapseLevel81: TMenuItem;
CollapseLevel91: TMenuItem;
mnuCollapse: TPopupMenu;
mnuUncollapse: TPopupMenu;
CollapseAll2: TMenuItem;
CollapseLevel02: TMenuItem;
CollapseLevel12: TMenuItem;
N13: TMenuItem;
CollapseLevel22: TMenuItem;
CollapseLevel32: TMenuItem;
CollapseLevel42: TMenuItem;
CollapseLevel52: TMenuItem;
CollapseLevel62: TMenuItem;
CollapseLevel72: TMenuItem;
CollapseLevel82: TMenuItem;
CollapseLevel92: TMenuItem;
ViewUncollapseLevel0: TAction;
ViewUncollapseLevel1: TAction;
ViewUncollapseLevel2: TAction;
ViewUncollapseLevel3: TAction;
ViewUncollapseLevel4: TAction;
ViewUncollapseLevel5: TAction;
ViewUncollapseLevel6: TAction;
ViewUncollapseLevel7: TAction;
ViewUncollapseLevel8: TAction;
ViewUncollapseLevel9: TAction;
UncollapseLevel01: TMenuItem;
UncollapseLevel11: TMenuItem;
UncollapseLevel21: TMenuItem;
UncollapseLevel31: TMenuItem;
UncollapseLevel41: TMenuItem;
UncollapseLevel51: TMenuItem;
UncollapseLevel61: TMenuItem;
UncollapseLevel71: TMenuItem;
UncollapseLevel81: TMenuItem;
UncollapseLevel91: TMenuItem;
UncollapseLevel02: TMenuItem;
UncollapseLevel12: TMenuItem;
UncollapseLevel22: TMenuItem;
UncollapseLevel32: TMenuItem;
UncollapseLevel42: TMenuItem;
UncollapseLevel52: TMenuItem;
UncollapseLevel62: TMenuItem;
UncollapseLevel72: TMenuItem;
UncollapseLevel82: TMenuItem;
UncollapseLevel92: TMenuItem;
N14: TMenuItem;
N15: TMenuItem;
dlgOpen: TOpenDialog;
dlgSave: TSaveDialog;
miViewDocumentType: TMenuItem;
miViewDocumentTypeMore: TMenuItem;
N16: TMenuItem;
DocumentType11: TMenuItem;
dlgFont: TFontDialog;
mnuEditor: TPopupMenu;
Close2: TMenuItem;
N17: TMenuItem;
Cut2: TMenuItem;
Copy2: TMenuItem;
Paste2: TMenuItem;
Delete2: TMenuItem;
SelectAll2: TMenuItem;
N18: TMenuItem;
Indent1: TMenuItem;
Unindent1: TMenuItem;
Open1: TMenuItem;
ToolButton33: TToolButton;
ToolButton34: TToolButton;
ViewDocumentType1: TAction;
ViewDocumentType2: TAction;
ViewDocumentType3: TAction;
ViewDocumentType4: TAction;
ViewDocumentType5: TAction;
ViewDocumentType6: TAction;
ViewDocumentType7: TAction;
ViewDocumentType8: TAction;
ViewDocumentType9: TAction;
ViewDocumentType10: TAction;
DocumentType21: TMenuItem;
DocumentType31: TMenuItem;
DocumentType41: TMenuItem;
DocumentType51: TMenuItem;
DocumentType61: TMenuItem;
DocumentType71: TMenuItem;
DocumentType81: TMenuItem;
DocumentType91: TMenuItem;
DocumentType101: TMenuItem;
ViewDocumentType0: TAction;
miViewDocumentTypeNone: TMenuItem;
N10: TMenuItem;
miFileRecentFiles: TMenuItem;
Search: TSynEditSearch;
RegexSearch: TSynEditRegexSearch;
ViewShowSpecialCharacters: TAction;
ShowSpecialCharacters1: TMenuItem;
SearchReplaceNext: TAction;
ReplaceNext1: TMenuItem;
N4: TMenuItem;
tmrStatusBar: TTimer;
FileWorkspaceOpen: TAction;
FileWorkspaceSave: TAction;
FileWorkspaceSaveAs: TAction;
FileWorkspaceClose: TAction;
N19: TMenuItem;
miFileWorkspace: TMenuItem;
Open2: TMenuItem;
Save2: TMenuItem;
SaveAs2: TMenuItem;
Close3: TMenuItem;
ViewCollapseCurrent: TAction;
N20: TMenuItem;
CollapseCurrent1: TMenuItem;
CollapseCurrent2: TMenuItem;
miViewLanguage: TMenuItem;
N21: TMenuItem;
FunctionList1: TMenuItem;
ViewFunctionList: TAction;
EditDeleteWord: TAction;
miEditDeleteMore: TMenuItem;
DeleteWord1: TMenuItem;
EditDeleteLine: TAction;
EditDeleteToEndOfWord: TAction;
EditDeleteToEndOfLine: TAction;
EditDeleteWordBack: TAction;
DeleteLine1: TMenuItem;
DeletetoEndofWord1: TMenuItem;
DeletetoEndofLine1: TMenuItem;
DeleteWordBack1: TMenuItem;
EditSelectWord: TAction;
EditSelectLine: TAction;
EditColumnSelect: TAction;
miEditSelectMore: TMenuItem;
SelectWord1: TMenuItem;
SelectLine1: TMenuItem;
ColumnSelect1: TMenuItem;
ViewOutput: TAction;
Output1: TMenuItem;
JvModernTabBarPainter: TJvModernTabBarPainter;
SynEditPrint: TSynEditPrint;
dlgPrint: TPrintDialog;
JvMouseGesture: TJvMouseGesture;
tmrDelayClose: TTimer;
JvDockServer: TJvDockServer;
JvDockVIDStyle1: TJvDockVIDStyle;
SearchFunctionList: TAction;
N22: TMenuItem;
FunctionList2: TMenuItem;
miEditChangeCase: TMenuItem;
EditChangeCaseUpper: TAction;
EditChangeCaseLower: TAction;
EditChangeCaseToggle: TAction;
EditChangeCaseCapitalize: TAction;
UpperCase1: TMenuItem;
LowerCase1: TMenuItem;
oggleCase1: TMenuItem;
Capitalize1: TMenuItem;
FileMRUClear: TAction;
FileWorkspaceMRUClear: TAction;
FileMRUOpenAll: TAction;
procedure FileNewExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FileOpenExecute(Sender: TObject);
procedure FileSaveExecute(Sender: TObject);
procedure FileSaveAsExecute(Sender: TObject);
procedure FileSaveAllExecute(Sender: TObject);
procedure FileCloseExecute(Sender: TObject);
procedure FileCloseAllExecute(Sender: TObject);
procedure FilePrintExecute(Sender: TObject);
procedure FileExitExecute(Sender: TObject);
procedure EditUndoExecute(Sender: TObject);
procedure EditRedoExecute(Sender: TObject);
procedure EditCutExecute(Sender: TObject);
procedure EditCopyExecute(Sender: TObject);
procedure EditPasteExecute(Sender: TObject);
procedure EditDeleteExecute(Sender: TObject);
procedure EditSelectAllExecute(Sender: TObject);
procedure EditIndentExecute(Sender: TObject);
procedure EditUnindentExecute(Sender: TObject);
procedure tbDocumentsTabSelected(Sender: TObject; Item: TJvTabBarItem);
procedure tbDocumentsTabClosed(Sender: TObject; Item: TJvTabBarItem);
procedure FileSaveUpdate(Sender: TObject);
procedure FileSaveAllUpdate(Sender: TObject);
procedure EditUndoUpdate(Sender: TObject);
procedure EditRedoUpdate(Sender: TObject);
procedure SelAvailUpdate(Sender: TObject);
procedure EditCopyUpdate(Sender: TObject);
procedure EditPasteUpdate(Sender: TObject);
procedure AnyDocumentOpenUpdate(Sender: TObject);
procedure ViewToolbarExecute(Sender: TObject);
procedure ViewStatusBarExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ViewShowGutterExecute(Sender: TObject);
procedure ViewShowLineNumbersExecute(Sender: TObject);
procedure ViewShowRightMarginExecute(Sender: TObject);
procedure ViewWordWrapExecute(Sender: TObject);
procedure ViewFontExecute(Sender: TObject);
procedure ViewShowIndentGuidesExecute(Sender: TObject);
procedure CodeFoldingUpdate(Sender: TObject);
procedure miEditorFont1Click(Sender: TObject);
procedure ViewSettingsExecute(Sender: TObject);
procedure ViewDocumentType1Execute(Sender: TObject);
procedure miViewDocumentTypeClick(Sender: TObject);
procedure ViewDocumentType0Execute(Sender: TObject);
procedure miViewDocumentTypeMoreClick(Sender: TObject);
procedure ViewDocumentType0Update(Sender: TObject);
procedure DocumentTypeMoreClick(Sender: TObject);
procedure RecentFilesClick(Sender: TObject);
procedure ViewCollapseAllExecute(Sender: TObject);
procedure ViewUncollapseAllExecute(Sender: TObject);
procedure ViewCollapseLevel0Execute(Sender: TObject);
procedure ViewUncollapseLevel0Execute(Sender: TObject);
procedure SearchFindExecute(Sender: TObject);
procedure SearchFindNextExecute(Sender: TObject);
procedure SearchReplaceExecute(Sender: TObject);
procedure SearchGoToLineExecute(Sender: TObject);
procedure HelpTopicsExecute(Sender: TObject);
procedure HelpAboutExecute(Sender: TObject);
procedure ViewShowSpecialCharactersExecute(Sender: TObject);
procedure SearchReplaceNextExecute(Sender: TObject);
procedure StatusBarDrawPanel(StatusBar: TStatusBar;
Panel: TStatusPanel; const Rect: TRect);
procedure tmrStatusBarTimer(Sender: TObject);
procedure FileWorkspaceOpenExecute(Sender: TObject);
procedure FileWorkspaceSaveExecute(Sender: TObject);
procedure FileWorkspaceSaveAsExecute(Sender: TObject);
procedure FileWorkspaceCloseExecute(Sender: TObject);
procedure FileWorkspaceSaveUpdate(Sender: TObject);
procedure RecentWorkspacesClick(Sender: TObject);
procedure ViewCollapseCurrentExecute(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure miViewLanguageClick(Sender: TObject);
procedure ViewFunctionListExecute(Sender: TObject);
procedure ViewOutputExecute(Sender: TObject);
procedure ViewFunctionListUpdate(Sender: TObject);
procedure ViewOutputUpdate(Sender: TObject);
procedure EditDeleteWordExecute(Sender: TObject);
procedure EditDeleteLineExecute(Sender: TObject);
procedure EditDeleteToEndOfWordExecute(Sender: TObject);
procedure EditDeleteToEndOfLineExecute(Sender: TObject);
procedure EditDeleteWordBackExecute(Sender: TObject);
procedure EditSelectWordExecute(Sender: TObject);
procedure EditSelectLineExecute(Sender: TObject);
procedure EditColumnSelectExecute(Sender: TObject);
procedure EditColumnSelectUpdate(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure JvMouseGestureMouseGestureDown(Sender: TObject);
procedure JvMouseGestureMouseGestureLeft(Sender: TObject);
procedure JvMouseGestureMouseGestureRight(Sender: TObject);
procedure JvMouseGestureMouseGestureUp(Sender: TObject);
procedure tmrDelayCloseTimer(Sender: TObject);
procedure SearchFunctionListExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure EditChangeCaseUpperExecute(Sender: TObject);
procedure EditChangeCaseLowerExecute(Sender: TObject);
procedure EditChangeCaseToggleExecute(Sender: TObject);
procedure EditChangeCaseCapitalizeExecute(Sender: TObject);
procedure FileMRUClearExecute(Sender: TObject);
procedure FileWorkspaceMRUClearExecute(Sender: TObject);
procedure FileMRUOpenAllExecute(Sender: TObject);
private
{ Private declarations }
fStatusBarColor: TColor;
fStatusBarTextColor: TColor;
fWorkspaceFile: String;
fWorkspaceModified: Boolean;
procedure FindReplaceForm(Replace: Boolean);
procedure SetupDialogsFilter;
procedure OpenWorkspace(FileName: String);
procedure OnIdle(Sender: TObject; var Done: Boolean);
procedure ReadLanguageData;
procedure UpdateLanguageMenu;
procedure LanguagesClick(Sender: TObject);
procedure UpdateDynamicMenus;
procedure UpdateFontMenu;
procedure ReadSettings(FirstTime: Boolean = False);
procedure UpdateDocumentTypeMenu;
procedure WMOpenFile(var Message: TMessage); message WM_OPENFILE;
public
{ Public declarations }
procedure StatusMsg(Msg: String; BackColor: TColor = -1;
TextColor: TColor = -1; TimeInterval: Integer = -1;
DoBeep: Boolean = False);
procedure UpdateMRUFilesMenu;
procedure UpdateMRUWorkspacesMenu;
procedure WmMButtonUp(var Message: TMessage); message WM_MBUTTONUP;
procedure SaveAs(aDocument: TDocument = nil);
end;
function DocumentTypeForExt(Ext: String): String;
function GetDocumentTypeIndex(aType: String): Integer;
var
MainForm: TMainForm;
Settings: TMyIniFile;
ActiveLanguage: String;
DocTypes, CommonDocTypes, Languages: TStringList;
MRUFiles, MRUFindText, MRUReplaceText, MRUWorkspaces: TMRUList;
frFindText, frReplaceText: String;
frWholeWords, frMatchCase, frRegExp, frFromCursor, frPrompt,
frInAll, frDirUp, frSelOnly: Boolean;
const
idXYPanel = 0; // Luciano
idModifiedPanel = 1;
idInsertModePanel = 2;
idCapsPanel = 3;
idNumPanel = 4;
idScrollPanel = 5;
idDocTypePanel = 6;
idDocSizePanel = 7;
idMsgPanel = 8;
implementation
uses uFind, uAbout, uReplace, uGoToLine, uProject, uFunctionList,
uOutput, uOptions;
{$IFDEF MSWINDOWS}
{$R *.dfm}
{$ENDIF}
{$IFDEF LINUX}
{$R *.xfm}
{$ENDIF}
function DocumentTypeForExt(Ext: String): String;
var
i: Integer;
ExtStr: String;
ExtList: TStringList;
begin
ExtList := TStringList.Create;
try
for i := 1 to DocTypes.Count do
begin
ExtList.Clear;
ExtStr := Settings.ReadString('DocumentTypes', 'DocumentTypeExtensions' + IntToStr(i) , '');
ExtractStrings([';'], [], PChar(ExtStr), ExtList);
if ExtList.IndexOf(Ext) <> -1 then
begin
Result := DocTypes[i - 1];
Break;
end;
end;
finally
ExtList.Free;
end;
end;
function GetDocumentTypeIndex(aType: String): Integer;
begin
Result := DocTypes.IndexOf(aType) + 1;
end;
procedure TMainForm.FileNewExecute(Sender: TObject);
begin
DocumentFactory.New;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
Application.OnIdle := OnIdle;
JvMouseGesture.Active := True;
fWorkspaceFile := '';
AppPath := IncludeTrailPathSep( ExtractFileDir(Application.ExeName) );
Settings := TMyIniFile.Create(AppPath + 'Settings.ini');
Settings.WriteInteger('General', 'InstanceHandle', Handle);
ReadSettings(True);
// Docking windows
FunctionListForm := TFunctionListForm.Create(Self);
OutputForm := TOutputForm.Create(Self);
LoadDockTreeFromFile(AppPath + 'DockWindows.ini');
// Function List window
if GetFormVisible(FunctionListForm) then
ShowDockForm(FunctionListForm);
// Output window
if GetFormVisible(OutputForm) then
ShowDockForm(OutputForm);
end;
procedure TMainForm.FileOpenExecute(Sender: TObject);
var
i: Integer;
begin
SetupDialogsFilter;
with dlgOpen do
begin
if Document <> nil then // Luciano
InitialDir := ExtractFileDir(Document.FileName);
if Execute then
for i := 0 to Files.Count - 1 do
DocumentFactory.Open( PChar(Files[i]) );
end;
end;
procedure TMainForm.FileSaveExecute(Sender: TObject);
begin
if Document.Saved then
Document.Save
else
FileSaveAsExecute(nil);
end;
procedure TMainForm.FileSaveAsExecute(Sender: TObject);
begin
SaveAs;
end;
procedure TMainForm.FileSaveAllExecute(Sender: TObject);
begin
DocumentFactory.SaveAll;
end;
procedure TMainForm.FileCloseExecute(Sender: TObject);
begin
if Document <> nil then
tmrDelayClose.Enabled := True;
end;
procedure TMainForm.FileCloseAllExecute(Sender: TObject);
begin
DocumentFactory.CloseAll;
end;
procedure TMainForm.FilePrintExecute(Sender: TObject);
var
PrintOptions: TPrintDialogOptions;
begin
Document.Print;
with dlgPrint do
begin
PrintOptions := Options;
MinPage := 1;
FromPage := 1;
MaxPage := SynEditPrint.PageCount;
ToPage := MaxPage;
end;
if not Document.SelAvail then
begin
Exclude(PrintOptions, poSelection);
dlgPrint.PrintRange := prAllPages;
end
else
begin
Include(PrintOptions, poSelection);
dlgPrint.PrintRange := prSelection;
end;
dlgPrint.Options := PrintOptions;
if dlgPrint.Execute then
begin
SynEditPrint.Copies := dlgPrint.Copies;
case dlgPrint.PrintRange of
prSelection: SynEditPrint.SelectedOnly := True;
prPageNums: SynEditPrint.PrintRange(dlgPrint.FromPage, dlgPrint.ToPage);
end;
SynEditPrint.Print;
end;
end;
procedure TMainForm.FileExitExecute(Sender: TObject);
begin
Close;
end;
procedure TMainForm.EditUndoExecute(Sender: TObject);
begin
Document.Undo;
end;
procedure TMainForm.EditRedoExecute(Sender: TObject);
begin
Document.Redo;
end;
procedure TMainForm.EditCutExecute(Sender: TObject);
begin
Document.Cut;
end;
procedure TMainForm.EditCopyExecute(Sender: TObject);
begin
Document.Copy;
end;
procedure TMainForm.EditPasteExecute(Sender: TObject);
begin
Document.Paste;
end;
procedure TMainForm.EditDeleteExecute(Sender: TObject);
begin
Document.Delete;
end;
procedure TMainForm.EditSelectAllExecute(Sender: TObject);
begin
Document.SelectAll;
end;
procedure TMainForm.EditIndentExecute(Sender: TObject);
begin
Document.Indent;
end;
procedure TMainForm.EditUnindentExecute(Sender: TObject);
begin
Document.Unindent;
end;
procedure TMainForm.tbDocumentsTabSelected(Sender: TObject;
Item: TJvTabBarItem);
begin
if Item <> nil then
TDocument(Item.Data).Activate;
end;
procedure TMainForm.tbDocumentsTabClosed(Sender: TObject;
Item: TJvTabBarItem);
begin
Document.Close;
end;
procedure TMainForm.FileSaveUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := (Document <> nil) and (Document.CanSave);
end;
procedure TMainForm.FileSaveAllUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := DocumentFactory.CanSaveAll;
end;
procedure TMainForm.EditUndoUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := (Document <> nil) and (Document.CanUndo);
end;
procedure TMainForm.EditRedoUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := (Document <> nil) and (Document.CanRedo);
end;
procedure TMainForm.SelAvailUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := (Document <> nil) and (Document.SelAvail);
end;
procedure TMainForm.EditCopyUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := (Document <> nil) and (Document.SelAvail);
end;
procedure TMainForm.EditPasteUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := (Document <> nil) and (Document.CanPaste);
end;
procedure TMainForm.AnyDocumentOpenUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := Document <> nil;
end;
procedure TMainForm.ViewToolbarExecute(Sender: TObject);
begin
tbMain.Visible := (Sender as TAction).Checked;
end;
procedure TMainForm.ViewStatusBarExecute(Sender: TObject);
begin
StatusBar.Visible := (Sender as TAction).Checked;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
with Settings do
begin
// Language
WriteString('General', 'ActiveLanguage', ActiveLanguage);
// Window size/position
if ReadBool('General', 'SaveWindowPosition', False) then
begin
WriteInteger('General', 'WindowState', Integer(WindowState));
if WindowState <> wsMaximized then
begin
WriteInteger('General', 'WindowLeft', Left);
WriteInteger('General', 'WindowTop', Top);
WriteInteger('General', 'WindowWidth', Width);
WriteInteger('General', 'WindowHeight', Height);
end;
end;
end;
// Dock windows
SaveDockTreeToFile(AppPath + 'DockWindows.ini');
// MRU stuff
MRUFiles.Free;
MRUWorkspaces.Free;
MRUFindText.Free;
MRUReplaceText.Free;
// Other stuff
Settings.Free;
DocTypes.Free;
CommonDocTypes.Free;
end;
procedure TMainForm.ViewShowGutterExecute(Sender: TObject);
begin
Settings.WriteBool('Editor', 'ShowGutter', ViewShowGutter.Checked);
DocumentFactory.ReadAllFromIni;
end;
procedure TMainForm.ViewShowLineNumbersExecute(Sender: TObject);
begin
Settings.WriteBool('Editor', 'ShowLineNumbers', ViewShowLineNumbers.Checked);
DocumentFactory.ReadAllFromIni;
end;
procedure TMainForm.ViewShowRightMarginExecute(Sender: TObject);
begin
Settings.WriteBool('Editor', 'ShowRightMargin', ViewShowRightMargin.Checked);
DocumentFactory.ReadAllFromIni;
end;
procedure TMainForm.ViewWordWrapExecute(Sender: TObject);
begin
Settings.WriteBool('Editor', 'WordWrap', ViewWordWrap.Checked);
DocumentFactory.ReadAllFromIni;
end;
procedure TMainForm.ViewFontExecute(Sender: TObject);
begin
with dlgFont do
begin
Font.Name := Settings.ReadString('Editor', 'FontName', 'Courier New');
Font.Size := Settings.ReadInteger('Editor', 'FontSize', 10);
if Execute then
begin
Settings.WriteString('Editor', 'FontName', Font.Name);
Settings.WriteInteger('Editor', 'FontSize', Font.Size);
end;
end;
DocumentFactory.ReadAllFromIni;
end;
procedure TMainForm.ViewShowIndentGuidesExecute(Sender: TObject);
begin
Settings.WriteBool('Editor', 'ShowIndentGuides', ViewShowIndentGuides.Checked);
DocumentFactory.ReadAllFromIni;
end;
procedure TMainForm.CodeFoldingUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := (Document <> nil)
and (Document.Editor.CodeFolding.Enabled);
end;
procedure TMainForm.miEditorFont1Click(Sender: TObject);
var
ItemCaption, FontName: String;
FontSize: Integer;
begin
ItemCaption := (Sender as TMenuItem).Caption;
FontName := StringReplace( Copy( ItemCaption, 1, Pos(',', ItemCaption) - 1 ), '&', '', [] );
FontSize := StrToInt( Copy( ItemCaption, Pos(',', ItemCaption) + 1, MaxInt ) );
Settings.WriteString('Editor', 'FontName', FontName);
Settings.WriteInteger('Editor', 'FontSize', FontSize);
DocumentFactory.ReadAllFromIni;
end;
procedure TMainForm.ViewSettingsExecute(Sender: TObject);
begin
with TOptionsDialog.Create(Self) do
try
if ShowModal = mrOK then
begin
ReadSettings;
DocumentFactory.ReadAllFromIni;
end;
finally
Free;
end;
end;
procedure TMainForm.ViewDocumentType1Execute(Sender: TObject);
begin
Document.DocumentType := CommonDocTypes[ (Sender as TAction).Tag ];
end;
procedure TMainForm.miViewDocumentTypeClick(Sender: TObject);
var
i, TypeIndex: Integer;
begin
if Document <> nil then
begin
if Document.DocumentType <> '' then
begin
TypeIndex := CommonDocTypes.IndexOf(Document.DocumentType) + 1;
if TypeIndex > 0 then
TAction( FindComponent('ViewDocumentType' + IntToStr(TypeIndex)) ).Checked := True
else
for i := 0 to CommonDocTypes.Count do
TAction( FindComponent('ViewDocumentType' + IntToStr(i)) ).Checked := False;
end
else
ViewDocumentType0.Checked := True;
end
else
ViewDocumentType0.Checked := True;
end;
procedure TMainForm.ViewDocumentType0Execute(Sender: TObject);
begin
Document.DocumentType := '';
end;
procedure TMainForm.miViewDocumentTypeMoreClick(Sender: TObject);
var
i, TypeIndex: Integer;
begin
if Document.DocumentType <> '' then
begin
TypeIndex := DocTypes.IndexOf(Document.DocumentType);
if TypeIndex > -1 then
miViewDocumentTypeMore.Items[TypeIndex].Checked := True;
end
else
for i := 0 to miViewDocumentTypeMore.Count - 1 do
miViewDocumentTypeMore.Items[i].Checked := False;
end;
procedure TMainForm.ViewDocumentType0Update(Sender: TObject);
begin
(Sender as TAction).Enabled := Document <> nil;
miViewDocumentTypeMore.Enabled := Document <> nil;
end;
procedure TMainForm.DocumentTypeMoreClick(Sender: TObject);
begin
Document.DocumentType := DocTypes[ (Sender as TMenuItem).Tag ];
end;
procedure TMainForm.UpdateMRUFilesMenu;
var
i: Integer;
MenuItem: TMenuItem;
begin
miFileRecentFiles.Clear;
for i := 0 to MRUFiles.Count - 1 do
begin
MenuItem := TMenuItem.Create(Self);
MenuItem.Caption := '&' + IntToStr(i) + #32 + MRUFiles[i];
MenuItem.Tag := i;
MenuItem.OnClick := RecentFilesClick;
miFileRecentFiles.Add(MenuItem);
end;
MenuItem := TMenuItem.Create(Self);
MenuItem.Caption := '-';
miFileRecentFiles.Add(MenuItem);
MenuItem := TMenuItem.Create(Self);
MenuItem.Action := FileMRUClear;
miFileRecentFiles.Add(MenuItem);
MenuItem := TMenuItem.Create(Self);
MenuItem.Action := FileMRUOpenAll;
miFileRecentFiles.Add(MenuItem);
end;
procedure TMainForm.RecentFilesClick(Sender: TObject);
begin
DocumentFactory.Open( PChar(MRUFiles[(Sender as TMenuItem).Tag]) );
end;
procedure TMainForm.ViewCollapseAllExecute(Sender: TObject);
begin
Document.CollapseAll;
end;
procedure TMainForm.ViewUncollapseAllExecute(Sender: TObject);
begin
Document.UncollapseAll;
end;
procedure TMainForm.ViewCollapseLevel0Execute(Sender: TObject);
begin
Document.CollapseLevel( (Sender as TAction).Tag );
end;
procedure TMainForm.ViewUncollapseLevel0Execute(Sender: TObject);
begin
Document.UncollapseLevel( (Sender as TAction).Tag );
end;
procedure TMainForm.SearchFindExecute(Sender: TObject);
begin
FindReplaceForm(False);
end;
procedure TMainForm.SearchFindNextExecute(Sender: TObject);
begin
if frFindText <> '' then
if not Document.FindNext then
StatusMsg( PChar( Format(sStrings[siNotFound], [frFindText]) ), ErrorMsgColor, clWhite,
4000, False );
end;
procedure TMainForm.SearchReplaceExecute(Sender: TObject);
begin
FindReplaceForm(True);
end;
procedure TMainForm.SearchGoToLineExecute(Sender: TObject);
begin
with TGoToLineDialog.Create(Self) do
try
if ShowModal = mrOk then
Document.GoToLine( StrToInt(txtLine.Text) );
finally
Free;
end;
end;
procedure TMainForm.HelpTopicsExecute(Sender: TObject);
begin
//
end;
procedure TMainForm.HelpAboutExecute(Sender: TObject);
begin
with TAboutDialog.Create(Self) do
try
ShowModal;
finally
Free;
end;
end;
procedure TMainForm.ViewShowSpecialCharactersExecute(Sender: TObject);
begin
Settings.WriteBool('Editor', 'ShowSpecialChars', ViewShowSpecialCharacters.Checked);
DocumentFactory.ReadAllFromIni;
end;
procedure TMainForm.SearchReplaceNextExecute(Sender: TObject);
begin
if frFindText <> '' then
if not Document.ReplaceNext then
StatusMsg( PChar( Format(sStrings[siNotFound], [frFindText]) ), ErrorMsgColor, clWhite,
4000, False );
end;
procedure TMainForm.FindReplaceForm(Replace: Boolean);
begin
if Replace then
FindDialog := TReplaceDialog.Create(Self)
else
FindDialog := TFindDialog.Create(Self);
FindDialog.chkWhole.Checked := frWholeWords;
FindDialog.chkCase.Checked := frMatchCase;
FindDialog.chkRegExp.Checked := frRegExp;
FindDialog.chkFromCursor.Checked := frFromCursor;
FindDialog.chkInAll.Checked := frInAll;
FindDialog.rbUp.Checked := frDirUp;
FindDialog.rbDown.Checked := not frDirUp;
if Document.SelAvail then
FindDialog.chkSelOnly.Checked := True
else
FindDialog.chkSelOnly.Enabled := False;
if Replace then
with TReplaceDialog(FindDialog) do
begin
chkPrompt.Checked := frPrompt;
end;
FindDialog.Show;
end;
procedure TMainForm.StatusMsg(Msg: String; BackColor, TextColor: TColor;
TimeInterval: Integer; DoBeep: Boolean);
begin
if BackColor = -1 then
fStatusBarColor := clBtnFace
else
begin
fStatusBarColor := BackColor;
StatusBar.Panels[idMsgPanel].Style := psOwnerDraw;
end;
if TextColor = -1 then
fStatusBarTextColor := clWindowText
else
begin
fStatusBarTextColor := TextColor;
StatusBar.Panels[idMsgPanel].Style := psOwnerDraw;
end;
if TimeInterval <> -1 then
begin
tmrStatusBar.Interval := TimeInterval;
tmrStatusBar.Enabled := True;
end;
StatusBar.Panels[idMsgPanel].Text := Msg;
if DoBeep then
Beep;
end;
procedure TMainForm.StatusBarDrawPanel(StatusBar: TStatusBar;
Panel: TStatusPanel; const Rect: TRect);
begin
if Panel.Index = idMsgPanel then
begin
StatusBar.Canvas.Brush.Color := fStatusBarColor;
StatusBar.Canvas.FillRect(Rect);
StatusBar.Canvas.Font.Color := fStatusBarTextColor;
StatusBar.Canvas.TextOut(Rect.Left + 2, Rect.Top + 1, Panel.Text);
end;
end;
procedure TMainForm.tmrStatusBarTimer(Sender: TObject);
begin
StatusBar.Panels[idMsgPanel].Style := psText;
StatusMsg('');
tmrStatusBar.Enabled := False;
end;
procedure TMainForm.SetupDialogsFilter;
var
i: Integer;
Filter: String;
begin
i := 1;
while Settings.ValueExists('Filters', 'Filter' + IntToStr(i)) do
begin
Filter := Filter + Settings.ReadString('Filters', 'Filter' + IntToStr(i), '');
Inc(i);
end;
dlgOpen.Filter := Filter;
dlgSave.Filter := Filter;
end;
procedure TMainForm.FileWorkspaceOpenExecute(Sender: TObject);
begin
with dlgOpen do
begin
Filter := 'Mystix workspace (*.mws)|*.mws|';
if Execute then
begin
DocumentFactory.CloseAll;
OpenWorkspace(FileName);
end;
end;
end;
procedure TMainForm.FileWorkspaceSaveExecute(Sender: TObject);
var
i: Integer;
WorkspaceFiles: TStringList;
begin
if fWorkspaceFile = '' then
FileWorkspaceSaveAsExecute(nil)
else
begin
fWorkspaceModified := False;
WorkspaceFiles := TStringList.Create;
try
for i := 0 to DocumentFactory.Count - 1 do
WorkspaceFiles.Add(DocumentFactory.Documents[i].FileName);
WorkspaceFiles.SaveToFile(fWorkspaceFile);
finally
WorkspaceFiles.Free;
end;
end;
end;
procedure TMainForm.FileWorkspaceSaveAsExecute(Sender: TObject);
begin
with dlgSave do
begin
Filter := 'Mystix workspace (*.mws)|*.mws|';
DefaultExt := 'mws';
if Execute then
begin
fWorkspaceFile := FileName;
fWorkspaceModified := False;
Caption := Copy( ExtractFileName(fWorkspaceFile) , 1,
Length( ExtractFileName(fWorkspaceFile) ) - 4 ) + ' - Mystix';
FileWorkspaceSaveExecute(nil);
end;
end;
end;
procedure TMainForm.FileWorkspaceCloseExecute(Sender: TObject);
var
i: Integer;
const
sMessage = 'Do you want to save changes in current workspace?';
begin
if fWorkspaceModified then
if Application.MessageBox(sMessage, 'Confirm', MB_ICONQUESTION or MB_YESNO) = IDYES then
FileWorkspaceSaveExecute(nil);
for i := DocumentFactory.Count - 1 downto 0 do
if DocumentFactory.Documents[i].Saved then
DocumentFactory.Documents[i].Close;
MRUWorkspaces.Add(fWorkspaceFile);
UpdateMRUWorkspacesMenu;
fWorkspaceFile := '';
Caption := 'Mystix';
end;
procedure TMainForm.FileWorkspaceSaveUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := fWorkspaceFile <> '';
end;
procedure TMainForm.UpdateMRUWorkspacesMenu;
var
i: Integer;
MenuItem: TMenuItem;
begin
for i := miFileWorkspace.Count - 1 downto 5 do
miFileWorkspace.Delete(i);
for i := 0 to MRUWorkspaces.Count - 1 do
begin
MenuItem := TMenuItem.Create(Self);
MenuItem.Caption := '&' + IntToStr(i) + #32 + MRUWorkspaces[i];
MenuItem.Tag := i;
MenuItem.OnClick := RecentWorkspacesClick;
miFileWorkspace.Add(MenuItem);
end;
MenuItem := TMenuItem.Create(Self);
MenuItem.Caption := '-';
miFileWorkspace.Add(MenuItem);
MenuItem := TMenuItem.Create(Self);
MenuItem.Action := FileWorkspaceMRUClear;
miFileWorkspace.Add(MenuItem);
end;
procedure TMainForm.RecentWorkspacesClick(Sender: TObject);
begin
OpenWorkspace( PChar(MRUWorkspaces[(Sender as TMenuItem).Tag]) );
end;
procedure TMainForm.OpenWorkspace(FileName: String);
var
WorkspaceFiles: TStringList;
i: Integer;
begin
if DocumentFactory.CloseAll then
begin
fWorkspaceFile := FileName;
fWorkspaceModified := False;
Caption := Copy( ExtractFileName(fWorkspaceFile), 1,
Length( ExtractFileName(fWorkspaceFile) ) - 4 ) + ' - Mystix';
WorkspaceFiles := TStringList.Create;
try
WorkspaceFiles.LoadFromFile(fWorkspaceFile);
for i := 0 to WorkspaceFiles.Count - 1 do
DocumentFactory.Open( PChar(WorkspaceFiles[i]) );
finally
WorkspaceFiles.Free;
end;
end;
end;
procedure TMainForm.ViewCollapseCurrentExecute(Sender: TObject);
begin
Document.CollapseCurrent;
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
i, j: Integer;
begin
if fWorkspaceFile <> '' then
Settings.WriteString('General', 'LastWorkspace', fWorkspaceFile)
else
begin
Settings.EraseSection('LastOpenFiles');
j := 0;
for i := 0 to DocumentFactory.Count - 1 do
if DocumentFactory[i].Saved then
begin
Settings.WriteString('LastOpenFiles', IntToStr(j),
DocumentFactory[i].FileName);
Inc(j);
end;
end;
CanClose := DocumentFactory.CloseAll;
end;
procedure TMainForm.OnIdle(Sender: TObject; var Done: Boolean);
begin // Luciano
if GetKeyState(VK_NUMLOCK) = 1 then
StatusBar.Panels[idNumPanel].Text := 'NUM'
else
StatusBar.Panels[idNumPanel].Text := '';
if GetKeyState(VK_CAPITAL) = 1 then
StatusBar.Panels[idCapsPanel].Text := 'CAPS'
else
StatusBar.Panels[idCapsPanel].Text := '';
if GetKeyState(VK_SCROLL) = 1 then
StatusBar.Panels[idScrollPanel].Text := 'SCRL'
else
StatusBar.Panels[idScrollPanel].Text := '';
end;
procedure TMainForm.ReadLanguageData;
var
i: Integer;
Msg: String;
begin
with TMyIniFile.Create(Languages.Values[ActiveLanguage]) do
try
// Menus
for i := 0 to ComponentCount - 1 do
if Components[i] is TMenuItem then
with TMenuItem(Components[i]) do
if (Action = nil) and (Caption <> '-') then
Caption := ReadString(Self.Name,
Self.Components[i].Name + '.Caption', '');
// Action List
for i := 0 to actlMain.ActionCount - 1 do
TAction(actlMain.Actions[i]).Caption := ReadString(Name,
actlMain.Actions[i].Name + '.Caption', '');
// Const strings
for i := 0 to StringsCount do
sStrings[i] := ReadString('Strings', Format('String%d', [i]), '');
if ReadString('Language', 'Version', '') <> ProjectVersion then
begin
if sStrings[siWrongLangVersion] = '' then
Msg := 'Selected language is not up to date'
else
Msg := sStrings[siWrongLangVersion];
StatusMsg(Msg, ErrorMsgColor, clHighlightText, 4000, True);
end;
finally
Free;
end;
if FunctionListForm <> nil then
FunctionListForm.ReadLanguageData;
if OutputForm <> nil then
OutputForm.ReadLanguageData;
tbtnCollapse.Width := 36;
tbtnUncollapse.Width := 36;
UpdateDynamicMenus;
if Document <> nil then
Document.Activate;
end;
procedure TMainForm.UpdateLanguageMenu;
var
i: Integer;
MenuItem: TMenuItem;
begin
miViewLanguage.Clear;
for i := 0 to Languages.Count - 1 do
begin
MenuItem := TMenuItem.Create(Self);
MenuItem.Caption := Languages.Names[i];
MenuItem.RadioItem := True;
MenuItem.GroupIndex := 1;
MenuItem.Tag := i;
MenuItem.OnClick := LanguagesClick;
miViewLanguage.Add(MenuItem);
end;
end;
procedure TMainForm.LanguagesClick(Sender: TObject);
begin
ActiveLanguage := Languages.Names[(Sender as TMenuItem).Tag];
ReadLanguageData;
end;
procedure TMainForm.UpdateDynamicMenus;
begin
UpdateLanguageMenu;
UpdateFontMenu;
UpdateDocumentTypeMenu;
UpdateMRUFilesMenu;
UpdateMRUWorkspacesMenu;
end;
procedure TMainForm.UpdateFontMenu;
var
i: Integer;
begin
for i := 1 to 5 do
if Settings.ValueExists('EditorFonts', 'FontName' + IntToStr(i)) then
with TMenuItem( FindComponent('miEditorFont' + IntToStr(i)) ) do
begin
Caption := Format('%s, %d', [Settings.ReadString('EditorFonts', 'FontName' + IntToStr(i), ''),
Settings.ReadInteger('EditorFonts', 'FontSize' + IntToStr(i), 0)]);
Visible := True;
end
else
Break;
end;
procedure TMainForm.miViewLanguageClick(Sender: TObject);
var
i: Integer;
begin
for i := 0 to Languages.Count - 1 do
if SameText(ActiveLanguage, Languages.Names[i]) then
begin
miViewLanguage.Items[i].Checked := True;
Break;
end;
end;
procedure TMainForm.ViewFunctionListExecute(Sender: TObject);
begin
if GetFormVisible(FunctionListForm) then
HideDockForm(FunctionListForm)
else
ShowDockForm(FunctionListForm);
end;
procedure TMainForm.ViewOutputExecute(Sender: TObject);
begin
if GetFormVisible(OutputForm) then
HideDockForm(OutputForm)
else
ShowDockForm(OutputForm);
end;
procedure TMainForm.ViewFunctionListUpdate(Sender: TObject);
begin
(Sender as TAction).Checked := GetFormVisible(FunctionListForm);
end;
procedure TMainForm.ViewOutputUpdate(Sender: TObject);
begin
(Sender as TAction).Checked := GetFormVisible(OutputForm);
end;
procedure TMainForm.EditDeleteWordExecute(Sender: TObject);
begin
Document.DeleteWord;
end;
procedure TMainForm.EditDeleteLineExecute(Sender: TObject);
begin
Document.DeleteLine;
end;
procedure TMainForm.EditDeleteToEndOfWordExecute(Sender: TObject);
begin
Document.DeleteToEndOfWord;
end;
procedure TMainForm.EditDeleteToEndOfLineExecute(Sender: TObject);
begin
Document.DeleteToEndOfLine;
end;
procedure TMainForm.EditDeleteWordBackExecute(Sender: TObject);
begin
Document.DeleteWordBack;
end;
procedure TMainForm.EditSelectWordExecute(Sender: TObject);
begin
Document.SelectWord;
end;
procedure TMainForm.EditSelectLineExecute(Sender: TObject);
begin
Document.SelectLine;
end;
procedure TMainForm.EditColumnSelectExecute(Sender: TObject);
begin
Document.ColumnSelect;
end;
procedure TMainForm.EditColumnSelectUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := Document <> nil;
if (Sender as TAction).Enabled then
(Sender as TAction).Checked := Document.Editor.SelectionMode = smColumn;
end;
procedure TMainForm.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbRight then
JvMouseGesture.StartMouseGesture(X, Y);
end;
procedure TMainForm.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if JvMouseGesture.TrailActive then
JvMouseGesture.TrailMouseGesture(X, Y);
end;
procedure TMainForm.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if JvMouseGesture.TrailActive then
JvMouseGesture.EndMouseGesture;
if (Button = mbRight) and (Document <> nil) then
mnuEditor.Popup(X, Y);
end;
procedure TMainForm.JvMouseGestureMouseGestureDown(Sender: TObject);
var
Action: TAction;
begin
try
Action := TAction(FindComponent(Settings.ReadString('Mouse', 'GestureDown', '')));
if Action.Enabled then
Action.OnExecute(Action);
except
end;
end;
procedure TMainForm.JvMouseGestureMouseGestureLeft(Sender: TObject);
var
Action: TAction;
begin
try
Action := TAction(FindComponent(Settings.ReadString('Mouse', 'GestureLeft', '')));
if Action.Enabled then
Action.OnExecute(Action);
except
end;
end;
procedure TMainForm.JvMouseGestureMouseGestureRight(Sender: TObject);
var
Action: TAction;
begin
try
Action := TAction(FindComponent(Settings.ReadString('Mouse', 'GestureRight', '')));
if Action.Enabled then
Action.OnExecute(Action);
except
end;
end;
procedure TMainForm.JvMouseGestureMouseGestureUp(Sender: TObject);
var
Action: TAction;
begin
try
Action := TAction(FindComponent(Settings.ReadString('Mouse', 'GestureUp', '')));
if Action.Enabled then
Action.OnExecute(Action);
except
end;
end;
procedure TMainForm.tmrDelayCloseTimer(Sender: TObject);
begin
tmrDelayClose.Enabled := False;
Document.Close;
end;
procedure TMainForm.ReadSettings(FirstTime: Boolean = False);
var
i: Integer;
LanguageFiles: TStringList;
begin
with Settings do
begin
// Document types
if FirstTime then
DocTypes := TStringList.Create
else
DocTypes.Clear;
i := 1;
while ValueExists('DocumentTypes', 'DocumentTypeName' + IntToStr(i)) do
begin
DocTypes.Add( ReadString('DocumentTypes', 'DocumentTypeName' + IntToStr(i), 'Unknown') );
Inc(i);
end;
// Common document types
if FirstTime then
CommonDocTypes := TStringList.Create
else
CommonDocTypes.Clear;
// Read MRU
MRUFiles := TMRUList.Create(Settings, 10, 'MRUFiles');
UpdateMRUFilesMenu;
MRUWorkspaces := TMRUList.Create(Settings, 10, 'MRUWorkspaces');
UpdateMRUWorkspacesMenu;
MRUFindText := TMRUList.Create(Settings, 30, 'MRUFindText');
MRUReplaceText := TMRUList.Create(Settings, 30, 'MRUFReplaceText');
// Language related
ActiveLanguage := ReadString('General', 'ActiveLanguage', 'English');
Languages := TStringList.Create;
FileListInDir(AppPath + 'Languages' + PathSep, '*.ini', 0, LanguageFiles);
for i := 0 to LanguageFiles.Count - 1 do
with TMyIniFile.Create(LanguageFiles[i]) do
try
Languages.Add( ReadString('Language', 'Name', '') + '=' + LanguageFiles[i] );
finally
Free;
end;
Languages.Sort;
ReadLanguageData;
// Read general settings
if (FirstTime) and (ReadBool('General', 'SaveWindowPosition', False)) then
begin
WindowState := TWindowState(ReadInteger('General', 'WindowState', 2));
if WindowState = wsMinimized then
WindowState := wsMaximized;
if WindowState <> wsMaximized then
begin
Left := ReadInteger('General', 'WindowLeft', 0);
Top := ReadInteger('General', 'WindowTop', 0);
Width := ReadInteger('General', 'WindowWidth', Screen.Width div 2);
Height := ReadInteger('General', 'WindowHeight', Screen.Height div 2);
end;
end;
// View menu
ViewToolbar.Checked := ReadBool('General', 'ShowToolbar', True);
ViewStatusBar.Checked := ReadBool('General', 'ShowStatusBar', True);
// Read editor settings
ViewShowGutter.Checked := ReadBool('Editor', 'ShowGutter', True);
ViewShowLineNumbers.Checked := ReadBool('Editor', 'ShowLineNumbers', True);
ViewShowRightMargin.Checked := ReadBool('Editor', 'ShowRightMargin', True);
ViewShowSpecialCharacters.Checked := ReadBool('Editor', 'ShowSpecialChars', True);
ViewWordWrap.Checked := ReadBool('Editor', 'WordWrap', True);
ViewShowIndentGuides.Checked := ReadBool('Editor', 'ShowIndentGuides', True);
// Read open/save dialog filters
SetupDialogsFilter;
// Read shortcuts
for i := 0 to actlMain.ActionCount - 1 do
TAction(actlMain.Actions[i]).ShortCut := TextToShortCut(ReadString('Keyboard',
actlMain.Actions[i].Name, ''));
// Call some procedures to make changes visible
ViewToolbarExecute(ViewToolbar);
ViewStatusBarExecute(ViewStatusBar);
end;
end;
procedure TMainForm.UpdateDocumentTypeMenu;
var
i: Integer;
MenuItem: TMenuItem;
begin
miViewDocumentTypeMore.Clear;
for i := 0 to DocTypes.Count - 1 do
begin
MenuItem := TMenuItem.Create(Self);
MenuItem.Caption := DocTypes[i];
MenuItem.RadioItem := True;
Menuitem.Tag := i;
MenuItem.OnClick := DocumentTypeMoreClick;
miViewDocumentTypeMore.Add(MenuItem);
end;
i := 1;
while Settings.ValueExists('CommonDocumentTypes', 'DocumentType'
+ IntToStr(i)) do
begin
CommonDocTypes.Add( Settings.ReadString('CommonDocumentTypes',
'DocumentType' + IntToStr(i), 'Unknown' ) );
with TAction( FindComponent('ViewDocumentType' + IntToStr(i)) ) do
begin
Caption := CommonDocTypes[CommonDocTypes.Count - 1];
Visible := True;
end;
Inc(i);
end;
while i < 10 do
begin
TAction(FindComponent('ViewDocumentType' + IntToStr(i))).Visible := False;
Inc(i);
end;
end;
procedure TMainForm.SearchFunctionListExecute(Sender: TObject);
begin
Document.UpdateFunctionList;
end;
procedure TMainForm.WmMButtonUp(var Message: TMessage);
var
Action: TAction;
begin
try
Action := TAction(FindComponent(Settings.ReadString('Mouse', 'MiddleButton', '')));
if Action.Enabled then
Action.OnExecute(Action);
except end;
end;
procedure TMainForm.SaveAs(aDocument: TDocument);
var
DefExt, Buffer: String;
i, p: Integer;
begin
if aDocument = nil then
aDocument := Document;
SetupDialogsFilter;
with dlgSave do
begin
if aDocument.Saved then
FileName := ExtractFileName(aDocument.FileName)
else
FileName := aDocument.FileName;
if Execute then
begin
if ExtractFileExt(FileName) = '' then
begin
Buffer := Filter;
i := 1;
while i < FilterIndex do
begin
p := Pos('|*.', Buffer);
Delete(Buffer, 1, p + 2);
p := Pos('|', Buffer);
Delete(Buffer, 1, p);
Inc(i);
end;
p := Pos('|*.', Buffer);
Delete(Buffer, 1, p + 2);
i := 1;
while not (Buffer[i] in [';', '|']) do
Inc(i);
DefExt := Copy(Buffer, 1, i - 1);
if DefExt = '*' then
DefExt := Settings.ReadString('General', 'DefaultExtension', 'txt');
DefExt := '.' + DefExt;
end
else
DefExt := '';
aDocument.Saved := True;
aDocument.FileName := FileName + DefExt;
aDocument.Save;
end;
end;
end;
procedure TMainForm.FormShow(Sender: TObject);
var
i: Integer;
Names: TStringList;
begin
if Settings.ReadBool('General', 'ReopenLastWorkspace', False) then
OpenWorkspace(Settings.ReadString('General', 'LastWorkspace', ''))
else if Settings.ReadBool('General', 'ReopenLastFiles', False) then
begin
Names := TStringList.Create;
try
Settings.ReadSection('LastOpenFiles', Names);
for i := 0 to Names.Count - 1 do
DocumentFactory.Open(Settings.ReadString('LastOpenFiles', Names[i], ''));
finally
Names.Free;
end;
end
else if Settings.ReadBool('General', 'CreateEmptyDocument', False) then
DocumentFactory.New;
for i := 1 to ParamCount do
DocumentFactory.Open(ParamStr(i));
end;
procedure TMainForm.EditChangeCaseUpperExecute(Sender: TObject);
begin
Document.UpperCase;
end;
procedure TMainForm.EditChangeCaseLowerExecute(Sender: TObject);
begin
Document.LowerCase;
end;
procedure TMainForm.EditChangeCaseToggleExecute(Sender: TObject);
begin
Document.ToggleCase;
end;
procedure TMainForm.EditChangeCaseCapitalizeExecute(Sender: TObject);
begin
Document.Capitalize;
end;
procedure TMainForm.FileMRUClearExecute(Sender: TObject);
begin
MRUFiles.Clear;
UpdateMRUFilesMenu;
end;
procedure TMainForm.FileWorkspaceMRUClearExecute(Sender: TObject);
begin
MRUWorkspaces.Clear;
UpdateMRUWorkspacesMenu;
end;
procedure TMainForm.FileMRUOpenAllExecute(Sender: TObject);
var
i: Integer;
begin
for i := 0 to MRUFiles.Count - 1 do
DocumentFactory.Open(MRUFiles[i]);
end;
procedure TMainForm.WMOpenFile(var Message: TMessage);
var
FileName: PChar;
begin
SetForegroundWindow(Self.Handle);
BringWindowToTop(Self.Handle);
GetMem(FileName, 255);
GlobalGetAtomName(Message.wParam, FileName, 255);
DocumentFactory.Open(FileName);
GlobalDeleteAtom(Message.wParam);
FreeMem(FileName);
end;
end.
|
{
This unit is part of the Lua4Delphi Source Code
Copyright (C) 2009-2012, LaKraven Studios Ltd.
Copyright Protection Packet(s): L4D014
www.Lua4Delphi.com
www.LaKraven.com
--------------------------------------------------------------------
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.
--------------------------------------------------------------------
Unit: L4D.Lua.Common.pas
Released: 5th February 2012
Changelog:
5th February 2012:
- Released
}
unit L4D.Lua.Lua51;
interface
{$I Lua4Delphi.inc}
uses
L4D.Lua.Common, L4D.Lua.Intf;
const
{$REGION 'DLL name defines'}
{$IFDEF MSWINDOWS}
LUA_DLL = 'lua5.1.dll';
{$ENDIF}
{$IFDEF LINUX}
LUA_DLL = 'lua5.1.so';
{$ENDIF}
{$IFDEF MACOS}
LUA_DLL = 'liblua5.1.dylib';
{$ENDIF}
{$ENDREGION}
// Thread State
LUA_ERRERR = 5;
// Extra Error Code for 'LuaL_load'
LUA_ERRFILE = LUA_ERRERR + 1;
type
{
TLua51Base
- The Base Class for Lua 5.1
}
TLua51Base = class(TLuaCommon, ILua51Lib, ILua51Aux)
protected
{$REGION 'ILuaLibInterchange'}
procedure lua_callk(L: PLuaState; nargs, nresults, ctx: Integer; k: TLuaDelphiFunction); overload; override; // External "lua_call" in 5.1, External "lua_callk" in 5.2
function lua_compare(L: PLuaState; idx1, idx2, op: Integer): LongBool; overload; override; // "lua_equal" OR "lua_lessthan" in 5.1, External in 5.2
procedure lua_getglobal(L: PLuaState; name: PAnsiChar); overload; override; // "lua_getfield" in 5.1, External in 5.2
procedure lua_getuservalue(L: PLuaState; idx: Integer); overload; override; // "lua_getfenv" in 5.1, External in 5.2
function lua_load(L: PLuaState; reader: TLuaReaderFunction; dt: Pointer; Source, Mode: PAnsiChar): Integer; overload; override; // Extra parameter in 5.2 (mode)... 5.1 to pass "nil" to operate normally
function lua_pcallk(L: PLuaState; nargs, nresults, arrfunc, ctx: Integer; k: TLuaDelphiFunction): Integer; overload; override; // "lua_pcall" in 5.1, "lua_pcallk" in 5.2
function lua_rawlen(L: PLuaState; idx: Integer): Cardinal; overload; override; // "lua_objlen" in 5.1, External in 5.2
procedure lua_setglobal(L: PLuaState; name: PAnsiChar); overload; override; // "lua_setfield" in 5.1, External in 5.2
procedure lua_setuservalue(L: PLuaState; idx: Integer); overload; override; // "lua_getfenv" & "lua_setfenv" in 5.1, External in 5.2
function lua_tointegerx(L: PLuaState; idx: Integer; isnum: PInteger): Integer; overload; override; // In 5.2
function lua_tonumberx(L: PLuaState; idx: Integer; isnum: PInteger): Double; overload; override; // In 5.2
function lua_yieldk(L: PLuaState; nresults, ctx: Integer; k: TLuaDelphiFunction): Integer; overload; override; // "lua_yield" in 5.1, "lua_yieldk" in 5.2
{$ENDREGION}
{$REGION 'ILuaAuxInterchange'}
function luaL_loadbufferx(L: PLuaState; buff: PAnsiChar; sz: Cardinal; name, mode: PAnsiChar): Integer; overload; override;
function luaL_loadfilex(L: PLuaState; filename, mode: PAnsiChar): Integer; overload; override;
{$ENDREGION}
{$REGION 'ILua51Aux'}
function luaL_findtable(L: PLuaState; idx: Integer; const fname: PAnsiChar; szhint: Integer): PAnsiChar; overload; virtual; abstract;
procedure luaL_openlib(L: PLuaState; const libname: PAnsiChar; const lr: PLuaLReg; nup: Integer); overload; virtual; abstract;
function luaL_prepbuffer(B: PLuaLBuffer): PAnsiChar; overload; virtual; abstract;
function luaL_typerror(L: PLuaState; narg: Integer; const tname: PAnsiChar): Integer; overload; virtual; abstract;
{$ENDREGION}
end;
{
TLua51Common
- The COMMON PARENT ANCESTOR for Lua 5.1 classes.
- Inherited by TLua51Static, TLua51Dynamic, TLua51Embedded
}
TLua51Common = class(TLua51Base, ILua51LibLocal, ILua51AuxLocal)
public
{$REGION 'ILua51AuxLocal'}
function luaL_findtable(idx: Integer; const fname: PAnsiChar; szhint: Integer): PAnsiChar; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_loadbuffer(const buff: PAnsiChar; sz: Cardinal; const name: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_loadfile(const filename: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_openlib(const libname: PAnsiChar; const lr: PLuaLReg; nup: Integer); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
procedure luaL_register(const libname: PAnsiChar; const lr: PLuaLReg); overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
function luaL_typerror(narg: Integer; const tname: PAnsiChar): Integer; overload; {$IFDEF L4D_USE_INLINE}inline;{$ENDIF}
{$ENDREGION}
end;
implementation
{$REGION 'Lua 5.1 Base Type'}
{ TLua51Base }
function TLua51Base.luaL_loadbufferx(L: PLuaState; buff: PAnsiChar; sz: Cardinal; name, mode: PAnsiChar): Integer;
begin
Result := luaL_loadbuffer(L, buff, sz, name);
end;
function TLua51Base.luaL_loadfilex(L: PLuaState; filename, mode: PAnsiChar): Integer;
begin
Result := luaL_loadfile(L, filename);
end;
procedure TLua51Base.lua_callk(L: PLuaState; nargs, nresults, ctx: Integer; k: TLuaDelphiFunction);
begin
lua_call(L, nargs, nresults);
end;
function TLua51Base.lua_compare(L: PLuaState; idx1, idx2, op: Integer): LongBool;
begin
case op of
LUA_OPEQ: Result := lua_equal(L, idx1, idx2);
LUA_OPLT: Result := lua_lessthan(L, idx1, idx2);
LUA_OPLE: Result := (lua_equal(L, idx1, idx2) or lua_lessthan(L, idx1, idx2));
else
Result := False;
end;
end;
procedure TLua51Base.lua_getglobal(L: PLuaState; name: PAnsiChar);
begin
lua_getfield(L, LUA_GLOBALSINDEX, name);
end;
procedure TLua51Base.lua_getuservalue(L: PLuaState; idx: Integer);
begin
lua_getfenv(L, idx);
end;
function TLua51Base.lua_load(L: PLuaState; reader: TLuaReaderFunction; dt: Pointer; Source, Mode: PAnsiChar): Integer;
begin
Result := lua_load(L, reader, dt, source);
end;
function TLua51Base.lua_pcallk(L: PLuaState; nargs, nresults, arrfunc, ctx: Integer; k: TLuaDelphiFunction): Integer;
begin
Result := lua_pcall(L, nargs, nresults, arrfunc);
end;
function TLua51Base.lua_rawlen(L: PLuaState; idx: Integer): Cardinal;
begin
Result := lua_objlen(L, idx);
end;
procedure TLua51Base.lua_setglobal(L: PLuaState; name: PAnsiChar);
begin
lua_setfield(L, LUA_GLOBALSINDEX, name);
end;
procedure TLua51Base.lua_setuservalue(L: PLuaState; idx: Integer);
begin
lua_setfenv(L, idx);
end;
function TLua51Base.lua_tointegerx(L: PLuaState; idx: Integer; isnum: PInteger): Integer;
begin
Result := lua_tointeger(L, idx);
end;
function TLua51Base.lua_tonumberx(L: PLuaState; idx: Integer; isnum: PInteger): Double;
begin
Result := lua_tonumber(L, idx);
end;
function TLua51Base.lua_yieldk(L: PLuaState; nresults, ctx: Integer; k: TLuaDelphiFunction): Integer;
begin
Result := lua_yield(L, nresults);
end;
{$ENDREGION}
{$REGION 'Lua 5.1 Common Type'}
{ TLua51Common }
function TLua51Common.luaL_findtable(idx: Integer; const fname: PAnsiChar; szhint: Integer): PAnsiChar;
begin
Result := luaL_findtable(FLuaState, idx, fname, szhint);
end;
function TLua51Common.luaL_loadbuffer(const buff: PAnsiChar; sz: Cardinal; const name: PAnsiChar): Integer;
begin
Result := luaL_loadbuffer(FLuaState, buff, sz, name);
end;
function TLua51Common.luaL_loadfile(const filename: PAnsiChar): Integer;
begin
Result := luaL_loadfile(FLuaState, filename);
end;
procedure TLua51Common.luaL_openlib(const libname: PAnsiChar; const lr: PLuaLReg; nup: Integer);
begin
luaL_openlib(FLuaState, libname, lr, nup);
end;
procedure TLua51Common.luaL_register(const libname: PAnsiChar; const lr: PLuaLReg);
begin
luaL_register(FLuaState, libname, lr);
end;
function TLua51Common.luaL_typerror(narg: Integer; const tname: PAnsiChar): Integer;
begin
Result := luaL_typerror(FLuaState, narg, tname);
end;
{$ENDREGION}
end.
|
(*Ejercicio 19
No es posible utilizar una computadora para generar números aleatorios genuinos ya que es preciso
utilizar un algoritmo para generar los números, lo que implica que es posible predecir los números
generados. Lo que sí pueden hacer las computadoras es generar números seudoaleatorios (números que,
estadísticamente, parecen ser aleatorios). Una técnica antigua que no produce buenos resultados se llama método
del cuadrado medio. Funciona así : dado un número a, para generar el siguiente número de la secuencia se
extraen los dígitos que están en la posición de las decenas y las centenas de a^2. Por ejemplo, si a es 53,
entonces a^2 es 2809, y el siguiente número seudoaleatorio será 80. Se ve que el siguiente número
seudoaleatorio a 80 es 40. Si se continúa este proceso se obtiene 60, 60, 60, ....
Escriba un programa en Pascal que lea un entero de dos dígitos y determine el siguiente número
seudoaleatorio que se generaría si se usara el método del cuadrado medio.
Suponga que la entrada consta de una sola línea que contiene al entero de dos dígitos.
Exhiba el número de dos dígitos original, el cuadrado de este entero, y el siguiente número,
todos con etiquetas apropiadas.
Ejemplo de entrada : 53.
Ejemplo de salida : Numero introducido = 53
Cuadrado del numero = 2809
Siguiente numero seudoaleatorio = 80. *)
program ejercicio18;
var entrada, cuadrado, m, d, c, uevo : integer;
begin
writeln('Ingrese un numero de dos digitos.');
read(entrada);
cuadrado := sqr(entrada);
m := cuadrado div 1000;
c := (cuadrado div 100) - (m*10);
d := (cuadrado div 10)- (m*100)-(c*10);
nuevo := (c*10)+d;
writeln('Numero introducido = ',entrada);
writeln('Cuadrado del numero = ',cuadrado);
writeln('Siguiente numero seudoaleatorio = ',nuevo);
end.
|
(*!------------------------------------------------------------
* Fano CLI Application (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano-cli
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano-cli/blob/master/LICENSE (MIT)
*------------------------------------------------------------- *)
unit CreateProjectTaskFactoryImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
TaskIntf,
TaskFactoryIntf,
TextFileCreatorIntf,
ContentModifierIntf;
type
(*!--------------------------------------
* Factory class for create project task
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*---------------------------------------*)
TCreateProjectTaskFactory = class(TInterfacedObject, ITaskFactory)
protected
function buildProjectTask(
const textFileCreator : ITextFileCreator;
const contentModifier : IContentModifier
) : ITask; virtual;
public
function build() : ITask; virtual;
end;
implementation
uses
TextFileCreatorImpl,
ContentModifierImpl,
DirectoryCreatorImpl,
CreateDirTaskImpl,
CreateAppConfigsTaskImpl,
CreateAdditionalFilesTaskImpl,
CreateShellScriptsTaskImpl,
CreateAppBootstrapTaskImpl,
InitGitRepoTaskImpl,
CommitGitRepoTaskImpl,
CreateProjectTaskImpl,
InvRunCheckTaskImpl,
ChangeDirTaskImpl,
EmptyDirCheckTaskImpl;
function TCreateProjectTaskFactory.buildProjectTask(
const textFileCreator : ITextFileCreator;
const contentModifier : IContentModifier
) : ITask;
begin
result := TCreateProjectTask.create(
TCreateDirTask.create(TDirectoryCreator.create()),
TCreateShellScriptsTask.create(textFileCreator, contentModifier),
TCreateAppConfigsTask.create(textFileCreator, contentModifier),
TCreateAdditionalFilesTask.create(textFileCreator, contentModifier),
TCreateAppBootstrapTask.create(textFileCreator, contentModifier),
TInitGitRepoTask.create(TCommitGitRepoTask.create())
);
end;
function TCreateProjectTaskFactory.build() : ITask;
var textFileCreator : ITextFileCreator;
contentModifier : IContentModifier;
createPrjTask : ITask;
chdirTask : ITask;
invRunCheckTask : ITask;
begin
//TODO: refactor as this is similar to TCreateProjectFastCgiTaskFactory
//or TCreateProjectScgiTaskFactory
textFileCreator := TTextFileCreator.create();
contentModifier := TContentModifier.create();
createPrjTask := buildProjectTask(textFileCreator, contentModifier);
//wrap with change dir task so active directory can be changed with --cd parameter
chDirTask := TChangeDirTask.create(createPrjTask);
//protect to avoid accidentally creating another project inside Fano-CLI
//project directory structure
invRunCheckTask := TInvRunCheckTask.create(chDirTask);
//protect to avoid accidentally creating project inside
//existing and non empty directory
result := TEmptyDirCheckTask.create(invRunCheckTask);
end;
end.
|
unit FIToolkit.Config.Exceptions;
interface
uses
FIToolkit.Commons.Exceptions;
type
EConfigException = class abstract (ECustomException);
{ FixInsight options exceptions }
EFixInsightOptionsException = class abstract (EConfigException);
EFIOEmptyOutputFileName = class (EFixInsightOptionsException);
EFIOInvalidOutputFileName = class (EFixInsightOptionsException);
EFIOOutputDirectoryNotFound = class (EFixInsightOptionsException);
EFIOProjectFileNotFound = class (EFixInsightOptionsException);
EFIOSettingsFileNotFound = class (EFixInsightOptionsException);
{ Config data exceptions }
EConfigDataException = class abstract (EConfigException);
ECDCustomTemplateFileNotFound = class (EConfigDataException);
ECDFixInsightExeNotFound = class (EConfigDataException);
ECDInputFileNotFound = class (EConfigDataException);
ECDInvalidExcludeProjectPattern = class (EConfigDataException);
ECDInvalidExcludeUnitPattern = class (EConfigDataException);
ECDInvalidNonZeroExitCodeMsgCount = class (EConfigDataException);
ECDInvalidOutputFileName = class (EConfigDataException);
ECDOutputDirectoryNotFound = class (EConfigDataException);
ECDSnippetSizeOutOfRange = class (EConfigDataException);
ECDTempDirectoryNotFound = class (EConfigDataException);
implementation
uses
FIToolkit.Config.Consts;
initialization
RegisterExceptionMessage(EFIOEmptyOutputFileName, RSFIOEmptyOutputFileName);
RegisterExceptionMessage(EFIOInvalidOutputFileName, RSFIOInvalidOutputFileName);
RegisterExceptionMessage(EFIOOutputDirectoryNotFound, RSFIOOutputDirectoryNotFound);
RegisterExceptionMessage(EFIOProjectFileNotFound, RSFIOProjectFileNotFound);
RegisterExceptionMessage(EFIOSettingsFileNotFound, RSFIOSettingsFileNotFound);
RegisterExceptionMessage(ECDCustomTemplateFileNotFound, RSCDCustomTemplateFileNotFound);
RegisterExceptionMessage(ECDFixInsightExeNotFound, RSCDFixInsightExeNotFound);
RegisterExceptionMessage(ECDInputFileNotFound, RSCDInputFileNotFound);
RegisterExceptionMessage(ECDInvalidExcludeProjectPattern, RSCDInvalidExcludeProjectPattern);
RegisterExceptionMessage(ECDInvalidExcludeUnitPattern, RSCDInvalidExcludeUnitPattern);
RegisterExceptionMessage(ECDInvalidNonZeroExitCodeMsgCount, RSCDInvalidNonZeroExitCodeMsgCount);
RegisterExceptionMessage(ECDInvalidOutputFileName, RSCDInvalidOutputFileName);
RegisterExceptionMessage(ECDOutputDirectoryNotFound, RSCDOutputDirectoryNotFound);
RegisterExceptionMessage(ECDSnippetSizeOutOfRange, RSCDSnippetSizeOutOfRange);
RegisterExceptionMessage(ECDTempDirectoryNotFound, RSCDTempDirectoryNotFound);
end.
|
unit Registry;
{
LLCL - FPC/Lazarus Light LCL
based upon
LVCL - Very LIGHT VCL
----------------------------
This file is a part of the Light LCL (LLCL).
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
This Source Code Form is "Incompatible With Secondary Licenses",
as defined by the Mozilla Public License, v. 2.0.
Copyright (c) 2015-2016 ChrisF
Based upon the Very LIGHT VCL (LVCL):
Copyright (c) 2008 Arnaud Bouchez - http://bouchez.info
Portions Copyright (c) 2001 Paul Toth - http://tothpaul.free.fr
Version 1.02:
* File creation.
* TRegistry implemented
}
{$IFDEF FPC}
{$define LLCL_FPC_MODESECTION}
{$I LLCLFPCInc.inc} // For mode
{$undef LLCL_FPC_MODESECTION}
{$ENDIF}
{$I LLCLOptions.inc} // Options
//------------------------------------------------------------------------------
interface
uses
LLCLOSInt, Windows,
Classes;
type
TRegKeyInfo = record
NumSubKeys: integer;
MaxSubKeyLen: integer;
NumValues: integer;
MaxValueLen: integer;
MaxDataLen: integer;
{$IFDEF FPC}
FileTime: TDateTime;
{$ELSE FPC}
FileTime: TFileTime;
{$ENDIF FPC}
end;
TRegDataType = (rdUnknown, rdString, rdExpandString, rdBinary, rdInteger); // (Keep order)
TRegDataInfo = record
RegData: TRegDataType;
DataSize: integer;
end;
type
TRegistry = class(TObject)
private
fRootKey: HKEY;
fAccess: longword;
fCurrentKey: HKEY;
procedure SetRootKey(Value: HKEY);
procedure NormKey(const Key: string; var BaseKey: HKEY; var SubKey: string);
function OpenCreateKey(const Key: string; CanCreate: boolean; WithAccess: longword; var ResultKey: HKey): boolean;
function GetInfosKey(var Value: TRegKeyInfo): boolean;
procedure GetKeyValueNames(Strings: TStrings; IsForKeys: boolean);
function ReadData(const ValueName: string; var DataType: TRegDataType; Data: pointer; var DataSize: integer): boolean;
procedure WriteData(const ValueName: string; DataType: TRegDataType; Data: pointer; DataSize: integer);
public
constructor Create; overload;
destructor Destroy; override;
function OpenKey(const Key: string; CanCreate: boolean): boolean;
function OpenKeyReadOnly(const Key: String): boolean;
function CreateKey(const Key: string): boolean;
function DeleteKey(const Key: string): boolean;
procedure CloseKey;
function KeyExists(const Key: string): boolean;
function GetKeyInfo(var Value: TRegKeyInfo): boolean;
procedure GetKeyNames(Strings: TStrings);
function ValueExists(const Name: string): boolean;
function GetDataInfo(const ValueName: string; var Value: TRegDataInfo): boolean;
procedure GetValueNames(Strings: TStrings);
function DeleteValue(const Name: string): boolean;
function ReadString(const Name: string): string;
procedure WriteString(const Name, Value: string);
function ReadInteger(const Name: string): integer;
procedure WriteInteger(const Name: string; Value: integer);
function ReadBool(const Name: string): boolean;
procedure WriteBool(const Name: string; Value: boolean);
function ReadDate(const Name: string): TDateTime;
procedure WriteDate(const Name: string; Value: TDateTime);
function ReadBinaryData(const Name: string; var Buffer; BufSize: integer): integer;
procedure WriteBinaryData(const Name: string; var Buffer; BufSize: integer);
property Access: longword read fAccess write fAccess;
property CurrentKey: HKEY read fCurrentKey;
property RootKey: HKEY read fRootKey write SetRootKey;
end;
//------------------------------------------------------------------------------
implementation
uses
SysUtils;
{$IFDEF FPC}
{$PUSH} {$HINTS OFF}
{$ENDIF}
{$IFNDEF FPC}
const
KEY_WOW64_64KEY = $0100; // Absent in old versions of Delphi
KEY_WOW64_32KEY = $0200; //
{$ENDIF}
//------------------------------------------------------------------------------
{ TRegistry }
constructor TRegistry.Create;
begin
inherited;
fRootKey := HKEY_CURRENT_USER;
fAccess := KEY_ALL_ACCESS;
fCurrentKey := 0;
end;
destructor TRegistry.Destroy;
begin
CloseKey;
inherited;
end;
procedure TRegistry.SetRootKey(Value: HKEY);
begin
if fRootKey<>Value then
begin
CloseKey;
fRootKey := Value;
end;
end;
procedure TRegistry.NormKey(const Key: string; var BaseKey: HKEY; var SubKey: string);
begin
if Pos('\', Key)=1 then
begin
SubKey := Copy(Key, 2, length(Key) - 1);
BaseKey := fRootKey;
end
else
begin
SubKey := Key;
if fCurrentKey=0 then
BaseKey := fRootKey
else
BaseKey := fCurrentKey;
end;
end;
function TRegistry.OpenCreateKey(const Key: string; CanCreate: boolean; WithAccess: longword; var ResultKey: HKey): boolean;
var BaseKey: HKEY;
var SubKey: string;
var Disposition: longword;
begin
NormKey(Key, BaseKey, SubKey);
if CanCreate then
result := (LLCLS_REG_RegCreateKeyEx(BaseKey, SubKey, 0, nil, REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS, nil, ResultKey, @Disposition) = 0)
else
result := (LLCLS_REG_RegOpenKeyEx(BaseKey, SubKey, 0, WithAccess, ResultKey) = 0);
end;
function TRegistry.GetInfosKey(var Value: TRegKeyInfo): boolean;
{$IFDEF FPC}
var TmpFileTime: TFileTime;
var TmpSystemTime: TSystemTime;
{$ENDIF}
begin
FillChar(Value, SizeOf(Value), 0);
{$IFDEF FPC}
result := (LLCLS_REG_RegQueryInfoKey(fCurrentKey, nil, nil, nil, @Value.NumSubKeys, @Value.MaxSubKeyLen,
nil, @Value.NumValues, @Value.MaxValueLen, @Value.MaxDataLen, nil, @TmpFileTime) = 0);
if result then
if LLCL_FileTimeToSystemTime(TmpFileTime, TmpSystemTime) then
Value.FileTime := SystemTimeToDateTime(TmpSystemTime);
{$ELSE FPC}
result := (LLCLS_REG_RegQueryInfoKey(fCurrentKey, nil, nil, nil, @Value.NumSubKeys, @Value.MaxSubKeyLen,
nil, @Value.NumValues, @Value.MaxValueLen, @Value.MaxDataLen, nil, @Value.FileTime) = 0);
{$ENDIF}
end;
procedure TRegistry.GetKeyValueNames(Strings: TStrings; IsForKeys: boolean);
var InfosKey: TRegKeyInfo;
var Len: integer;
var s: string;
var i, j, k, l: integer;
begin
Strings.Clear;
if GetInfosKey(InfosKey) then
begin
if IsForKeys then
begin
k := InfosKey.MaxSubKeyLen;
j := InfosKey.NumSubKeys;
end
else
begin
k := InfosKey.MaxValueLen;
j := InfosKey.NumValues;
end;
Inc(k);
SetLength(S, k);
for i := 0 to (j - 1) do
begin
Len := k;
if IsForKeys then
l := LLCLS_REG_RegEnumKeyEx(fCurrentKey, i, s, @Len, nil, nil, nil, nil)
else
l := LLCLS_REG_RegEnumValue(fCurrentKey, i, s, @Len, nil, nil, nil, nil);
if l=0 then
Strings.Add(s);
end;
end;
end;
function TRegistry.ReadData(const ValueName: string; var DataType: TRegDataType; Data: pointer; var DataSize: integer): boolean;
begin
DataType := rdUnknown;
result := (LLCLS_REG_RegQueryValueEx(fCurrentKey, ValueName, nil, @DataType, Data, @DataSize) = 0);
end;
procedure TRegistry.WriteData(const ValueName: string; DataType: TRegDataType; Data: pointer; DataSize: integer);
begin
if LLCLS_REG_RegSetValueEx(fCurrentKey, ValueName, 0, longword(DataType), Data, DataSize)<>0 then
raise Exception.CreateFmt(LLCL_STR_REGI_WRITEDATAERR, [ValueName]);
end;
procedure TRegistry.CloseKey;
begin
if fCurrentKey<>0 then
LLCL_RegCloseKey(fCurrentKey);
fCurrentKey := 0;
end;
function TRegistry.OpenKey(const Key: string; CanCreate: boolean): boolean;
var RKey: HKEY;
begin
result := OpenCreateKey(Key, CanCreate, fAccess, RKey);
if result and (RKey<>fCurrentKey) then
begin
CloseKey;
fCurrentKey := RKey;
end;
end;
function TRegistry.OpenKeyReadOnly(const Key: String): boolean;
var SaveAccess: longword;
begin
SaveAccess := fAccess;
fAccess := KEY_READ or (SaveAccess and (KEY_WOW64_64KEY or KEY_WOW64_32KEY)); // Old versions of Delphi don't have KEY_WOW64_xxxx
result := OpenKey(Key, false);
fAccess := SaveAccess;
end;
function TRegistry.CreateKey(const Key: string): boolean;
var RKey: HKEY;
begin
result := OpenCreateKey(Key, true, 0, RKey); // Access not used for creation
if result then
LLCL_RegCloseKey(RKey)
else
raise Exception.CreateFmt(LLCL_STR_REGI_CREATEKEYERR, [Key]);
end;
function TRegistry.DeleteKey(const Key: string): boolean;
var BaseKey: HKEY;
var SubKey: string;
begin
NormKey(Key, BaseKey, SubKey);
result := (LLCLS_REG_RegDeleteKey(BaseKey, SubKey) = 0);
end;
function TRegistry.KeyExists(const Key: string): boolean;
var RKey: HKEY;
begin
result := OpenCreateKey(Key, false, STANDARD_RIGHTS_READ or KEY_QUERY_VALUE or KEY_ENUMERATE_SUB_KEYS
or (fAccess and (KEY_WOW64_64KEY or KEY_WOW64_32KEY)), RKey); // Old versions of Delphi don't have KEY_WOW64_xxxx
if result then
LLCL_RegCloseKey(RKey);
end;
function TRegistry.GetKeyInfo(var Value: TRegKeyInfo): boolean;
begin
result := GetInfosKey(Value);
end;
procedure TRegistry.GetKeyNames(Strings: TStrings);
begin
GetKeyValueNames(Strings, true);
end;
function TRegistry.ValueExists(const Name: string): boolean;
var DummyRDI: TRegDataInfo;
begin
result := GetDataInfo(Name, DummyRDI);
end;
function TRegistry.GetDataInfo(const ValueName: string; var Value: TRegDataInfo): boolean;
begin
FillChar(Value, SizeOf(Value), 0);
result := (LLCLS_REG_RegQueryValueEx(fCurrentKey, ValueName, nil, @Value.RegData, nil, @Value.DataSize) = 0);
end;
procedure TRegistry.GetValueNames(Strings: TStrings);
begin
GetKeyValueNames(Strings, false);
end;
function TRegistry.DeleteValue(const Name: string): boolean;
begin
result := (LLCLS_REG_RegDeleteValue(fCurrentKey, Name) = 0);
end;
function TRegistry.ReadString(const Name: string): string;
var DataType: TRegDataType;
begin
DataType := rdUnknown;
if not ((LLCLS_REG_RegQueryStringValue(fCurrentKey, Name, @DataType, result) = 0) and (DataType in [rdString,rdExpandString])) then
raise Exception.CreateFmt(LLCL_STR_REGI_READDATAERR, [Name]);
end;
procedure TRegistry.WriteString(const Name, Value: string);
var pData: pointer;
var Len: cardinal;
begin
pData := LLCLS_REG_SetTextPtr(Value, Len);
WriteData(Name, rdString, pData, Len);
FreeMem(pData);
end;
function TRegistry.ReadInteger(const Name: string): integer;
var InfosData: TRegDataInfo;
begin
InfosData.DataSize := SizeOf(integer);
if not (ReadData(Name, InfosData.RegData, @result, InfosData.DataSize) and (InfosData.RegData=rdInteger)) then
raise Exception.CreateFmt(LLCL_STR_REGI_READDATAERR, [Name]);
end;
procedure TRegistry.WriteInteger(const Name: string; Value: integer);
begin
WriteData(Name, rdInteger, @Value, SizeOf(integer));
end;
function TRegistry.ReadBool(const Name: string): boolean;
begin
result := (ReadInteger(Name)<>0);
end;
procedure TRegistry.WriteBool(const Name: string; Value: boolean);
begin
WriteInteger(Name, ord(Value));
end;
function TRegistry.ReadDate(const Name: string): TDateTime;
begin
ReadBinaryData(Name, result, SizeOf(TDateTime));
end;
procedure TRegistry.WriteDate(const Name: string; Value: TDateTime);
begin
WriteBinaryData(Name, Value, SizeOf(TDateTime));
end;
function TRegistry.ReadBinaryData(const Name: string; var Buffer; BufSize: integer): integer;
var DataType: TRegDataType;
begin
result := BufSize;
if not (ReadData(Name, DataType, @Buffer, result) and (DataType=rdBinary)) then
raise Exception.CreateFmt(LLCL_STR_REGI_READDATAERR, [Name]);
end;
procedure TRegistry.WriteBinaryData(const Name: string; var Buffer; BufSize: integer);
begin
WriteData(Name, rdBinary, @Buffer, BufSize);
end;
//------------------------------------------------------------------------------
{$IFDEF FPC}
{$POP}
{$ENDIF}
end.
|
unit Router4D.Utils;
{$I Router4D.inc}
interface
uses
System.Rtti,
Router4D.Props,
SysUtils,
Classes;
type
TRouter4DUtils = class
private
public
class function CreateInstance<T> : T;
end;
TNotifyEventWrapper = class(TComponent)
private
FProc: TProc<TObject, String>;
FAux : String;
public
constructor Create(Owner: TComponent; Proc: TProc<TObject, String>; Aux : String = ''); reintroduce;
class function AnonProc2NotifyEvent(Owner: TComponent; Proc: TProc<TObject, String>; Aux : String = ''): TNotifyEvent;
published
procedure Event(Sender: TObject);
end;
implementation
{ TRouter4DUtils }
class function TRouter4DUtils.CreateInstance<T>: T;
var
AValue: TValue;
ctx: TRttiContext;
rType: TRttiType;
AMethCreate: TRttiMethod;
instanceType: TRttiInstanceType;
begin
ctx := TRttiContext.Create;
rType := ctx.GetType(TypeInfo(T));
for AMethCreate in rType.GetMethods do
begin
if (AMethCreate.IsConstructor) and (Length(AMethCreate.GetParameters) = 1) then
begin
instanceType := rType.AsInstance;
AValue := AMethCreate.Invoke(instanceType.MetaclassType, [nil]);
Result := AValue.AsType<T>;
try
GlobalEventBus.RegisterSubscriber(AValue.AsType<TObject>);
except
end;
Exit;
end;
end;
end;
{ TNotifyEventWrapper }
class function TNotifyEventWrapper.AnonProc2NotifyEvent(Owner: TComponent; Proc: TProc<TObject, String>; Aux : String = ''): TNotifyEvent;
begin
Result := Self.Create(Owner, Proc, Aux).Event;
end;
constructor TNotifyEventWrapper.Create(Owner: TComponent; Proc: TProc<TObject, String>; Aux : String = '');
begin
inherited Create(Owner);
FProc := Proc;
FAux := Aux;
end;
procedure TNotifyEventWrapper.Event(Sender: TObject);
begin
FProc(Sender, FAux);
end;
end.
|
unit MasterMind.Presenter.Tests;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
interface
uses
Classes, SysUtils, fpcunit, testregistry, MasterMind.API, MasterMind.View.Mock, MasterMind.Evaluator.Mock;
type
TTestMasterMindPresenter = class(TTestCase)
private
FPresenter: IGamePresenter;
FViewMock: IGameViewMock;
FShowGuessesCallCounter: Integer;
FStartRequestGuessCallCounter: Integer;
FEvaluatorMock: IGuessEvaluatorMock;
FCurrentlyGuessedCode: TMasterMindCode;
FShowPlayerWinsCallCounter: Integer;
FShowPlayerLosesCallCounter: Integer;
procedure CheckShowGuessesIsCalledWithEmptyPreviousGuesses(const PreviousGuesses: TPreviousGuesses);
procedure CheckShowGuessesIsCalledWithOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult(const PreviousGuesses: TPreviousGuesses);
procedure CheckShowPlayerWinsIsCalledWithOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult(const PreviousGuesses: TPreviousGuesses);
procedure CheckShowPlayerLosesIsCalledWithTwelvePreviousGuesses(const PreviousGuesses: TPreviousGuesses);
procedure CheckStartRequestGuessIsCalledWithEmptyPreviousGuesses(const PreviousGuesses: TPreviousGuesses);
procedure CheckStartRequestGuessIsCalledWithPreviousGuess(const PreviousGuesses: TPreviousGuesses);
procedure NoOperation(const PreviousGuesses: TPreviousGuesses);
procedure CheckPreviousGuessesIsEmpty(const PreviousGuesses: TPreviousGuesses);
procedure CheckShowGuessWasCalledOneTime;
procedure CheckShowPlayerWinsCalledOneTime;
procedure CheckShowPlayerLosesCalledOneTime;
procedure CheckOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult(const PreviousGuesses: TPreviousGuesses; const MethodName: String);
procedure CheckStartRequestGuessWasCalledOneTime;
procedure CheckShowGuessWasCalledNTimes(const N: Integer);
protected
procedure Setup; override;
published
procedure TestNewGameClearsTheBoardAndSelectsANewCodeAndStartsRequestNewGuess;
procedure TestTakeGuessEvaluatesAndAddsWrongGuessToTheVisibleBoard;
procedure TestTakeGuessCallsShowPlayerWinsMessageWhenGuessWasCorrect;
procedure TestTakeTwelveWrongGuessesCallsShowPlayerLosesMessage;
end;
implementation
uses
MasterMind.Presenter, MasterMind.CodeSelector.Mock, MasterMind.TestHelper, EnumHelper;
procedure TTestMasterMindPresenter.Setup;
var
CodeSelector: ICodeSelector;
View: IGameView;
Evaluator: IGuessEvaluator;
begin
CodeSelector := TMasterMindCodeSelectorMock.Create(MakeCode([mmcGreen, mmcGreen, mmcRed, mmcRed]));
Evaluator := TMasterMindGuessEvaluatorMock.Create;
FEvaluatorMock := Evaluator as IGuessEvaluatorMock;
View := TMasterMindViewMock.Create;
FViewMock := View as IGameViewMock;
FPresenter := TMasterMindPresenter.Create(CodeSelector, Evaluator, View);
end;
procedure TTestMasterMindPresenter.CheckShowGuessesIsCalledWithEmptyPreviousGuesses(const PreviousGuesses: TPreviousGuesses);
begin
Inc(FShowGuessesCallCounter);
CheckPreviousGuessesIsEmpty(PreviousGuesses);
end;
procedure TTestMasterMindPresenter.CheckStartRequestGuessIsCalledWithEmptyPreviousGuesses(const PreviousGuesses: TPreviousGuesses);
begin
Inc(FStartRequestGuessCallCounter);
CheckPreviousGuessesIsEmpty(PreviousGuesses);
end;
procedure TTestMasterMindPresenter.CheckStartRequestGuessIsCalledWithPreviousGuess(const PreviousGuesses: TPreviousGuesses);
begin
Inc(FStartRequestGuessCallCounter);
CheckShowGuessesIsCalledWithOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult(PreviousGuesses);
end;
procedure TTestMasterMindPresenter.CheckPreviousGuessesIsEmpty(const PreviousGuesses: TPreviousGuesses);
begin
CheckEquals(0, Length(PreviousGuesses), 'Expected previous guesses to be empty!');
end;
procedure TTestMasterMindPresenter.NoOperation(const PreviousGuesses: TPreviousGuesses);
begin
// Nop
end;
procedure TTestMasterMindPresenter.CheckShowGuessWasCalledNTimes(const N: Integer);
begin
CheckEquals(N, FShowGuessesCallCounter, 'View.ShowGuesses has not been called');
end;
procedure TTestMasterMindPresenter.CheckShowGuessWasCalledOneTime;
begin
CheckShowGuessWasCalledNTimes(1);
end;
procedure TTestMasterMindPresenter.CheckShowPlayerWinsCalledOneTime;
begin
CheckEquals(1, FShowPlayerWinsCallCounter, 'View.ShowPlayerWins has not been called');
end;
procedure TTestMasterMindPresenter.CheckShowPlayerLosesCalledOneTime;
begin
CheckEquals(1, FShowPlayerLosesCallCounter, 'View.ShowPlayerLoses has not been called');
end;
procedure TTestMasterMindPresenter.CheckStartRequestGuessWasCalledOneTime;
begin
CheckEquals(1, FStartRequestGuessCallCounter, 'View.StartRequestGuess has not been called');
end;
procedure TTestMasterMindPresenter.CheckShowGuessesIsCalledWithOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult(const PreviousGuesses: TPreviousGuesses);
begin
Inc(FShowGuessesCallCounter);
CheckOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult(PreviousGuesses, 'ShowGuesses');
end;
procedure TTestMasterMindPresenter.CheckShowPlayerWinsIsCalledWithOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult(const PreviousGuesses: TPreviousGuesses);
begin
Inc(FShowPlayerWinsCallCounter);
CheckOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult(PreviousGuesses, 'ShowPlayerWins');
end;
procedure TTestMasterMindPresenter.CheckShowPlayerLosesIsCalledWithTwelvePreviousGuesses(const PreviousGuesses: TPreviousGuesses);
begin
Inc(FShowPlayerLosesCallCounter);
CheckEquals(12, Length(PreviousGuesses));
end;
procedure TTestMasterMindPresenter.CheckOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult(const PreviousGuesses: TPreviousGuesses; const MethodName: String);
begin
CheckEquals(1, Length(PreviousGuesses), MethodName +' called with PreviousGuesses having wrong length');
TEnumHelper<TMasterMindCodeColor>.CheckArraysEqual(FCurrentlyGuessedCode, PreviousGuesses[0].GuessedCode);
TEnumHelper<TMasterMindHint>.CheckArraysEqual(FEvaluatorMock.EvaluationResult, PreviousGuesses[0].GuessResult)
end;
procedure TTestMasterMindPresenter.TestNewGameClearsTheBoardAndSelectsANewCodeAndStartsRequestNewGuess;
begin
FViewMock.OnShowGuesses := CheckShowGuessesIsCalledWithEmptyPreviousGuesses;
FViewMock.OnStartRequestGuess := CheckStartRequestGuessIsCalledWithEmptyPreviousGuesses;
FPresenter.NewGame;
CheckShowGuessWasCalledOneTime;
TEnumHelper<TMasterMindCodeColor>.CheckArraysEqual([mmcGreen, mmcGreen, mmcRed, mmcRed], FPresenter.CodeToBeGuessed);
end;
procedure TTestMasterMindPresenter.TestTakeGuessEvaluatesAndAddsWrongGuessToTheVisibleBoard;
begin
FEvaluatorMock.EvaluationResult := MakeResult([mmhCorrect, mmhWrongPlace, mmhNoMatch, mmhNoMatch]);
FCurrentlyGuessedCode := MakeCode([mmcRed, mmcRed, mmcRed, mmcRed]);
FViewMock.OnShowGuesses := CheckShowGuessesIsCalledWithOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult;
FViewMock.OnStartRequestGuess := CheckStartRequestGuessIsCalledWithPreviousGuess;
FPresenter.TakeGuess(FCurrentlyGuessedCode);
CheckShowGuessWasCalledNTimes(2);
CheckStartRequestGuessWasCalledOneTime;
end;
procedure TTestMasterMindPresenter.TestTakeGuessCallsShowPlayerWinsMessageWhenGuessWasCorrect;
begin
FEvaluatorMock.EvaluationResult := MakeResult([mmhCorrect, mmhCorrect, mmhCorrect, mmhCorrect]);
FCurrentlyGuessedCode := MakeCode([mmcRed, mmcRed, mmcRed, mmcRed]);
FViewMock.OnShowGuesses := CheckShowGuessesIsCalledWithOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult;
FViewMock.OnShowPlayerWins := CheckShowPlayerWinsIsCalledWithOnePreviousGuessHavingTheGuessedCodeAndTheEvaluatorsResult;
FPresenter.TakeGuess(FCurrentlyGuessedCode);
CheckShowGuessWasCalledOneTime;
CheckShowPlayerWinsCalledOneTime;
end;
procedure TTestMasterMindPresenter.TestTakeTwelveWrongGuessesCallsShowPlayerLosesMessage;
var
I: Integer;
begin
FEvaluatorMock.EvaluationResult := MakeResult([mmhNoMatch, mmhNoMatch, mmhNoMatch, mmhNoMatch]);
FViewMock.OnStartRequestGuess := NoOperation;
FViewMock.OnShowGuesses := NoOperation;
FViewMock.OnShowPlayerLoses := CheckShowPlayerLosesIsCalledWithTwelvePreviousGuesses;
for I := 0 to 12 - 1 do
FPresenter.TakeGuess(MakeCode([mmcGreen, mmcGreen, mmcGreen, mmcGreen]));
CheckShowPlayerLosesCalledOneTime;
end;
initialization
RegisterTest(TTestMasterMindPresenter);
end. |
unit TestAverageCountLogger;
{
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, Windows, AverageLogger, AverageLogger.Count,
Dialogs, Classes, Sysutils, Math;
type
TInput = record
FileContents: TStringList;
NewValue: String;
end;
TListCheckFunction =
function (Input: TStringList): Boolean;
TExpectedValue = record
TodayDelta: String;
Period: TAveragePeriod;
FormattedAverageValue: String;
end;
// Test methods for class TAverageLogger
TestTAverageCountLogger = class(TTestCase)
public
procedure SetUp; override;
private
AverageCountLogger: TAverageCountLogger;
UserDefaultFormat: TFormatSettings;
procedure TestByExpectedValue(Input: TInput;
ExpectedResult: TExpectedValue; ListCheckFunction: TListCheckFunction);
procedure CheckEquality(TodayDelta: String; OutputList: TStringList;
PeriodAverageResult: TPeriodAverage; ExpectedResult: TExpectedValue;
ListCheckFunction: TListCheckFunction);
published
procedure TestBuildFileName;
procedure TestBlankToZero;
procedure TestBlankToOtherValue;
procedure TestSomeValueToOtherValue;
procedure Test30DaysAverage;
procedure Test90DaysAverage;
procedure TestOver180Days;
end;
implementation
procedure TestTAverageCountLogger.TestByExpectedValue(
Input: TInput; ExpectedResult: TExpectedValue;
ListCheckFunction: TListCheckFunction);
var
PeriodAverageResult: TPeriodAverage;
begin
AverageCountLogger := TAverageCountLogger.Create(Input.FileContents);
AverageCountLogger.ReadAndRefresh(Input.NewValue);
PeriodAverageResult := AverageCountLogger.GetMaxPeriodFormattedAverage;
CheckEquality(AverageCountLogger.GetFormattedTodayDelta, Input.FileContents,
PeriodAverageResult, ExpectedResult, @ListCheckFunction);
FreeAndNil(AverageCountLogger);
end;
procedure TestTAverageCountLogger.CheckEquality(
TodayDelta: String; OutputList: TStringList;
PeriodAverageResult: TPeriodAverage; ExpectedResult: TExpectedValue;
ListCheckFunction: TListCheckFunction);
begin
CheckEqualsString(ExpectedResult.TodayDelta,
AverageCountLogger.GetFormattedTodayDelta, 'TodayDelta');
CheckEquals(Ord(ExpectedResult.Period),
Ord(PeriodAverageResult.Period), 'Period');
CheckEqualsString(ExpectedResult.FormattedAverageValue,
PeriodAverageResult.FormattedAverageValue, 'AverageValue');
if @ListCheckFunction <> nil then
CheckTrue(ListCheckFunction(OutputList), 'ListCheckFunction');
end;
procedure TestTAverageCountLogger.TestBuildFileName;
begin
CheckEquals('@Folder@\ WriteLog @Serial@ .txt',
TAverageCountLogger.BuildFileName('@Folder@\ ', ' @Serial@ '));
end;
procedure TestTAverageCountLogger.TestBlankToZero;
const
ExpectedInThisScenario: TExpectedValue =
(TodayDelta: '0.0'; Period: Days30; FormattedAverageValue: '0.0');
var
Input: TInput;
begin
Input.FileContents := TStringList.Create;
Input.NewValue := '0';
TestByExpectedValue(Input, ExpectedInThisScenario, nil);
end;
procedure TestTAverageCountLogger.SetUp;
begin
UserDefaultFormat := TFormatSettings.Create(GetUserDefaultLCID);
UserDefaultFormat.DateSeparator := '-';
end;
procedure TestTAverageCountLogger.TestBlankToOtherValue;
function ListCheckFunction(Input: TStringList): Boolean;
begin
result :=
(Input.Count = 2) and
(Input[1] = '10');
end;
const
ExpectedInThisScenario: TExpectedValue =
(TodayDelta: '0.0'; Period: Days30; FormattedAverageValue: '0.0');
var
Input: TInput;
begin
Input.FileContents := TStringList.Create;
Input.NewValue := '10';
TestByExpectedValue(Input, ExpectedInThisScenario, @ListCheckFunction);
end;
procedure TestTAverageCountLogger.TestSomeValueToOtherValue;
function ListCheckFunction(Input: TStringList): Boolean;
begin
result :=
(Input.Count = 4) and
(Input[1] = '20') and
(Input[3] = '10');
end;
const
ExpectedInThisScenario: TExpectedValue =
(TodayDelta: '10.0'; Period: Days30; FormattedAverageValue: '5.0');
var
Input: TInput;
begin
Input.FileContents := TStringList.Create;
Input.FileContents.Add(FormatDateTime('yy/mm/dd', Now - 1));
Input.FileContents.Add('10');
Input.NewValue := '20';
TestByExpectedValue(Input, ExpectedInThisScenario, @ListCheckFunction);
end;
procedure TestTAverageCountLogger.Test30DaysAverage;
function ListCheckFunction(Input: TStringList): Boolean;
begin
result :=
(Input.Count = 4) and
(Input[1] = '310') and
(Input[3] = '10');
end;
const
ExpectedInThisScenario: TExpectedValue =
(TodayDelta: '300.0'; Period: Days90; FormattedAverageValue: '10.0');
var
Input: TInput;
begin
Input.FileContents := TStringList.Create;
//29days because of ceil ->
Input.FileContents.Add(FormatDateTime('yy/mm/dd', Now - 29));
Input.FileContents.Add('10');
Input.NewValue := '310';
TestByExpectedValue(Input, ExpectedInThisScenario, @ListCheckFunction);
end;
procedure TestTAverageCountLogger.Test90DaysAverage;
function ListCheckFunction(Input: TStringList): Boolean;
begin
result :=
(Input.Count = 4) and
(Input[1] = '910') and
(Input[3] = '10');
end;
const
ExpectedInThisScenario: TExpectedValue =
(TodayDelta: '900.0'; Period: Days180; FormattedAverageValue: '10.0');
var
Input: TInput;
begin
Input.FileContents := TStringList.Create;
//89days because of ceil ->
Input.FileContents.Add(FormatDateTime('yy/mm/dd', Now - 89));
Input.FileContents.Add('10');
Input.NewValue := '910';
TestByExpectedValue(Input, ExpectedInThisScenario, @ListCheckFunction);
end;
procedure TestTAverageCountLogger.TestOver180Days;
function ListCheckFunction(Input: TStringList): Boolean;
begin
result :=
(Input.Count = 2) and
(Input[1] = '10');
end;
const
ExpectedInThisScenario: TExpectedValue =
(TodayDelta: '0.0'; Period: Days30; FormattedAverageValue: '0.0');
var
Input: TInput;
begin
Input.FileContents := TStringList.Create;
Input.FileContents.Add(FormatDateTime('yy/mm/dd', Now - 181));
Input.FileContents.Add('5');
Input.NewValue := '10';
TestByExpectedValue(Input, ExpectedInThisScenario, @ListCheckFunction);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTAverageCountLogger.Suite);
end.
|
{
ID: nhutqua1
PROG: frac1
LANG: PASCAL
}
const fileinp='frac1.in';
fileout='frac1.out';
maxN=160;
var n:longint;
procedure Init;
begin
assign(input,fileinp); reset(input);
readln(n);
close(input);
end;
procedure GetFrac(n1,d1,n2,d2:longint);
begin
if d1 + d2 > n then exit;
GetFrac(n1,d1,n1+n2,d1+d2);
writeln(n1+n2,'/',d1+d2);
GetFrac(n1+n2,d1+d2,n2,d2);
end;
procedure Print;
begin
assign(output,fileout); rewrite(output);
writeln('0/1');
GetFrac(0,1,1,1);
writeln('1/1');
close(output);
end;
begin
Init;
Print;
end. |
unit Vigilante.Configuracao.View;
interface
uses
Vigilante.View.Base, Winapi.Windows, Winapi.Messages, System.SysUtils,
System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, Vcl.WinXCtrls, Vigilante.Configuracao,
Vigilante.Configuracao.Observer, Vigilante.Controller.Configuracao;
type
TfrmConfiguracaoView = class(TViewBase, IConfiguracao, IConfiguracaoObserver)
chkSimulado: TToggleSwitch;
chkAtualizacaoAutomatica: TToggleSwitch;
Label2: TLabel;
edtAtualizacaoIntervalo: TEdit;
Label3: TLabel;
Button1: TButton;
gpbAtualizacoesAutomaticas: TGroupBox;
gpbOrigemDosDados: TGroupBox;
procedure edtAtualizacaoIntervaloClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
FController: IConfiguracaoController;
procedure AlterarStatusChkState(const chkToggle: TToggleSwitch;
const ALigado: boolean);
public
function GetSimularBuild: boolean;
function GetAtualizacoesAutomaticas: boolean;
function GetAtualizacoesIntervalo: integer;
procedure DefinirController(const AController: IConfiguracaoController);
procedure SetSimularBuild(const Value: boolean);
procedure SetAtualizacoesAutomaticas(const Value: boolean);
procedure SetAtualizacoesIntervalo(const Value: integer);
procedure PersistirConfiguracoes;
procedure ConfiguracoesAlteradas(const AConfiguracao: IConfiguracao);
procedure CarregarConfiguracoes;
end;
implementation
{$R *.dfm}
uses
System.StrUtils, Vigilante.Configuracao.Impl;
procedure TfrmConfiguracaoView.Button1Click(Sender: TObject);
begin
inherited;
PersistirConfiguracoes;
end;
procedure TfrmConfiguracaoView.CarregarConfiguracoes;
begin
ConfiguracoesAlteradas(PegarConfiguracoes);
end;
procedure TfrmConfiguracaoView.ConfiguracoesAlteradas(
const AConfiguracao: IConfiguracao);
begin
if not Assigned(FController) then
Exit;
FController.CarregarConfiguracoes(AConfiguracao, Self);
end;
procedure TfrmConfiguracaoView.DefinirController(
const AController: IConfiguracaoController);
begin
FController := AController;
FController.CarregarConfiguracoes(PegarConfiguracoes, Self);
end;
procedure TfrmConfiguracaoView.edtAtualizacaoIntervaloClick(Sender: TObject);
begin
inherited;
PersistirConfiguracoes;
end;
procedure TfrmConfiguracaoView.PersistirConfiguracoes;
begin
FController.PersistirAlteracoes(Self);
end;
procedure TfrmConfiguracaoView.AlterarStatusChkState(
const chkToggle: TToggleSwitch; const ALigado: boolean);
var
_state: TToggleSwitchState;
begin
_state := tssOff;
if ALigado then
_state := tssOn;
chkToggle.State := _state;
end;
function TfrmConfiguracaoView.GetAtualizacoesAutomaticas: boolean;
begin
Result := chkAtualizacaoAutomatica.State = tssOn;
end;
function TfrmConfiguracaoView.GetAtualizacoesIntervalo: integer;
var
_atualizacaoIntervalo: string;
begin
Result := -1;
_atualizacaoIntervalo := edtAtualizacaoIntervalo.Text;
if _atualizacaoIntervalo.Trim.IsEmpty then
Exit;
Result := _atualizacaoIntervalo.toInteger * 1000;
end;
function TfrmConfiguracaoView.GetSimularBuild: boolean;
begin
Result := chkSimulado.State = tssOn;
end;
procedure TfrmConfiguracaoView.SetAtualizacoesAutomaticas(const Value: boolean);
begin
AlterarStatusChkState(chkAtualizacaoAutomatica, Value);
end;
procedure TfrmConfiguracaoView.SetAtualizacoesIntervalo(const Value: integer);
begin
edtAtualizacaoIntervalo.Text := (Value div 1000).ToString;
end;
procedure TfrmConfiguracaoView.SetSimularBuild(const Value: boolean);
begin
AlterarStatusChkState(chkSimulado, Value);
end;
end.
|
unit ncaFrmReajustePreco;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, cxControls, cxContainer, cxEdit, cxTextEdit,
cxCurrencyEdit, cxLabel, Vcl.StdCtrls, cxButtons, LMDControl,
LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel;
type
TFrmReajustePreco = class(TForm)
LMDSimplePanel2: TLMDSimplePanel;
btnSalvar: TcxButton;
btnCancelar: TcxButton;
cxLabel1: TcxLabel;
panMargem: TLMDSimplePanel;
edMargem: TcxCurrencyEdit;
cxLabel3: TcxLabel;
lbPerc: TcxLabel;
procedure FormCreate(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edMargemFocusChanged(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function ObtemPerc: Double;
end;
var
FrmReajustePreco: TFrmReajustePreco;
implementation
{$R *.dfm}
uses ncaFrmPri, ncaDM;
resourcestring
rsPercZero = 'O percentual a ser aplicado deve ser maior que zero';
procedure TFrmReajustePreco.btnSalvarClick(Sender: TObject);
begin
edMargem.PostEditValue;
if edMargem.Value<0.0001 then raise exception.Create(rsPercZero);
ModalResult := mrOk;
end;
procedure TFrmReajustePreco.edMargemFocusChanged(Sender: TObject);
begin
lbPerc.Visible := edMargem.Focused;
lbPerc.Left := edMargem.Left + edMargem.Width + 5;
end;
procedure TFrmReajustePreco.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmReajustePreco.FormCreate(Sender: TObject);
begin
edMargem.Value := 0;
btnSalvar.Enabled := Dados.CM.UA.Admin;
end;
function TFrmReajustePreco.ObtemPerc: Double;
begin
ShowModal;
if ModalResult=mrOk then
Result := edMargem.Value else
Result := 0;
end;
end.
|
{*************************************************************}
{ }
{ Embarcadero Delphi Visual Component Library }
{ InterBase Express core components }
{ }
{ Copyright (c) 1998-2017 Embarcadero Technologies, Inc.}
{ All rights reserved }
{ }
{ Additional code created by Jeff Overcash and used }
{ with permission. }
{*************************************************************}
unit IBX.IBFilterSummary;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls;
type
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
TfrmIBFilterSummary = class(TForm)
lstSummary: TListView;
btnOk: TBitBtn;
BitBtn1: TBitBtn;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.DFM}
end.
|
unit Settings;
interface
uses SysUtils, Classes,
{ Fluente }
Util;
type
TSettings = class(TObject)
private
FSettings: TStringList;
public
constructor Create(const CaminhoArquivoConfiguracao: string); reintroduce;
function save(const Key, Value: string): TSettings;
function get(const Key: string): string;
end;
implementation
{ TSettings }
constructor TSettings.Create(const CaminhoArquivoConfiguracao: string);
var
_i: Integer;
_arquivo: TStringList;
begin
inherited Create;
Self.FSettings := TStringList.Create;
if FileExists(CaminhoArquivoConfiguracao) then
begin
_arquivo := TStringList.Create();
try
_arquivo.LoadFromFile(CaminhoArquivoConfiguracao);
for _i := 0 to _arquivo.Count-1 do
begin
Self.FSettings.AddObject(
Copy(_arquivo[_i], 1, Pos('=', _arquivo[_i]) -1),
TValor.Create()
.Texto(Copy(_arquivo[_i], Pos('=', _arquivo[_i])+1, 1024))) ;
end;
finally
FreeAndNil(_arquivo);
end;
end;
end;
function TSettings.get(const Key: string): string;
begin
// Self.FSettings.TryGetValue(Key, Result)
end;
function TSettings.save(const Key, Value: string): TSettings;
begin
// Self.FSettings.AddOrSetValue(Key, Value);
Result := Self
end;
end.
|
unit uDocTree;
interface
uses SysUtils, Classes, ORNet, ORFn, rCore, uCore, uConst, ORCtrls, ComCtrls, uTIU;
type
PDocTreeObject = ^TDocTreeObject;
TDocTreeObject = record
DocID : string ; //Document IEN
DocDate : string; //Formatted date of document
DocTitle : string; //Document Title Text
NodeText : string; //Title, Location, Author (depends on tab)
ImageCount : integer; //Number of images
VisitDate : string; //ADM/VIS: date;FMDate
DocFMDate : string; //FM date of document
DocHasChildren : string; //Has children (+,>,<)
DocParent : string; //Parent document, or context
Author : string; //DUZ;Author name
PkgRef : string; //IEN;Package (consults only, for now)
Location : string; //Location name
Status : string; //Status
Subject : string; //Subject
OrderID : string; //Order file IEN (consults only, for now)
OrderByTitle : boolean; //Within ID Parents, order children by title, not date
Orphaned : boolean; //True if the parent no longer exist in the system
end;
// Procedures for document treeviews/listviews
procedure CreateListItemsForDocumentTree(Dest, Source: TStrings; Context: integer; GroupBy: string;
Ascending: boolean; TabIndex: integer);
procedure BuildDocumentTree(DocList: TStrings; const Parent: string; Tree: TORTreeView; Node: TORTreeNode;
TIUContext: TTIUContext; TabIndex: integer);
procedure BuildDocumentTree2(DocList: TStrings; Tree:
TORTreeView; TIUContext: TTIUContext; TabIndex: integer) ;
procedure SetTreeNodeImagesAndFormatting(Node: TORTreeNode; CurrentContext: TTIUContext; TabIndex: integer);
procedure ResetDocTreeObjectStrings(AnObject: PDocTreeObject);
procedure KillDocTreeObjects(TreeView: TORTreeView);
procedure KillDocTreeNode(ANode: TTreeNode);
function ContextMatch(ANode: TORTreeNode; AParentID: string; AContext: TTIUContext): Boolean;
function TextFound(ANode: TORTreeNode; CurrentContext: TTIUContext): Boolean;
procedure RemoveParentsWithNoChildren(Tree: TTreeView; Context: TTIUContext);
procedure TraverseTree(ATree: TTreeView; AListView: TListView; ANode: TTreeNode; MyNodeID: string;
AContext: TTIUContext);
procedure AddListViewItem(ANode: TTreeNode; AListView: TListView);
function MakeNoteTreeObject(x: string): PDocTreeObject;
function MakeDCSummTreeObject(x: string): PDocTreeObject;
function MakeConsultsNoteTreeObject(x: string): PDocTreeObject;
implementation
uses
rConsults, uDCSumm, uConsults;
{==============================================================
RPC [TIU DOCUMENTS BY CONTEXT] returns
the following string '^' pieces:
===============================================================
1 - Document IEN
2 - Document Title
3 - FM date of document
4 - Patient Name
5 - DUZ;Author name
6 - Location
7 - Status
8 - ADM/VIS: date;FMDate
9 - Discharge Date;FMDate
10 - Package variable pointer
11 - Number of images
12 - Subject
13 - Has children
14 - Parent document
15 - Order children of ID Note by title rather than date
===============================================================}
procedure CreateListItemsForDocumentTree(Dest, Source: TStrings; Context: integer; GroupBy: string;
Ascending: Boolean; TabIndex: integer);
const
NO_MATCHES = '^No Matching Documents Found^^^^^^^^^^^%^0';
var
i: Integer;
x, x1, x2, x3, MyParent, MyTitle, MyLocation, MySubject: string;
AList, SrcList: TStringList;
begin
AList := TStringList.Create;
SrcList := TStringList.Create;
try
FastAssign(Source, SrcList);
with SrcList do
begin
if (Count = 0) then
begin
Dest.Insert(0, IntToStr(Context) + NO_MATCHES);
Exit;
end;
for i := 0 to Count - 1 do
begin
x := Strings[i];
MyParent := Piece(x, U, 14);
MyTitle := Piece(x, U, 2);
if Length(Trim(MyTitle)) = 0 then
begin
MyTitle := '** No Title **';
SetPiece(x, U, 2, MyTitle);
end;
MyLocation := Piece(x, U, 6);
if Length(Trim(MyLocation)) = 0 then
begin
MyLocation := '** No Location **';
SetPiece(x, U, 6, MyLocation);
end;
MySubject := Piece(x, U, 12);
(* case TIUContext.SearchField[1] of
'T': if ((TextFound(MyTitle)) then continue;
'S': if (not TextFound(MySubject)) then continue;
'B': if not ((TextFound(MyTitle)) or (TextFound(MySubject))) then continue;
end;*)
if GroupBy <> '' then case GroupBy[1] of
'D': begin
x1 := Piece(Piece(x, U, 8), ';', 1); // Visit date
x2 := Piece(Piece(Piece(x, U, 8), ';', 2), '.', 1); // Visit date (FM) no time - v15.4
if x2 = '' then
begin
x2 := 'No Visit';
x1 := Piece(x1, ':', 1) + ': No Visit';
end;
(*else
x1 := Piece(x1, ':', 1) + ': ' + FormatFMDateTimeStr('mmm dd,yy@hh:nn',x2)*) //removed v15.4
if MyParent = IntToStr(Context) then
SetPiece(x, U, 14, MyParent + x2 + Copy(x1, 1, 3)); // '2980324Adm'
x3 := x2 + Copy(x1, 1, 3) + U + MixedCase(x1) + U + IntToStr(Context) + MixedCase(Copy(x1, 1, 3));
if (Copy(MyTitle, 1, 8) <> 'Addendum') and (AList.IndexOf(x3) = -1) then
AList.Add(x3); // '2980324Adm^Mar 24,98'
end;
'L': begin
if MyParent = IntToStr(Context) then // keep ID notes together, or
SetPiece(x, U, 14, MyParent + MyLocation);
(* if (Copy(MyTitle, 1, 8) <> 'Addendum') then // split ID Notes by location?
SetPiece(x, U, 14, IntToStr(Context) + MyLocation);*)
x3 := MyLocation + U + MixedCase(MyLocation) + U + IntToStr(Context);
if (Copy(MyTitle, 1, 8) <> 'Addendum') and (AList.IndexOf(x3) = -1) then
AList.Add(x3);
end;
'T': begin
if MyParent = IntToStr(Context) then // keep ID notes together, or
SetPiece(x, U, 14, MyParent + MyTitle);
(* if (Copy(MyTitle, 1, 8) <> 'Addendum') then // split ID Notes by title?
SetPiece(x, U, 14, IntToStr(Context) + MyTitle);*)
x3 := MyTitle + U + MixedCase(MyTitle) + U + IntToStr(Context);
if (Copy(MyTitle, 1, 8) <> 'Addendum') and (AList.IndexOf(x3) = -1) then
AList.Add(x3);
end;
'A': begin
x1 := Piece(Piece(x, U, 5), ';', 3);
if x1 = '' then x1 := '** No Author **';
if MyParent = IntToStr(Context) then // keep ID notes together, or
SetPiece(x, U, 14, MyParent + x1);
//if (Copy(MyTitle, 1, 8) <> 'Addendum') then // split ID Notes by author?
// SetPiece(x, U, 14, IntToStr(Context) + x1);
x3 := x1 + U + MixedCase(x1) + U + IntToStr(Context);
if (Copy(MyTitle, 1, 8) <> 'Addendum') and(AList.IndexOf(x3) = -1) then
AList.Add(x3);
end;
(* 'A': begin // Makes note appear both places in tree,
x1 := Piece(Piece(x, U, 5), ';', 3); // but also appears TWICE in lstNotes.
if x1 = '' then x1 := '** No Author **'; // IS THIS REALLY A PROBLEM??
if MyParent = IntToStr(Context) then // Impact on EditingIndex?
SetPiece(x, U, 14, MyParent + x1); // Careful when deleting note being edited!!!
Dest.Add(x); // Need to find and delete ALL occurrences!
SetPiece(x, U, 14, IntToStr(Context) + x1);
x3 := x1 + U + MixedCase(x1) + U + IntToStr(Context);
if (AList.IndexOf(x3) = -1) then AList.Add(x3);
end;*)
end;
Dest.Add(x);
end; {for}
SortByPiece(TStringList(Dest), U, 3);
if not Ascending then InvertStringList(TStringList(Dest));
if GroupBy <> '' then if GroupBy[1] ='D' then
begin
AList.Add('Adm^Inpatient Notes' + U + IntToStr(Context));
AList.Add('Vis^Outpatient Notes' + U + IntToStr(Context));
end;
Dest.Insert(0, IntToStr(Context) + '^' + NC_TV_TEXT[TabIndex, Context] + '^^^^^^^^^^^%^0');
Alist.Sort;
InvertStringList(AList);
if GroupBy <> '' then if GroupBy[1] ='D' then
if (not Ascending) then InvertStringList(AList);
for i := 0 to AList.Count-1 do
Dest.Insert(0, IntToStr(Context) + Piece(AList[i], U, 1) + '^' + Piece(AList[i], U, 2) + '^^^^^^^^^^^%^' + Piece(AList[i], U, 3));
end;
finally
AList.Free;
SrcList.Free;
end;
end;
procedure BuildDocumentTree(DocList: TStrings; const Parent: string; Tree: TORTreeView; Node: TORTreeNode;
TIUContext: TTIUContext; TabIndex: integer);
var
MyID, MyParent, Name: string;
i: Integer;
ChildNode, tmpNode: TORTreeNode;
DocHasChildren: Boolean;
AnObject: PDocTreeObject;
begin
with DocList do for i := 0 to Count - 1 do
begin
tmpNode := nil;
MyParent := Piece(Strings[i], U, 14);
if (MyParent = Parent) then
begin
MyID := Piece(Strings[i], U, 1);
if Piece(Strings[i], U, 13) <> '%' then
case TabIndex of
CT_NOTES: Name := MakeNoteDisplayText(Strings[i]);
CT_CONSULTS: Name := MakeConsultNoteDisplayText(Strings[i]);
CT_DCSUMM: Name := MakeDCSummDisplayText(Strings[i]);
end
else
Name := Piece(Strings[i], U, 2);
DocHasChildren := (Piece(Strings[i], U, 13) <> '');
if Node <> nil then if Node.HasChildren then
tmpNode := Tree.FindPieceNode(MyID, 1, U, Node);
if (tmpNode <> nil) and tmpNode.HasAsParent(Node) then
Continue
else
begin
case TabIndex of
CT_NOTES: AnObject := MakeNoteTreeObject(Strings[i]);
CT_CONSULTS: AnObject := MakeConsultsNoteTreeObject(Strings[i]);
CT_DCSUMM: AnObject := MakeDCSummTreeObject(Strings[i]);
else
AnObject := nil;
end;
ChildNode := TORTreeNode(Tree.Items.AddChildObject(TORTreeNode(Node), Name, AnObject));
ChildNode.StringData := Strings[i];
SetTreeNodeImagesAndFormatting(ChildNode, TIUContext, TabIndex);
if DocHasChildren then BuildDocumentTree(DocList, MyID, Tree, ChildNode, TIUContext, TabIndex);
end;
end;
end;
end;
procedure BuildDocumentTree2(DocList: TStrings; Tree:
TORTreeView; TIUContext: TTIUContext; TabIndex: integer);
type
TBuildDocTree = record
Name: string;
ParentNode: TORTreeNode;
MyNode: TORTreeNode;
AnObject: PDocTreeObject;
end;
var
OurDocTree: array of TBuildDocTree;
ListOfParents: TStringList;
LastRecCnt: Integer;
FirstParent: TObject;
procedure MapTheParent(var ItemsToAdd, ParentList: TStringList);
var
i, j, Z: Integer;
ParentNode: TORTreeNode;
NextParentList: TStringList;
begin
NextParentList := TStringList.Create;
try
//If we have no parents (first time) then add 0
if ListOfParents.count < 1 then ListOfParents.add('0');
//Loop though the parent list and find any nodes that need to be added
for j := 0 to ListOfParents.Count - 1 do begin
//Find this parent node (if exist). to be used when adding these individual nodes.
ParentNode := nil;
for z := Low(OurDocTree) to High(OurDocTree) do
begin
if UpperCase(Piece(ListOfParents.Strings[j], U, 1)) = UpperCase(Piece(OurDocTree[z].MyNode.StringData, U, 1) ) then
begin
ParentNode := OurDocTree[z].MyNode;
break;
end;
end;
//Find any items from our remaining items list that is a child of this parent
for i := 0 to DocList.count - 1 do begin
if UpperCase(Piece(DocList.Strings[i], U, 14)) = UpperCase(Piece(ListOfParents.Strings[j], U, 1))
then begin
//Add to the virtual tree
ItemsToAdd.AddObject(DocList.Strings[i], ParentNode);
if not Assigned(FirstParent) then
FirstParent := ParentNode;
//If this item is also a parent then we need to add it to our parent list for the next run through
if (Piece(DocList.Strings[i], U, 13) <> '') then
NextParentList.Add(DocList.Strings[i]);
end;
end;
end;
ParentList.Assign(NextParentList);
finally
NextParentList.Free;
end;
end;
procedure AddItemsToTree(ListOfParents: TStringList; Orphaned: Boolean);
Var
I, J: Integer;
ItemsToAdd: TStringList;
begin
ItemsToAdd := TStringList.Create;
try
//Map out the parent objects and return the future parents
If not Orphaned then
MapTheParent(ItemsToAdd, ListOfParents)
else
ItemsToAdd.Assign(ListOfParents);
//Now loop through all items that need to be added this go-around
for i := 0 to ItemsToAdd.count - 1 do begin
SetLength(OurDocTree, Length(OurDocTree) + 1);
//Set up the name vaiable
if Piece(ItemsToAdd.Strings[i], U, 13) <> '%' then
case TabIndex of
CT_NOTES: OurDocTree[High(OurDocTree)].Name := MakeNoteDisplayText(ItemsToAdd.Strings[i]);
CT_CONSULTS: OurDocTree[High(OurDocTree)].Name := MakeConsultNoteDisplayText(ItemsToAdd.Strings
[i]);
CT_DCSUMM: OurDocTree[High(OurDocTree)].Name := MakeDCSummDisplayText(ItemsToAdd.Strings[i]);
end
else
OurDocTree[High(OurDocTree)].Name := Piece(ItemsToAdd.Strings[i], U, 2);
//Set up the actual node
case TabIndex of
CT_NOTES: OurDocTree[High(OurDocTree)].AnObject := MakeNoteTreeObject(ItemsToAdd.Strings[i]);
CT_CONSULTS: OurDocTree[High(OurDocTree)].AnObject := MakeConsultsNoteTreeObject(ItemsToAdd.Strings
[i]);
CT_DCSUMM: OurDocTree[High(OurDocTree)].AnObject := MakeDCSummTreeObject(ItemsToAdd.Strings[i]);
else
OurDocTree[High(OurDocTree)].AnObject := nil;
end;
//Now create this node using the ParentObject
OurDocTree[High(OurDocTree)].MyNode := TORTreeNode(Tree.Items.AddChildObject(TORTreeNode
(ItemsToAdd.Objects[i]), OurDocTree[High(OurDocTree)].Name, OurDocTree[High(OurDocTree)].AnObject));
OurDocTree[High(OurDocTree)].MyNode.StringData := ItemsToAdd.Strings[i];
SetTreeNodeImagesAndFormatting(OurDocTree[High(OurDocTree)].MyNode, TIUContext, TabIndex);
//Find the node from the remaing list to remove.
for j := 0 to DocList.count - 1 do begin
if DocList[j] = ItemsToAdd[i] then begin
DocList.delete(j);
break;
end;
end;
end;
finally
ItemsToAdd.free;
end;
end;
begin
ListOfParents := TStringList.Create();
try
//Clear the array
SetLength(OurDocTree, 0);
//Build the virtual tree array
LastRecCnt := -1;
FirstParent := nil;
while (DocList.Count > 0) and (LastRecCnt <> DocList.Count) do
begin
LastRecCnt := DocList.Count;
AddItemsToTree(ListOfParents, false);
end;
//Handle any orphaned records (backp)
if DocList.Count > 0 then
begin
AddItemsToTree(TStringList(DocList), True);
end;
//Clear the list
SetLength(OurDocTree, 0);
finally
ListOfParents.Free;
end;
end;
procedure SetTreeNodeImagesAndFormatting(Node: TORTreeNode; CurrentContext: TTIUContext; TabIndex: integer);
var
tmpAuthor: int64;
i: integer;
procedure MakeBold(ANode: TORTreeNode);
var
LookingForAddenda: boolean;
begin
if not assigned(Node) then exit;
LookingForAddenda := (Pos('ADDENDUM', UpperCase(CurrentContext.Keyword)) > 0);
with ANode do
begin
Bold := True;
if assigned(Parent) then
begin
if (ImageIndex <> IMG_ADDENDUM) or ((ImageIndex = IMG_ADDENDUM) and LookingForAddenda) then
Parent.Expand(False);
if assigned(Parent.Parent) then
begin
if (Parent.ImageIndex <> IMG_ADDENDUM) or ((Parent.ImageIndex = IMG_ADDENDUM) and LookingForAddenda) then
Parent.Parent.Expand(False);
if assigned(Parent.Parent.Parent) then
if (Parent.Parent.ImageIndex <> IMG_ADDENDUM) or ((Parent.Parent.ImageIndex = IMG_ADDENDUM) and LookingForAddenda) then
Parent.Parent.Parent.Expand(False);
end;
end;
end;
end;
begin
with Node, PDocTreeObject(Node.Data)^ do
begin
i := Pos('*', DocTitle);
if i > 0 then i := i + 1 else i := 0;
if Orphaned then
ImageIndex := IMG_ORPHANED
else if (Copy(DocTitle, i + 1, 8) = 'Addendum') then
ImageIndex := IMG_ADDENDUM
else if (DocHasChildren = '') then
ImageIndex := IMG_SINGLE
else if Pos('+>', DocHasChildren) > 0 then
ImageIndex := IMG_ID_CHILD_ADD
else if (DocHasChildren = '>') then
ImageIndex := IMG_ID_CHILD
else if Pos('+<', DocHasChildren) > 0 then
ImageIndex := IMG_IDPAR_ADDENDA_SHUT
else if DocParent = '0' then
begin
ImageIndex := IMG_TOP_LEVEL;
SelectedIndex := IMG_TOP_LEVEL;
StateIndex := -1;
with CurrentContext, Node do
begin
if Node.HasChildren and (GroupBy <> '') then case GroupBy[1] of
'T': Text := NC_TV_TEXT[TabIndex, StrToInt(DocID)] + ' by title';
'D': Text := NC_TV_TEXT[TabIndex, StrToInt(DocID)] + ' by visit date';
'L': Text := NC_TV_TEXT[TabIndex, StrToInt(DocID)] + ' by location';
'A': Text := NC_TV_TEXT[TabIndex, StrToInt(DocID)] + ' by author';
end;
if TabIndex <> CT_CONSULTS then
begin
if (DocID = '2') or (DocID ='3') then
begin
if StrToIntDef(Status, 0) in [NC_UNSIGNED, NC_UNCOSIGNED] then
begin
if Author = 0 then tmpAuthor := User.DUZ else tmpAuthor := Author;
Text := Text + ' for ' + ExternalName(tmpAuthor, 200);
end
else
Text := Text + ' for ' + User.Name;
end;
if DocID = '4' then
Text := Text + ' for ' + ExternalName(Author, 200);
end;
end;
end
else
case DocHasChildren[1] of
'<': ImageIndex := IMG_IDNOTE_SHUT;
'+': ImageIndex := IMG_PARENT;
'%': begin
StateIndex := -1;
ImageIndex := IMG_GROUP_SHUT;
SelectedIndex := IMG_GROUP_OPEN;
end;
end;
SelectedIndex := ImageIndex;
if (ImageIndex in [IMG_TOP_LEVEL, IMG_GROUP_OPEN, IMG_GROUP_SHUT]) then
StateIndex := IMG_NONE
else
begin
if ImageCount > 0 then
StateIndex := IMG_1_IMAGE
else if ImageCount = 0 then
StateIndex := IMG_NO_IMAGES
else if ImageCount = -1 then
StateIndex := IMG_IMAGES_HIDDEN;
end;
if (Parent <> nil) and
(Parent.ImageIndex in [IMG_PARENT, IMG_IDNOTE_SHUT, IMG_IDNOTE_OPEN, IMG_IDPAR_ADDENDA_SHUT, IMG_IDPAR_ADDENDA_OPEN]) and
(StateIndex in [IMG_1_IMAGE, IMG_IMAGES_HIDDEN]) then
begin
Parent.StateIndex := IMG_CHILD_HAS_IMAGES;
end;
(* case ImageCount of
0: StateIndex := IMG_NO_IMAGES;
1: StateIndex := IMG_1_IMAGE;
2: StateIndex := IMG_2_IMAGES;
else
StateIndex := IMG_MANY_IMAGES;
end;*)
if Node.Parent <> nil then
if not CurrentContext.Filtered then
//don't bother to BOLD every entry
else
begin
if (*ContextMatch(Node) then
if (CurrentContext.KeyWord = '') or *)TextFound(Node, CurrentContext) then MakeBold(Node);
end;
end;
end;
procedure TraverseTree(ATree: TTreeView; AListView: TListView; ANode: TTreeNode; MyNodeID: string; AContext: TTIUContext);
var
IncludeIt: Boolean;
x: string;
begin
while ANode <> nil do
begin
IncludeIt := False;
if (ContextMatch(TORTreeNode(ANode), MyNodeID, AContext) and
TextFound(TORTreeNode(ANode), AContext)) then
begin
with PDocTreeObject(ANode.Data)^ do
begin
if (AContext.GroupBy <> '') and
(ATree.Selected.ImageIndex in [IMG_GROUP_OPEN, IMG_GROUP_SHUT]) then
begin
case AContext.GroupBy[1] of
'T':
if (UpperCase(DocTitle)
= UpperCase(PDocTreeObject(ATree.Selected.Data)^.DocTitle)) or
(UpperCase(DocTitle) = UpperCase('Addendum to ' +
PDocTreeObject(ATree.Selected.Data)^.DocTitle)) or
(AContext.Filtered and TextFound(TORTreeNode(ANode), AContext))
then
IncludeIt := True;
'D':
begin
x := PDocTreeObject(ATree.Selected.Data)^.DocID;
if (Copy(x, 2, 3) = 'Vis') or (Copy(x, 2, 3) = 'Adm') then
begin
if Copy(VisitDate, 1, 3) = Copy(x, 2, 3) then
IncludeIt := True;
end
else if Piece(Piece(VisitDate, ';', 2), '.', 1)
= Copy(x, 2, Length(x) - 4) then
IncludeIt := True;
end;
'L':
if MyNodeID + Location = PDocTreeObject(ATree.Selected.Data)^.DocID
then
IncludeIt := True;
'A':
if MyNodeID + Piece(Author, ';', 2)
= PDocTreeObject(ATree.Selected.Data)^.DocID then
IncludeIt := True;
end;
end
else
IncludeIt := True;
end;
end;
if IncludeIt then
AddListViewItem(ANode, AListView);
if ANode.HasChildren then
TraverseTree(ATree, AListView, ANode.GetFirstChild, MyNodeID, AContext);
ANode := ANode.GetNextSibling;
end;
end;
function ContextMatch(ANode: TORTreeNode; AParentID: string; AContext: TTIUContext): Boolean;
var
Status: string;
Author: int64;
begin
Result := True;
if not Assigned(ANode.Data) then Exit;
Status := PDocTreeObject(ANode.Data)^.Status;
if (AContext.Status <> AParentID[1]) or (AContext.Author = 0) then
Author := User.DUZ
else
Author := AContext.Author;
if Length(Trim(Status)) = 0 then exit;
(*if PDocTreeObject(ANode.Data)^.DocHasChildren = '%' then Result := False else Result := True;
Result := False;*)
case AParentID[1] of
'1': Result := (Status = 'completed') or
(Status = 'deleted') or
(Status = 'amended') or
(Status = 'uncosigned') or
(Status = 'retracted');
'2': Result := ((Status = 'unsigned') or
(Status = 'unreleased') or
(Status = 'deleted') or
(Status = 'retracted') or
(Status = 'unverified')) and
(Piece(PDocTreeObject(ANode.Data)^.Author, ';', 1) = IntToStr(Author));
'3': Result := ((Status = 'uncosigned') or
(Status = 'unsigned') or
(Status = 'unreleased') or
(Status = 'deleted') or
(Status = 'retracted') or
(Status = 'unverified')) ;//and
{ TODO -oRich V. -cSort/Search : Uncosigned notes - need to check cosigner, not author, but don't have it }
//(Piece(PDocTreeObject(ANode.Data)^.Author, ';', 1) = IntToStr(Author));
'4': Result := (Piece(PDocTreeObject(ANode.Data)^.Author, ';', 1) = IntToStr(Author));
'5': if PDocTreeObject(ANode.Data)^.DocHasChildren = '%' then Result := False
else Result := (StrToFloat(PDocTreeObject(ANode.Data)^.DocFMDate) >= AContext.FMBeginDate) and
(Trunc(StrToFloat(PDocTreeObject(ANode.Data)^.DocFMDate)) <= AContext.FMEndDate);
'N': Result := True; // NEW NOTE
'E': Result := True; // EDITING NOTE
'A': Result := True; // NEW ADDENDUM or processing alert
end;
end;
function TextFound(ANode: TORTreeNode; CurrentContext: TTIUContext): Boolean;
var
MySearch: string;
begin
Result := False;
if not Assigned(ANode.Data) then Exit;
if CurrentContext.SearchField <> '' then
case CurrentContext.SearchField[1] of
'T': MySearch := PDocTreeObject(ANode.Data)^.DocTitle;
'S': MySearch := PDocTreeObject(ANode.Data)^.Subject;
'B': MySearch := PDocTreeObject(ANode.Data)^.DocTitle + ' ' + PDocTreeObject(ANode.Data)^.Subject;
end;
Result := (not CurrentContext.Filtered) or
((CurrentContext.Filtered) and (Pos(UpperCase(CurrentContext.KeyWord), UpperCase(MySearch)) > 0));
end;
procedure ResetDocTreeObjectStrings(AnObject: PDocTreeObject);
begin
with AnObject^ do
begin
DocID := '';
DocDate := '';
DocTitle := '';
NodeText := '';
VisitDate := '';
DocFMDate := '';
DocHasChildren := '';
DocParent := '';
Author := '';
PkgRef := '';
Location := '';
Status := '';
Subject := '';
OrderID := '';
end;
end;
procedure KillDocTreeObjects(TreeView: TORTreeView);
var
i: integer;
begin
with TreeView do
for i := 0 to Items.Count-1 do
begin
if(Assigned(Items[i].Data)) then
begin
ResetDocTreeObjectStrings(PDocTreeObject(Items[i].Data));
Dispose(PDocTreeObject(Items[i].Data));
Items[i].Data := nil;
end;
end;
end;
procedure KillDocTreeNode(ANode: TTreeNode);
begin
if(Assigned(ANode.Data)) then
begin
ResetDocTreeObjectStrings(PDocTreeObject(ANode.Data));
Dispose(PDocTreeObject(ANode.Data));
ANode.Data := nil;
end;
ANode.Owner.Delete(ANode);
end;
procedure RemoveParentsWithNoChildren(Tree: TTreeView; Context: TTIUContext);
var
n: integer;
begin
with Tree do
for n := Items.Count - 1 downto 0 do
if ((Items[n].ImageIndex = IMG_GROUP_SHUT)) then
begin
if (not Items[n].HasChildren) then
KillDocTreeNode(Items[n])
else if Context.Filtered then // if any hits, would be IMG_GROUP_OPEN
KillDocTreeNode(Items[n]);
end;
end;
procedure AddListViewItem(ANode: TTreeNode; AListView: TListView);
var
ListItem: TListItem;
begin
if not Assigned(ANode.Data) then Exit;
with Anode, PDocTreeObject(ANode.Data)^, AListView do
begin
(* if (FCurrentContext.Status = '1') and
(Copy(DocTitle, 1 , 8) = 'Addendum') then Exit;*)
if ANode.ImageIndex in [IMG_TOP_LEVEL, IMG_GROUP_OPEN, IMG_GROUP_SHUT] then Exit;
ListItem := Items.Add;
ListItem.Caption := DocDate; // date
ListItem.StateIndex := ANode.StateIndex;
ListItem.ImageIndex := ANode.ImageIndex;
with ListItem.SubItems do
begin
Add(DocTitle); // title
Add(Subject); // subject
Add(MixedCase(Piece(Author, ';', 2))); // author
Add(Location); // location
Add(DocFMDate); // reference date (FM)
Add(DocID); // TIUDA
end;
end;
end;
function MakeNoteTreeObject(x: string): PDocTreeObject;
var
AnObject: PDocTreeObject;
begin
New(AnObject);
with AnObject^ do
begin
DocID := Piece(x, U, 1);
DocDate := FormatFMDateTime('mmm dd,yy', MakeFMDateTime(Piece(x, U, 3)));
DocTitle := Piece(x, U, 2);
Location := Piece(x, U, 6);
NodeText := MakeNoteDisplayText(x);
ImageCount := StrToIntDef(Piece(x, U, 11), 0);
VisitDate := Piece(x, U, 8);
DocFMDate := Piece(x, U, 3);
DocHasChildren := Piece(x, U, 13);
if Copy(DocHasChildren, 1, 1) = '*' then
DocHasChildren := Copy(DocHasChildren, 2, 5);
DocParent := Piece(x, U, 14);
Author := Piece(Piece(x, U, 5), ';', 1) + ';' + Piece(Piece(x, U, 5), ';', 3);
PkgRef := Piece(x, U, 10);
Status := Piece(x, U, 7);
Subject := Piece(x, U, 12);
OrderByTitle := Piece(x, U, 15) = '1';
Orphaned := Piece(x, U, 16) = '1';
end;
Result := AnObject;
end;
function MakeDCSummTreeObject(x: string): PDocTreeObject;
var
AnObject: PDocTreeObject;
begin
New(AnObject);
if Copy(Piece(x, U, 9), 1, 4) = ' ' then SetPiece(x, U, 9, 'Dis: ');
with AnObject^ do
begin
DocID := Piece(x, U, 1);
DocDate := FormatFMDateTime('mmm dd,yy', MakeFMDateTime(Piece(x, U, 3)));
DocTitle := Piece(x, U, 2);
Location := Piece(x, U, 6);
NodeText := MakeDCSummDisplayText(x);
DocFMDate := Piece(x, U, 3);
ImageCount := StrToIntDef(Piece(x, U, 11), 0);
DocHasChildren := Piece(x, U, 13);
if Copy(DocHasChildren, 1, 1) = '*' then
DocHasChildren := Copy(DocHasChildren, 2, 5);
DocParent := Piece(x, U, 14);
Author := Piece(Piece(x, U, 5), ';', 1) + ';' + Piece(Piece(x, U, 5), ';', 3);
PkgRef := Piece(x, U, 10);
Status := Piece(x, U, 7);
Subject := Piece(x, U, 12);
VisitDate := Piece(x, U, 8);
OrderByTitle := Piece(x, U, 15) = '1';
Orphaned := Piece(x, U, 16) = '1';
end;
Result := AnObject;
end;
function MakeConsultsNoteTreeObject(x: string): PDocTreeObject;
var
AnObject: PDocTreeObject;
begin
New(AnObject);
with AnObject^ do
begin
DocID := Piece(x, U, 1);
DocDate := FormatFMDateTime('mmm dd,yy', MakeFMDateTime(Piece(x, U, 3)));
DocTitle := Piece(x, U, 2);
Location := Piece(x, U, 6);
NodeText := MakeConsultNoteDisplayText(x);
DocFMDate := Piece(x, U, 3);
Status := Piece(x, U, 7);
Author := Piece(Piece(x, U, 5), ';', 1) + ';' + Piece(Piece(x, U, 5), ';', 3);
PkgRef := Piece(x, U, 10);
if Piece(PkgRef, ';', 2) = PKG_CONSULTS then
OrderID := GetConsultOrderIEN(StrToIntDef(Piece(PkgRef, ';', 1), 0));
ImageCount := StrToIntDef(Piece(x, U, 11), 0);
VisitDate := Piece(x, U, 8);
DocHasChildren := Piece(x, U, 13);
if Copy(DocHasChildren, 1, 1) = '*' then
DocHasChildren := Copy(DocHasChildren, 2, 5);
DocParent := Piece(x, U, 14);
OrderByTitle := Piece(x, U, 15) = '1';
Orphaned := Piece(x, U, 16) = '1';
end;
Result := AnObject;
end;
end.
|
unit FPrincipal;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Menus, ComCtrls, OleCtrls, ToolWin, ActnList, shdocvw,
Buttons, jpeg, IniFiles;
const
ARQ_UPLOADER = 'Uploader.ini';
CM_HOMEPAGEREQUEST = WM_USER + $1000;
type
TFormPrincipal = class(TForm)
Panel2: TPanel;
Panel3: TPanel;
WebBrowser: TWebBrowser;
Panel1: TPanel;
Panel4: TPanel;
procedure FormCreate(Sender: TObject);
procedure MenuFecharClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
StrUrl: String;
procedure FindAddress;
procedure HomePageRequest(var message: tmessage); message CM_HOMEPAGEREQUEST;
public
end;
var
FormPrincipal: TFormPrincipal;
implementation
{$R *.DFM}
procedure TFormPrincipal.FindAddress;
var
Flags: OLEVariant;
begin
Flags := 0;
WebBrowser.Navigate(WideString(StrUrl), Flags, Flags, Flags, Flags);
end;
procedure TFormPrincipal.HomePageRequest(var Message: TMessage);
begin
//URLs.Text := StrUrl;
//FindAddress;
end;
procedure TFormPrincipal.FormCreate(Sender: TObject);
begin
{ Find the home page - needs to be posted because HTML control hasn't been
registered yet. }
//PostMessage(Handle, CM_HOMEPAGEREQUEST, 0, 0);
end;
procedure TFormPrincipal.MenuFecharClick(Sender: TObject);
begin
WebBrowser.Stop;
Close;
end;
procedure TFormPrincipal.FormShow(Sender: TObject);
var AuxIni: TIniFile;
LocalDir: String;
begin
LocalDir:=ExtractFileDir(Application.ExeName);
LocalDir:=LocalDir+'\';
if (pos(':\\',LocalDir)>0) then delete(LocalDir,pos(':\\',LocalDir)+1,1);
AuxIni:= TIniFile.Create(LocalDir + ARQ_UPLOADER);
StrUrl:= AuxIni.ReadString('WEB', 'SITE', 'www.athenas.com.br');
AuxIni.Free;
FormPrincipal.Caption:= FormPrincipal.Caption + ' - ' + StrUrl;
StrUrl:= StrUrl + 'UploadLogin.asp';
FindAddress;
end;
end.
|
unit fAlertNoteSelector;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
ORCtrls,
ORDtTm,
ORNet,
ORFn,
ComCtrls;
type
TfrmAlertNoteSelector = class(TForm)
rbtnNewNote: TRadioButton;
rbtnSelectAddendum: TRadioButton;
rbtnSelectOwn: TRadioButton;
btnOK: TButton;
lbATRNotes_ORIG: TORListBox;
lbATRs: TORListBox;
lbATRNotes: TListBox;
buCancel: TButton;
StaticText1: TStaticText;
procedure rbtnNewNoteClick(Sender: TObject);
procedure rbtnSelectAddendumClick(Sender: TObject);
procedure rbtnSelectOwnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lbATRNotesClick(Sender: TObject);
procedure buCancelClick(Sender: TObject);
private
FXQAID: string;
FTIUNoteIEN: string;
public
property XQAID: string read FXQAID write FXQAID;
property TIUNoteIEN: string read FTIUNoteIEN write FTIUNoteIEN;
function GetTIUNotesByDate(thisPatientDFN: string;
thisStartDate: TFMDateTime; { Start Date }
thisDocType: integer = 3;
thisContext: integer = 5;
thisMaxResults: string = '0';
thisSortDirection: integer = 1;
thisIncludeAddenda: boolean = false;
thisIncludeUntranscribed: boolean = false): TStringList;
procedure DisplayTARAlertValues();
end;
var
frmAlertNoteSelector: TfrmAlertNoteSelector;
implementation
{ - Needs to be upgraded / DRP
uses
fTARProcess,
fTARNotification,
UTARConst;
}
{$R *.dfm}
procedure TfrmAlertNoteSelector.rbtnNewNoteClick(Sender: TObject);
begin
try
if rbtnNewNote.Checked then
begin
rbtnSelectAddendum.Checked := false;
rbtnSelectOwn.Checked := false;
end;
except
on E: Exception do
MessageDlg('An exception has occurred in procedure TfrmATRNoteSelect.rbtnNewNoteClick()' + CRLF + E.Message, mtError, [mbOk], 0);
end;
end;
procedure TfrmAlertNoteSelector.rbtnSelectAddendumClick(Sender: TObject);
begin
try
if rbtnSelectAddendum.Checked then
begin
rbtnNewNote.Checked := false;
rbtnSelectOwn.Checked := false;
end;
except
on E: Exception do
MessageDlg('An exception has occurred in procedure TfrmATRNoteSelect.rbtnSelectAddendumClick()' + CRLF + E.Message, mtError, [mbOk], 0);
end;
end;
procedure TfrmAlertNoteSelector.rbtnSelectOwnClick(Sender: TObject);
begin
try
if rbtnSelectOwn.Checked then
begin
rbtnSelectAddendum.Checked := false;
rbtnNewNote.Checked := false;
end;
except
on E: Exception do
MessageDlg('An exception has occurred in procedure TfrmATRNoteSelect.rbtnSelectOwnClick()' + CRLF + E.Message, mtError, [mbOk], 0);
end;
end;
procedure TfrmAlertNoteSelector.buCancelClick(Sender: TObject);
{
User wants to cancel out of this process.
So, we have to "roll back" the processing level of the selected TAR.
}
var
thisTARien: string;
begin
try
thisTARien := Piece(self.XQAID, ';', 7);
// If user has gotten this far in the TAR processing, they they have
// already taken 'some' action. So, be proactive and "reset" it to
// '1 = Some Action Taken' even though it already is 1.
{ TODO -oDan P -cSMART : Upgrade to redesinged SMART Notes
CallV('ORATR SET ATR PROCESSING LEVEL', [thisTARien, TAR_SOME_ACTION_TAKEN]);
}
// We don't want to do this here, because user may have already processed
// a Reminder for this TAR. We just want to Cancel.
// CallV('ORATR SET TIU NOTE', [thisTARien, '@']);
except
on E: Exception do
MessageDlg('An exception has occurred in procedure TfrmATRNoteSelect.buCancelClick()' + CRLF + E.Message, mtError, [mbOk], 0);
end;
end;
procedure TfrmAlertNoteSelector.DisplayTARAlertValues();
var
i: integer;
slParamArray: TStringList;
thisIEN: string;
begin
try
lbATRs.Clear;
rbtnSelectAddendum.Checked := true;
slParamArray := TStringList.Create;
thisIEN := Piece(self.XQAID, ';', 7);
slParamArray.Add('ATR^' + thisIEN);
{ TODO -oDan P -cSMART : Upgrade to redesinged SMART Notes
CallV('ORATR GET TEST RESULTS', [slParamArray]);
for i := 0 to frmTARNotification.RPCBroker.Results.Count - 1 do
lbATRs.Items.Add(frmTARNotification.RPCBroker.Results[i]);
}
if slParamArray <> nil then
FreeAndNil(slParamArray);
except
on E: Exception do
MessageDlg('An exception has occurred in procedure frmATRNoteSelect.DisplayTARAlertValues()' + CRLF + E.Message, mtError, [mbOk], 0);
end;
end;
procedure TfrmAlertNoteSelector.FormShow(Sender: TObject);
var
j: integer;
thisOrderDate: double;
thisTIUDate: double;
slTIUNotes: TStringList;
thisATRTIUNoteIEN: string;
begin
try
lbATRs.Clear;
DisplayTARAlertValues();
// Add ONLY the TIU Notes from the date that the ORIGINAL ORDER (ie, the order that generated the ATR Alert) was signed.
{ TODO -oDan P -cSMART : Upgrade to redesinged SMART Notes
frmATRNoteSelect.rbtnNewNote.Checked := true; // default
slTIUNotes := TStringList.Create;
thisOrderDate := strToInt64(Piece(Piece(self.XQAID, ';', 6), '.', 1));
slTIUNotes := GetTIUNotesByDate(frmTARNotification.PatientDFN, thisOrderDate);
//FastAssign(frmTARNotification.RPCBroker.Results, slTIUNotes); // DRP - Unfavorable Results In XE
slTIUNotes.Text := frmTARNotification.RPCBroker.Results.Text;
}
thisATRTIUNoteIEN := Piece(self.XQAID, ';', 7);
if thisATRTIUNoteIEN <> '' then
begin
rbtnNewNote.Enabled := true;
rbtnNewNote.Checked := true;
end
else
begin
rbtnNewNote.Enabled := false;
rbtnNewNote.Checked := false;
end;
if slTIUNotes.Count = 0 then
rbtnSelectAddendum.Enabled := false
else
rbtnSelectAddendum.Enabled := true;
for j := 0 to slTIUNotes.Count - 1 do
begin
thisTIUDate := strToInt64(Piece(Piece(slTIUNotes[j], '^', 3), '.', 1));
if thisOrderDate = thisTIUDate then
lbATRNotes.Items.Add(Piece(slTIUNotes[j], '^', 2) + ' - ' + Piece(slTIUNotes[j], '^', 6) + ' ' + Piece(Piece(slTIUNotes[j], '^', 8), ';', 1));
end;
if slTIUNotes <> nil then
FreeAndNil(slTIUNotes);
except
on E: Exception do
MessageDlg('An exception has occurred in procedure frmATRNoteSelect.FormShow()' + CRLF + E.Message, mtError, [mbOk], 0);
end;
end;
function TfrmAlertNoteSelector.GetTIUNotesByDate(thisPatientDFN: string;
thisStartDate: TFMDateTime; // Start Date
thisDocType: integer = 3; // Progress Notes
thisContext: integer = 5; // 5 = signed documents/date range
thisMaxResults: string = '0';
thisSortDirection: integer = 1;
thisIncludeAddenda: boolean = false;
thisIncludeUntranscribed: boolean = false): TStringList;
var
i: integer;
slTIUDocumentsByContext: TStringList;
begin
try
{ TODO -oDan P -cSMART : Upgrade to redesinged SMART Notes
CallV('TIU DOCUMENTS BY CONTEXT', [thisDocType, // Document type, 3 = Progress Notes
thisContext, // Document Context: signed documents by date range
thisPatientDFN, // patient
thisStartDate, // Start Date
thisStartDate, // End Date same as Start Date
frmTARNotification.UserDUZ, // User ID
0, // Max results
1, // 0=Ascending, 1=Descending
0, // param SHOWADD
1]); // param INCUND
slTIUDocumentsByContext := TStringList.Create;
for i := 0 to frmTARNotification.RPCBroker.Results.Count - 1 do
begin
if i = 0 then
begin
self.Caption := Piece(ORNet.RPCBrokerV.Results[i], '^', 4); // form caption = patient name + (last init,last4)
slTIUDocumentsByContext.Add(frmTARNotification.RPCBroker.Results[i]);
end
else
slTIUDocumentsByContext.Add(frmTARNotification.RPCBroker.Results[i]);
end;
if frmTARNotification.RPCBroker.Results.Count > 0 then
self.TIUNoteIEN := Piece(frmTARNotification.RPCBroker.Results[0], '^', 1);
result := slTIUDocumentsByContext;
}
except
on E: Exception do
MessageDlg('An exception has occurred in TfrmATRNoteSelect.GetTIUNotesByDate()' + CRLF + E.Message, mtError, [mbOk], 0);
end;
end;
procedure TfrmAlertNoteSelector.lbATRNotesClick(Sender: TObject);
begin
try
rbtnSelectAddendum.Checked := true;
except
on E: Exception do
MessageDlg('An exception has occurred in TfrmATRNoteSelect.lbATRNotesClick()' + CRLF + E.Message, mtError, [mbOk], 0);
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Math;
type
TForm1 = class(TForm)
Timer1: TTimer;
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormClick(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
type
TBoide=record
x,y: integer;
vx,vy: integer;
end;
const
maxboides=500;
Cursor_attract=300;
cohesion_attract=100;
Align_attract=8;
Separation_repuls=100;
Vitesse_Max=200;
Distance_Max=200*200;
Angle_Vision=90; // 180° total
var
Form1: TForm1;
boides:array[0..maxboides] of TBoide;
buffer:tbitmap;
palette:array[0..360] of longint;
implementation
{$R *.dfm}
// vérifie si b1 vois b2
function AngleDeVisionOk(b1,b2:tboide):boolean;
var
angle: extended;
begin
b1.x:=b1.x-b2.x;
b1.y:=b1.y-b2.y;
angle:=abs(arctan2(b1.x,b1.y)*180/pi);
result:=(b1.x*b1.x+b1.y*b1.y<Distance_Max) and (angle<=Angle_Vision);
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
pt: TPoint;
i,j,c: integer;
bx,by,bvx,bvy: integer;
cohesion,align,separation,center: TPoint;
begin
// position de la souris
GetCursorPos(pt);
// pour chaque boïde
for i:=0 to maxboides do
begin
c:=0;
cohesion.X:=0;
cohesion.y:=0;
align.x:=0;
align.y:=0;
separation.x:=0;
separation.y:=0;
// ils suivent le comportement des voisins
// on parcours toute la liste
for j:=0 to maxboides do
// si le boides J est dans le champs de vision de I
// càd : pas trop loin et devant lui
if (i<>j) and AngleDeVisionOk(boides[i],boides[j]) then
begin
// alors on traite les 3 forces qui régissent de comportement du groupe
c:=c+1;
// il se rapproche du centre de masse de ses voisins
cohesion.X:=cohesion.x+boides[j].x;
cohesion.y:=cohesion.Y+boides[j].y;
// il aligne sa direction sur celle des autres
align.x:=align.x+boides[j].vx;
align.y:=align.y+boides[j].vy;
// mais il s'éloigne si ils sont trop nombreux
separation.x:=separation.x-(boides[j].x-boides[i].x);
separation.y:=separation.y-(boides[j].y-boides[i].y);
end;
// si il y a des voisins, on fini les calculs des moyennes
if c<>0 then
begin
cohesion.x:=(cohesion.x div c-boides[i].x) div cohesion_attract;
cohesion.y:=(cohesion.y div c-boides[i].y) div cohesion_attract;
align.x:=(align.x div c-boides[i].vx) div Align_attract;
align.y:=(align.y div c-boides[i].vy) div Align_attract;
separation.x:=separation.x div Separation_repuls;
separation.y:=separation.y div Separation_repuls;
end;
// la dernière force les poussent tous vers la souris
center.x:=(pt.x*10-boides[i].x) div Cursor_attract;
center.y:=(pt.y*10-boides[i].y) div Cursor_attract;
// on combine toutes les infos pour avoir la nouvelle vitesse
boides[i].vx:=boides[i].vx+cohesion.x+align.x+separation.x+center.x;
boides[i].vy:=boides[i].vy+cohesion.y+align.y+separation.y+center.y;
// attention, si il va trop vite, on le freine
c:=round(sqrt(boides[i].vx*boides[i].vx+boides[i].vy*boides[i].vy));
if c>Vitesse_Max then
begin
boides[i].vx:=boides[i].vx*Vitesse_Max div c;
boides[i].vy:=boides[i].vy*Vitesse_Max div c;
end;
// on le déplace en fonction de sa vitesse
boides[i].x:=boides[i].x+boides[i].vx;
boides[i].y:=boides[i].y+boides[i].vy;
//rebond sur les bords
//if boides[i].x>clientwidth then boides[i].vx:=-boides[i].vx;
//if boides[i].x<0 then boides[i].vx:=-boides[i].vx;
//if boides[i].y>clientheight then boides[i].vy:=-boides[i].vy;
//if boides[i].y<0 then boides[i].vy:=-boides[i].vy;
// univers fermé
//if boides[i].x>clientwidth then boides[i].x:=boides[i].x-clientwidth;
//if boides[i].x<0 then boides[i].x:=boides[i].x+clientwidth;
//if boides[i].y>clientheight then boides[i].y:=boides[i].y-clientheight;
//if boides[i].y<0 then boides[i].y:=boides[i].y+clientheight;
end;
// on efface le buffer et on affiche les boïdes
buffer.canvas.Brush.color:=clblack;
buffer.canvas.FillRect(clientrect);
for i:=0 to maxboides do
begin
bx:=boides[i].x div 10;
by:=boides[i].y div 10;
bvx:=boides[i].vx div 10;
bvy:=boides[i].vy div 10;
//calcul de la direction de déplacement pour la couleur
c:=round(arctan2(bvx,bvy)*180/PI)+180;
buffer.canvas.pen.color:=palette[c];
// dessine un très de la longueur de la vitesse
buffer.canvas.MoveTo(bx,by);
buffer.canvas.lineto(bx+bvx,by+bvy);
end;
// affiche le résultat
canvas.Draw(0,0,buffer);
end;
procedure TForm1.FormCreate(Sender: TObject);
var
i: integer;
begin
randomize;
// on dessinera dans buffer
buffer:=tbitmap.Create;
buffer.Width:=clientwidth;
buffer.Height:=clientheight;
// on initialise une vitesse et une place aléatoire pour le départ
for i:=0 to maxboides do
with boides[i] do
begin
x:=random(clientwidth*10);
y:=random(clientheight*10);
vx:=random(200)-100;
vy:=random(200)-100;
end;
// on crée la palette de oculeur pour l'affichage
for i:=0 to 360 do
Case (i div 60) of
0,6:palette[i]:=rgb(255,(i Mod 60)*255 div 60,0);
1: palette[i]:=rgb(255-(i Mod 60)*255 div 60,255,0);
2: palette[i]:=rgb(0,255,(i Mod 60)*255 div 60);
3: palette[i]:=rgb(0,255-(i Mod 60)*255 div 60,255);
4: palette[i]:=rgb((i Mod 60)*255 div 60,0,255);
5: palette[i]:=rgb(255,0,255-(i Mod 60)*255 div 60);
end;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
buffer.Width:=clientwidth;
buffer.Height:=clientheight;
end;
procedure TForm1.FormClick(Sender: TObject);
begin
timer1.Free;
buffer.Free;
close;
end;
end. |
unit SwitchField;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types,
FMX.Objects, FMX.StdCtrls, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math,
System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects, ColorClass;
type
TSwitchField = class(TControl)
private
{ Private declarations }
procedure Enable();
procedure Disable();
function GetColorRoundRectangle(SolidColor: TAlphaColor): TAlphaColor;
procedure ApplyColorChanges();
protected
{ Protected declarations }
FPointerOnMouseEnter: TNotifyEvent;
FPointerOnMouseExit: TNotifyEvent;
FPointerOnClick: TNotifyEvent;
FPointerOnChange: TNotifyEvent;
FText: TLabel;
FLayoutIcon: TLayout;
FCircleMain: TCircle;
FCircleMainEffect: TCircle;
FRoundRectangle: TRoundRect;
FShadowCircleMain: TShadowEffect;
{ Block focus on background }
FButtonLockFocus: TButton;
FColorMain: TAlphaColor;
procedure OnSwitchFieldClick(Sender: TObject);
procedure OnSwitchFieldMouseEnter(Sender: TObject);
procedure OnSwitchFieldMouseExit(Sender: TObject);
function GetFCheckedIconColor: TAlphaColor;
procedure SetFCheckedIconColor(const Value: TAlphaColor);
function GetFButtonClass: TColorClass;
function GetFIsChecked: Boolean;
function GetFTag: NativeInt;
function GetFText: String;
function GetFTextSettings: TTextSettings;
procedure SetFButtonClass(const Value: TColorClass);
procedure SetFIsChecked(const Value: Boolean);
procedure SetFTag(const Value: NativeInt);
procedure SetFText(const Value: String);
procedure SetFTextSettings(const Value: TTextSettings);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property Cursor;
property Align;
property Anchors;
property Enabled;
property Height;
property Opacity;
property Visible;
property Width;
property Size;
property Scale;
property Margins;
property Position;
property RotationAngle;
property RotationCenter;
property HitTest;
{ Additional properties }
property ButtonClass: TColorClass read GetFButtonClass write SetFButtonClass;
property CheckedIconColor: TAlphaColor read GetFCheckedIconColor write SetFCheckedIconColor;
property Text: String read GetFText write SetFText;
property TextSettings: TTextSettings read GetFTextSettings write SetFTextSettings;
property IsChecked: Boolean read GetFIsChecked write SetFIsChecked;
property Tag: NativeInt read GetFTag write SetFTag;
{ Events }
property OnPainting;
property OnPaint;
property OnResize;
{ Mouse events }
property OnChange: TNotifyEvent read FPointerOnChange write FPointerOnChange;
property OnClick: TNotifyEvent read FPointerOnClick write FPointerOnClick;
property OnDblClick;
property OnKeyDown;
property OnKeyUp;
property OnMouseDown;
property OnMouseUp;
property OnMouseWheel;
property OnMouseMove;
property OnMouseEnter: TNotifyEvent read FPointerOnMouseEnter write FPointerOnMouseEnter;
property OnMouseLeave: TNotifyEvent read FPointerOnMouseExit write FPointerOnMouseExit;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Componentes Customizados', [TSwitchField]);
end;
{ TSwitchField }
constructor TSwitchField.Create(AOwner: TComponent);
begin
inherited;
Self.Width := 250;
Self.Height := 30;
Self.Cursor := crHandPoint;
TControl(Self).OnClick := OnSwitchFieldClick;
TControl(Self).OnMouseEnter := OnSwitchFieldMouseEnter;
TControl(Self).OnMouseLeave := OnSwitchFieldMouseExit;
FButtonLockFocus := TButton.Create(Self);
Self.AddObject(FButtonLockFocus);
FButtonLockFocus.SetSubComponent(True);
FButtonLockFocus.Stored := False;
FButtonLockFocus.Opacity := 0;
FButtonLockFocus.TabStop := False;
FButtonLockFocus.Width := 1;
FButtonLockFocus.Height := 1;
FButtonLockFocus.HitTest := False;
FButtonLockFocus.SendToBack;
FText := TLabel.Create(Self);
Self.AddObject(FText);
FText.Align := TAlignLayout.Client;
FText.HitTest := False;
FText.StyledSettings := [];
FText.TextSettings.Font.Size := 14;
FText.TextSettings.Font.Family := 'SF Pro Display';
FText.SetSubComponent(True);
FText.Stored := False;
FText.TextSettings.FontColor := TAlphaColor($FF323232);
// FBackupFontColor := TAlphaColor($FF323232);
FLayoutIcon := TLayout.Create(Self);
Self.AddObject(FLayoutIcon);
FLayoutIcon.Align := TAlignLayout.Left;
FLayoutIcon.HitTest := False;
FLayoutIcon.SetSubComponent(True);
FLayoutIcon.Stored := False;
FLayoutIcon.Width := 60;
FCircleMain := TCircle.Create(Self);
FLayoutIcon.AddObject(FCircleMain);
FCircleMain.Align := TAlignLayout.Center;
FCircleMain.HitTest := False;
FCircleMain.SetSubComponent(True);
FCircleMain.Stored := False;
FCircleMain.Stroke.Kind := TBrushKind.None;
FCircleMain.Visible := True;
FCircleMain.Width := 20;
FCircleMain.Height := 20;
FCircleMain.Margins.Left := -22;
FCircleMain.Fill.Color := SOLID_WHITE;
FRoundRectangle := TRoundRect.Create(Self);
FLayoutIcon.AddObject(FRoundRectangle);
FRoundRectangle.Align := TAlignLayout.Center;
FRoundRectangle.HitTest := False;
FRoundRectangle.SetSubComponent(True);
FRoundRectangle.Stored := False;
FRoundRectangle.Stroke.Kind := TBrushKind.None;
FRoundRectangle.Visible := True;
FRoundRectangle.Width := 34;
FRoundRectangle.Height := 14;
FRoundRectangle.SendToBack;
FRoundRectangle.Fill.Color := TAlphaColor($FFC4C4C4);
FCircleMainEffect := TCircle.Create(Self);
FCircleMain.AddObject(FCircleMainEffect);
FCircleMainEffect.Align := TAlignLayout.Center;
FCircleMainEffect.HitTest := False;
FCircleMainEffect.SetSubComponent(True);
FCircleMainEffect.Stored := False;
FCircleMainEffect.Stroke.Kind := TBrushKind.None;
FCircleMainEffect.Visible := True;
FCircleMainEffect.Width := 40;
FCircleMainEffect.Height := 40;
FCircleMainEffect.Opacity := 0;
FCircleMainEffect.SendToBack;
FCircleMainEffect.Fill.Color := SOLID_BLACK;
{ Shadow }
FShadowCircleMain := TShadowEffect.Create(Self);
FCircleMain.AddObject(FShadowCircleMain);
FShadowCircleMain.Direction := 90;
FShadowCircleMain.Distance := 2.5;
FShadowCircleMain.Opacity := 0.3;
FShadowCircleMain.Softness := 0.2;
FShadowCircleMain.Enabled := True;
SetFButtonClass(TColorClass.Primary);
end;
destructor TSwitchField.Destroy;
begin
if Assigned(FShadowCircleMain) then
FShadowCircleMain.Free;
if Assigned(FCircleMainEffect) then
FCircleMainEffect.Free;
if Assigned(FRoundRectangle) then
FRoundRectangle.Free;
if Assigned(FCircleMain) then
FCircleMain.Free;
if Assigned(FLayoutIcon) then
FLayoutIcon.Free;
if Assigned(FText) then
FText.Free;
if Assigned(FButtonLockFocus) then
FButtonLockFocus.Free;
inherited;
end;
procedure TSwitchField.Disable;
begin
FRoundRectangle.AnimateColor('Fill.Color', TAlphaColor($FFC4C4C4), 0.2, TAnimationType.InOut);
FCircleMain.AnimateColor('Fill.Color', TAlphaColor($FFFFFFFF), 0.2, TAnimationType.InOut);
FCircleMain.AnimateFloat('Margins.Left', -22, 0.2, TAnimationType.InOut);
FCircleMainEffect.AnimateColor('Fill.Color', TAlphaColor($FF000000), 0.1, TAnimationType.InOut);
end;
procedure TSwitchField.Enable;
begin
FRoundRectangle.AnimateColor('Fill.Color', GetColorRoundRectangle(FColorMain), 0.2, TAnimationType.InOut);
FCircleMain.AnimateColor('Fill.Color', FColorMain, 0.2, TAnimationType.InOut);
FCircleMain.AnimateFloat('Margins.Left', 22, 0.2, TAnimationType.InOut);
FCircleMainEffect.AnimateColor('Fill.Color', FColorMain, 0.1, TAnimationType.InOut);
end;
function TSwitchField.GetFButtonClass: TColorClass;
begin
if FColorMain = SOLID_PRIMARY_COLOR then
Result := TColorClass.Primary
else if FColorMain = SOLID_SECONDARY_COLOR then
Result := TColorClass.Secondary
else if FColorMain = SOLID_ERROR_COLOR then
Result := TColorClass.Error
else if FColorMain = SOLID_WARNING_COLOR then
Result := TColorClass.Warning
else if FColorMain = SOLID_SUCCESS_COLOR then
Result := TColorClass.Success
else if FColorMain = SOLID_BLACK then
Result := TColorClass.Normal
else
Result := TColorClass.Custom;
end;
function TSwitchField.GetFCheckedIconColor: TAlphaColor;
begin
Result := FColorMain;
end;
function TSwitchField.GetFIsChecked: Boolean;
begin
Result := FCircleMain.Margins.Left > 0;
end;
function TSwitchField.GetFTag: NativeInt;
begin
Result := TControl(Self).Tag;
end;
function TSwitchField.GetFText: String;
begin
Result := FText.Text;
end;
function TSwitchField.GetFTextSettings: TTextSettings;
begin
Result := FText.TextSettings;
end;
procedure TSwitchField.OnSwitchFieldClick(Sender: TObject);
begin
if FCircleMain.Margins.Left = -22 then
Enable
else
Disable;
if Assigned(FPointerOnClick) then
FPointerOnClick(Sender);
if Assigned(FPointerOnChange) then
FPointerOnChange(Sender);
end;
procedure TSwitchField.OnSwitchFieldMouseEnter(Sender: TObject);
begin
FCircleMainEffect.AnimateFloat('Opacity', 0.15, 0.2);
if Assigned(FPointerOnMouseEnter) then
FPointerOnMouseEnter(Sender);
end;
procedure TSwitchField.OnSwitchFieldMouseExit(Sender: TObject);
begin
FCircleMainEffect.AnimateFloat('Opacity', 0, 0.2);
if Assigned(FPointerOnMouseExit) then
FPointerOnMouseExit(Sender);
end;
procedure TSwitchField.SetFButtonClass(const Value: TColorClass);
begin
if Value = TColorClass.Primary then
FColorMain := SOLID_PRIMARY_COLOR
else if Value = TColorClass.Secondary then
FColorMain := SOLID_SECONDARY_COLOR
else if Value = TColorClass.Error then
FColorMain := SOLID_ERROR_COLOR
else if Value = TColorClass.Warning then
FColorMain := SOLID_WARNING_COLOR
else if Value = TColorClass.Normal then
FColorMain := SOLID_BLACK
else if Value = TColorClass.Success then
FColorMain := SOLID_SUCCESS_COLOR
else
FColorMain := TAlphaColor($FF323230);
ApplyColorChanges();
end;
procedure TSwitchField.ApplyColorChanges;
begin
if Self.IsChecked then
begin
FCircleMain.Fill.Color := FColorMain;
FCircleMainEffect.Fill.Color := FColorMain;
FRoundRectangle.Fill.Color := GetColorRoundRectangle(FColorMain);
end;
end;
procedure TSwitchField.SetFCheckedIconColor(const Value: TAlphaColor);
begin
FColorMain := Value;
ApplyColorChanges();
end;
procedure TSwitchField.SetFIsChecked(const Value: Boolean);
begin
if Value then
Enable
else
Disable;
end;
procedure TSwitchField.SetFTag(const Value: NativeInt);
begin
TControl(Self).Tag := Value;
end;
procedure TSwitchField.SetFText(const Value: String);
begin
FText.Text := Value;
end;
procedure TSwitchField.SetFTextSettings(const Value: TTextSettings);
begin
FText.TextSettings := Value;
end;
function TSwitchField.GetColorRoundRectangle(SolidColor: TAlphaColor): TAlphaColor;
var
Color: TAlphaColorRec;
begin
Color.Color := SolidColor;
Color.A := $96;
Result := Color.Color;
end;
end.
|
unit NumOrderFrame;
interface
uses
Windows, SysUtils, Classes, Graphics, Controls, Forms, ItemsDef, StdCtrls,
ExtCtrls, ActnList, ToolWin, ComCtrls, Core, Types, Contnrs, Buttons,
NxEdit;
type
TVisNumPage = class;
TLayoutDirection = (ldUpDown, ldLeftRight);
// Визуальный билет на листе
TVisTicket = class
public
Pos: TPoint;
Size: TPoint;
DrawRect: TRect;
Ticket: TTicket;
NumPlanItem: TNumPlanItem;
Order: integer;
VisNumPage: TVisNumPage;
Ordered: Boolean;
constructor Create(ANumPlanItem: TNumPlanItem);
procedure Save();
procedure Draw(c: TCanvas);
end;
// Список визуальных билетов
TVisTicketList = class (TObjectList)
public
function GetItem(Index: Integer): TVisTicket;
function GetItemByOrder(AOrder: Integer): TVisTicket;
procedure SortByOrder();
end;
// Визуальный лист
TVisNumPage = class
public
NumPage: TNumPage;
Size: TPoint;
DrawRect: TRect;
Name: string;
Order: integer;
Visible: Boolean;
VisTicketList: TObjectList;
constructor Create(ANumPlanItem: TNumPlanItem);
destructor Destroy; override;
procedure Save();
function GetTicket(Index: Integer): TVisTicket;
function GetTicketFromPos(Pos: TPoint): TVisTicket;
function AddTicket(ANumPlanItem: TNumPlanItem): TVisTicket;
end;
// Список визуальных листов
TVisPagesList = class (TObjectList)
public
function GetItem(Index: Integer): TVisNumPage;
function AddNumPlanItem(ANumPlanItem: TNumPlanItem): TVisTicket;
procedure SortByOrder();
end;
/// Двухмерный массив листов (страниц)
/// Заполняется сверху вниз слева направо
/// Также содержит размеры (в мм) колонок и рядов
TPagesArray = class(TObject)
private
FSizesActual: Boolean;
FSizesX: array of integer; // Максимумы размера листа по колонкам расклада
FSizesY: array of integer; // Максимумы размера листа по строкам расклада
FItems: array of array of TVisNumPage; // расклад листов
FLayout: TPoint; // параметры расклада
FItemsCount: Integer; // число листов в раскладе
FLayoutDirection: TLayoutDirection;
function FGetItem(X, Y: integer): TVisNumPage;
function FGetSizeX(Index: Integer): Integer;
function FGetSizeY(Index: Integer): Integer;
procedure SetLayout(Layout: TPoint);
procedure SetLayoutDirection(ld: TLayoutDirection);
procedure CalculateSizes();
public
MinItemSizeMM: TPoint; // Минимальный размер листа (для базового масштаба)
VisPagesList: TVisPagesList;
constructor Create();
destructor Destroy(); override;
procedure Clear();
procedure AddItem(Item: TVisNumPage);
procedure Save();
property Layout: TPoint read FLayout write SetLayout; // Параметры расклада
property LayoutDirection: TLayoutDirection read FLayoutDirection write SetLayoutDirection;
property Items[X, Y: Integer]: TVisNumPage read FGetItem; default; // расклад листок
property SizeX[Index: Integer]: Integer read FGetSizeX; // Максисмум ширины листа по колонке
property SizeY[Index: Integer]: Integer read FGetSizeY; // Максимум высоты листа по строке
end;
type
TframeNumOrder = class(TFrame)
tlbNumOrder: TToolBar;
actlstNumOrder: TActionList;
panImage: TPanel;
pbPreview: TPaintBox;
cbbCurNum: TComboBox;
sbPreview: TScrollBox;
actOK: TAction;
actClose: TAction;
actHelp: TAction;
actZoomPlus: TAction;
actZoomMinus: TAction;
actZoomFit: TAction;
actOptions: TAction;
btn1: TToolButton;
btnOptions: TToolButton;
lbCurOrder: TLabel;
btnZoomPlus: TToolButton;
btnZoomMinus: TToolButton;
btnZoomFit: TToolButton;
btn2: TToolButton;
btnOK: TToolButton;
btnClose: TToolButton;
btnHelp: TToolButton;
grpOptions: TGroupBox;
nsePagesInLine: TNxSpinEdit;
rgLayout: TRadioGroup;
lbPagesInDirection: TLabel;
nseMinPageSizeX: TNxSpinEdit;
nseMinPageSizeY: TNxSpinEdit;
nseBetweenPages: TNxSpinEdit;
lbMinPageSize: TLabel;
lbMPSX: TLabel;
lbBetweenPages: TLabel;
btnOptionsOK: TBitBtn;
btnOptionsCancel: TBitBtn;
actOptionsOK: TAction;
actOptionsCancel: TAction;
panOptions: TPanel;
actShowArrows: TAction;
btnShowArrows: TToolButton;
actInvalidate: TAction;
actUndo1: TAction;
btnInvalidate: TToolButton;
btn3: TToolButton;
btnUndo1: TToolButton;
procedure pbPreviewPaint(Sender: TObject);
procedure pbPreviewMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure DummyAction(Sender: TObject);
procedure actlstNumOrderExecute(Action: TBasicAction;
var Handled: Boolean);
procedure sbPreviewMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
private
{ Private declarations }
PreviewParams: TPreviewParams;
Scale: Real;
CurOrder: Integer;
ViewMode: AnsiChar;
PagesArray: TPagesArray;
VisTicketList: TVisTicketList;
UndoList: TVisTicketList;
// Options
ShowPageTplName: Boolean;
MinPageSize: TPoint;
BetweenPages: Integer;
PagesInLine: Integer;
LayoutDirection: TLayoutDirection;
procedure SetPreviewParams();
procedure UpdatePreview();
procedure DrawTicket(Canvas: TCanvas; BasePoint: TPoint; VisTicket: TVisTicket; Text: string);
function GetPageFromPos(Pos: TPoint): TVisNumPage;
function GetTicketFromPos(Pos: TPoint): TVisTicket;
procedure OptionsMod(Action: string);
public
{ Public declarations }
NumProject: TNumProject;
PageID: Integer;
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
function Start(): boolean;
end;
const
BETWEEN_PAGES = 20; // Промежуток между листами
MIN_PAGE_X_PP = 100; // Мин. ширина страницы
MIN_PAGE_Y_PP = 100; // Мин. высота страницы
implementation
uses MainForm;
{$R *.dfm}
// === TTicketVisual ===
constructor TVisTicket.Create(ANumPlanItem: TNumPlanItem);
begin
if not Assigned(ANumPlanItem) then Exit;
NumPlanItem:=ANumPlanItem;
Order:=NumPlanItem.Order;
if not Assigned(ANumPlanItem.Ticket) then Exit;
Ticket:=NumPlanItem.Ticket;
Pos:=Ticket.Position;
if not Assigned(Ticket.Tpl) then Exit;
Size:=Ticket.Tpl.Size;
Ordered:=False;
end;
procedure TVisTicket.Save();
var
tmpNumPage: TNumPage;
NumProject: TNumProject;
begin
//tmpNumPage:=NumPlanItem.NumPage;
NumProject:=NumPlanItem.Project;
NumPlanItem:=NumProject.NumPlanItems.GetItemByOrder(Order);
if not Assigned(NumPlanItem) then Exit;
NumPlanItem.Ticket:=Ticket;
NumPlanItem.NumPage:=VisNumPage.NumPage;
//NumPlanItem.Order:=Order;
NumPlanItem.Write();
end;
procedure TVisTicket.Draw(c: TCanvas);
begin
end;
// === TVisTicketList ===
function TVisTicketList.GetItem(Index: Integer): TVisTicket;
begin
Result:=(Items[Index] as TVisTicket);
end;
function TVisTicketList.GetItemByOrder(AOrder: Integer): TVisTicket;
var
i: Integer;
begin
Result:=nil;
for i:=0 to Count-1 do
begin
if GetItem(i).Order=AOrder then
begin
Result:=GetItem(i);
Break;
end;
end;
end;
function VisTicketListSort(Item1, Item2: Pointer): Integer;
begin
Result:=TVisTicket(Item2).Order-TVisTicket(Item1).Order;
end;
procedure TVisTicketList.SortByOrder();
begin
Self.Sort(@VisTicketListSort);
end;
// === TVisNumPage ===
constructor TVisNumPage.Create(ANumPlanItem: TNumPlanItem);
begin
if not Assigned(ANumPlanItem) then Exit;
if not Assigned(ANumPlanItem.NumPage) then Exit;
NumPage:=ANumPlanItem.NumPage;
Order:=NumPage.Order;
if not Assigned(NumPage.NumPageTpl) then Exit;
Size:=NumPage.NumPageTpl.Size;
Name:=NumPage.NumPageTpl.Name;
// Items
VisTicketList:=TObjectList.Create(true);
end;
destructor TVisNumPage.Destroy();
begin
FreeAndNil(VisTicketList);
end;
procedure TVisNumPage.Save();
begin
NumPage.Order:=Order;
NumPage.Write();
end;
function TVisNumPage.GetTicket(Index: Integer): TVisTicket;
begin
Result:=nil;
if Index >= VisTicketList.Count then Exit;
Result:=(VisTicketList.Items[Index] as TVisTicket);
end;
function TVisNumPage.GetTicketFromPos(Pos: TPoint): TVisTicket;
var
i: Integer;
VisTicket: TVisTicket;
r: TRect;
begin
Result:=nil;
for i:=0 to VisTicketList.Count-1 do
begin
VisTicket:=(VisTicketList[i] as TVisTicket);
r:=Bounds(VisTicket.Pos.X, VisTicket.Pos.Y, VisTicket.Size.X, VisTicket.Size.Y);
if PtInRect(r, Pos) then
begin
Result:=VisTicket;
Exit;
end;
end;
end;
function TVisNumPage.AddTicket(ANumPlanItem: TNumPlanItem): TVisTicket;
var
i: Integer;
begin
for i:=0 to VisTicketList.Count-1 do
begin
if (VisTicketList.Items[i] as TVisTicket).NumPlanItem = ANumPlanItem then
begin
Result:=(VisTicketList.Items[i] as TVisTicket);
Exit;
end;
end;
Result:=TVisTicket.Create(ANumPlanItem);
Result.VisNumPage:=Self;
VisTicketList.Add(Result);
end;
// === TVisPagesList ===
function TVisPagesList.GetItem(Index: Integer): TVisNumPage;
begin
Result:=(Self.Items[Index] as TVisNumPage);
end;
function TVisPagesList.AddNumPlanItem(ANumPlanItem: TNumPlanItem): TVisTicket;
var
i: Integer;
NumPage: TNumPage;
VisNumPage: TVisNumPage;
begin
Result:=nil;
NumPage:=ANumPlanItem.NumPage;
for i:=0 to self.Count-1 do
begin
VisNumPage:=(Self.Items[i] as TVisNumPage);
if VisNumPage.NumPage = NumPage then
begin
Result:=VisNumPage.AddTicket(ANumPlanItem);
Exit;
end;
end;
VisNumPage:=TVisNumPage.Create(ANumPlanItem);
Self.Add(VisNumPage);
Result:=VisNumPage.AddTicket(ANumPlanItem);
end;
function VisPagesListSort(Item1, Item2: Pointer): Integer;
begin
Result:=TVisNumPage(Item1).Order-TVisNumPage(Item2).Order;
end;
procedure TVisPagesList.SortByOrder();
begin
Self.Sort(@VisPagesListSort);
end;
// === TPagesArray ===
constructor TPagesArray.Create();
begin
FSizesActual:=False;
SetLength(FSizesX, 0);
SetLength(FSizesY, 0);
SetLength(FItems, 0);
FItemsCount:=0;
MinItemSizeMM:=Point(MaxInt, MaxInt);
VisPagesList:=TVisPagesList.Create(True);
end;
destructor TPagesArray.Destroy();
begin
FreeAndNil(VisPagesList);
SetLength(FItems, 0);
SetLength(FSizesY, 0);
SetLength(FSizesX, 0);
inherited Destroy();
end;
procedure TPagesArray.Clear();
var
x, y: Integer;
begin
FItemsCount:=0;
for x:=Low(FItems) to High(FItems) do
begin
for y:=Low(FItems[x]) to High(FItems[x]) do
begin
FItems[x, y]:=nil;
end;
end;
end;
procedure TPagesArray.AddItem(Item: TVisNumPage);
var
x, y: Integer;
NumPageTpl: TNumPageTpl;
begin
// вычислим номер следующей вободной колонки и ряда
if FLayoutDirection = ldUpDown then
begin
if Layout.Y = 0 then Exit;
x:=(FItemsCount div Layout.Y);
if x >= Layout.X then Exit;
y:=FItemsCount-(Layout.Y * x);
if y >= Layout.Y then Exit;
end
else
begin
if Layout.X = 0 then Exit;
y:=(FItemsCount div Layout.X);
if y >= Layout.Y then Exit;
x:=FItemsCount-(Layout.X * y);
if x >= Layout.X then Exit;
end;
// Установим лист в заданную точку
FItems[x, y]:=Item;
Inc(FItemsCount);
FSizesActual:=False;
end;
function TPagesArray.FGetItem(X, Y: integer): TVisNumPage;
begin
Result:=nil;
if Y >= Layout.Y then Exit;
if X >= Layout.X then Exit;
Result:=FItems[X, Y];
end;
procedure TPagesArray.Save();
var
x, y: Integer;
VisNumPage: TVisNumPage;
begin
StartTransaction();
for x:=0 to self.VisPagesList.Count-1 do
begin
VisNumPage:=VisPagesList.GetItem(x);
VisNumPage.Save();
for y:=0 to VisNumPage.VisTicketList.Count-1 do
begin
if Assigned(VisNumPage.VisTicketList[y]) then
begin
(VisNumPage.VisTicketList[y] as TVisTicket).Save();
end;
end;
end;
CloseTransaction();
end;
procedure TPagesArray.SetLayoutDirection(ld: TLayoutDirection);
begin
if ld <> FLayoutDirection then
begin
FLayoutDirection:=ld;
SetLayout(FLayout);
end;
end;
procedure TPagesArray.SetLayout(Layout: TPoint);
var
x, y: Integer;
List: TList;
begin
// Сохранение всех листов в список
List:=TList.Create();
for x:=Low(FItems) to High(FItems) do
begin
for y:=Low(FItems[x]) to High(FItems[x]) do
begin
List.Add(FItems[x, y]);
end;
end;
// Переформировка массива
FSizesActual:=False;
FLayout:=Layout;
SetLength(FItems, FLayout.X);
for x:=Low(FItems) to High(FItems) do
begin
SetLength(FItems[x], FLayout.Y);
end;
// Перезаполнение массива
for x:=0 to FItemsCount-1 do
begin
AddItem(TVisNumPage(List[x]));
end;
List.Free();
CalculateSizes();
end;
procedure TPagesArray.CalculateSizes();
var
x, y, sx, sy: Integer;
VisNumPage: TVisNumPage;
begin
// Сброс размеров
MinItemSizeMM:=Point(MaxInt, MaxInt);
SetLength(FSizesX, FLayout.X);
SetLength(FSizesY, FLayout.Y);
for x:=Low(FSizesX) to High(FSizesX) do FSizesX[x]:=0;
for y:=Low(FSizesY) to High(FSizesY) do FSizesY[y]:=0;
// Определяем размеры
for x:=Low(FItems) to High(FItems) do
begin
for y:=Low(FItems[x]) to High(FItems[x]) do
begin
VisNumPage:=Items[x, y];
if not Assigned(VisNumPage) then Continue;
// Размер листа
sx:=VisNumPage.Size.X;
sy:=VisNumPage.Size.Y;
// Максимальный размер листа для колонки и ряда
if sx > FSizesX[x] then FSizesX[x]:=sx;
if sy > FSizesY[y] then FSizesY[y]:=sy;
// Обновим минимальный размер листа
if sx < MinItemSizeMM.X then MinItemSizeMM.X := sx;
if sy < MinItemSizeMM.Y then MinItemSizeMM.Y := sy;
end;
end;
FSizesActual:=True;
end;
function TPagesArray.FGetSizeX(Index: Integer): Integer;
begin
if not FSizesActual then CalculateSizes();
Result:=FSizesX[Index];
end;
function TPagesArray.FGetSizeY(Index: Integer): Integer;
begin
if not FSizesActual then CalculateSizes();
Result:=FSizesY[Index];
end;
// ===
procedure SetPen(c: TCanvas; Color: TColor; Mode: TPenMode; Style: TPenStyle; Width: Integer);
begin
c.Pen.Color:=Color;
c.Pen.Mode:=Mode;
c.Pen.Style:=Style;
c.Pen.Width:=Width;
end;
procedure SetBrush(c: TCanvas; Color: TColor; Style: TBrushStyle);
begin
c.Brush.Color:=Color;
c.Brush.Style:=Style;
end;
// === TframeNumOrder ===
constructor TframeNumOrder.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Scale:=1;
panImage.DoubleBuffered:=True;
sbPreview.DoubleBuffered:=True;
PagesArray:=TPagesArray.Create();
VisTicketList:=TVisTicketList.Create(False);
UndoList:=TVisTicketList.Create(False);
OptionsMod('init');
//
//Created:=True;
//ChangeLanguage();
end;
destructor TframeNumOrder.Destroy();
begin
FreeAndNil(UndoList);
FreeAndNil(VisTicketList);
FreeAndNil(PagesArray);
//Created:=False;
inherited Destroy();
end;
function TframeNumOrder.Start(): boolean;
var
i: Integer;
VisTicket: TVisTicket;
begin
Result:=False;
if not Assigned(NumProject) then Exit;
OptionsMod('load');
// Set view mode
ViewMode:='v';
// Fill tickets list
PagesArray.VisPagesList.Clear();
cbbCurNum.Clear();
for i:=0 to NumProject.NumPlanItems.Count-1 do
begin
VisTicket:=PagesArray.VisPagesList.AddNumPlanItem(NumProject.NumPlanItems[i]);
VisTicketList.Add(VisTicket);
cbbCurNum.AddItem(IntToStr(i+1), nil);
end;
VisTicketList.SortByOrder();
PagesArray.VisPagesList.SortByOrder();
if cbbCurNum.Items.Count>0 then cbbCurNum.ItemIndex:=0;
SetPreviewParams();
ShowPageTplName:=True;
// Update preview
UpdatePreview();
Result:=True;
end;
procedure TframeNumOrder.SetPreviewParams();
var
//Canvas: TCanvas;
kx, ky: Real;
PreviewSize: TSize;
i, Cols: Integer;
sx, sy: Integer;
begin
// Назначаем расклад
PagesArray.Clear();
PagesArray.LayoutDirection:=LayoutDirection;
if NumProject.Pages.Count=0 then Exit;
Cols:=PagesInLine;
if LayoutDirection = ldUpDown then
begin
PagesArray.Layout:=Point((NumProject.Pages.Count div Cols)+1, Cols);
end
else
begin
PagesArray.Layout:=Point(Cols, (NumProject.Pages.Count div Cols)+1)
end;
//for i:=0 to NumProject.Pages.Count-1 do PagesArray.AddItem(NumProject.Pages[i]);
for i:=0 to PagesArray.VisPagesList.Count-1 do PagesArray.AddItem(PagesArray.VisPagesList.GetItem(i));
// Вычислим размер расклада листов (в мм)
sx:=0;
sy:=0;
for i:=0 to PagesArray.Layout.X-1 do
begin
sx:=sx+PagesArray.SizeX[i];
end;
for i:=0 to PagesArray.Layout.Y-1 do sy:=sy+PagesArray.SizeY[i];
// Вычисляем коэффициент размера для базового масштаба
// Масштаб считаем от минимального размера листа
// чтобы лист не был слишком мелким на экране
if PagesArray.MinItemSizeMM.X = 0 then Exit;
if PagesArray.MinItemSizeMM.Y = 0 then Exit;
kx := MinPageSize.X / PagesArray.MinItemSizeMM.X;
ky := MinPageSize.Y / PagesArray.MinItemSizeMM.Y;
// Задаем общий коэффициент базового масштаба и общий размер вида расклада
with PreviewParams do
begin
if kx < ky then
begin
k:=kx*Scale;
end
else
begin
k:=ky*Scale;
end;
PreviewSize.cx:=Round(sx*k)+((PagesArray.Layout.X-1) * BetweenPages);
PreviewSize.cy:=Round(sy*k)+((PagesArray.Layout.Y-1) * BetweenPages);
CanvasSize.cx:=PreviewSize.cx+16;
CanvasSize.cy:=PreviewSize.cy+16;
SizeMm.cx:=sx;
SizeMm.cy:=sy;
// Границы рабочей области
BordersRect.Left:=(CanvasSize.cx-PreviewSize.cx) div 2;
BordersRect.Top:=(CanvasSize.cy-PreviewSize.cy) div 2;
BordersRect.Right:=BordersRect.Left+PreviewSize.cx;
BordersRect.Bottom:=BordersRect.Top+PreviewSize.cy;
// Установим полный размер изображения
pbPreview.Width:=CanvasSize.cx;
pbPreview.Height:=CanvasSize.cy;
end;
end;
procedure TframeNumOrder.DrawTicket(Canvas: TCanvas; BasePoint: TPoint; VisTicket: TVisTicket; Text: string);
var
r: TRect;
x,y,sx,sy: Integer;
nx, ny, nsx, nsy: Integer;
begin
if not Assigned(VisTicket) then Exit;
with PreviewParams do
begin
x:=BasePoint.X+Round(VisTicket.Pos.X*k);
y:=BasePoint.Y+Round(VisTicket.Pos.Y*k);
sx:=Round(VisTicket.Size.X*k);
sy:=Round(VisTicket.Size.Y*k);
r:=Bounds(x, y, sx, sy);
VisTicket.DrawRect:=r;
SetPen(Canvas, clBlack, pmCopy, psSolid, 1);
SetBrush(Canvas, clWhite, bsSolid);
if VisTicket.Ordered then SetBrush(Canvas, clMoneyGreen, bsSolid);
Canvas.Rectangle(r);
if Length(Text)=0 then Text:=IntToStr(VisTicket.Order);
nsx:=Canvas.TextWidth(Text);
nsy:=Canvas.TextHeight(Text);
nx:=x+((sx-nsx) div 2);
ny:=y+((sy-nsy) div 2);
Canvas.TextOut(nx, ny, Text);
end;
end;
function TframeNumOrder.GetPageFromPos(Pos: TPoint): TVisNumPage;
var
//RealPoint: TPoint;
i: Integer;
VisNumPage: TVisNumPage;
begin
Result:=nil;
// Вычисляем точку клика на холсте
// Точка клика уже на холсте!
// Находим нужный лист
for i:=0 to PagesArray.VisPagesList.Count-1 do
begin
VisNumPage:=PagesArray.VisPagesList.GetItem(i);
if PtInRect(VisNumPage.DrawRect, Pos) then
begin
Result:=VisNumPage;
Exit;
end;
end;
end;
function TframeNumOrder.GetTicketFromPos(Pos: TPoint): TVisTicket;
var
//RealPoint: TPoint;
PointMM: TPoint;
i: Integer;
VisNumPage: TVisNumPage;
begin
Result:=nil;
// Вычисляем точку клика на холсте
// Точка клика уже на холсте!
// Находим нужный лист
VisNumPage:=GetPageFromPos(Pos);
if not Assigned(VisNumPage) then Exit;
// Переводим точку клика в миллиметры внутри листа
if PreviewParams.k = 0 then Exit;
PointMM.X:=Round((Pos.X-VisNumPage.DrawRect.Left)/PreviewParams.k);
PointMM.Y:=Round((Pos.Y-VisNumPage.DrawRect.Top)/PreviewParams.k);
Result:=VisNumPage.GetTicketFromPos(PointMM);
end;
procedure TframeNumOrder.UpdatePreview();
var
r, r1: TRect;
x,y,sx,sy, i, ic, n, nc, m: Integer;
ix, iy: Integer;
Ticket: TTicket;
TicketTpl: TTicketTpl;
VisTicket, VisTicket2: TVisTicket;
VisNumPage: TVisNumPage;
Canvas: TCanvas;
s: string;
TempNpi, Npi2: TNumPlanItem;
//LogFont: TLogFont;
bmp: TBitmap;
begin
//SetPreviewParams();
with PreviewParams do
begin
VisibleRect:=sbPreview.ClientRect;
OffsetRect(VisibleRect, sbPreview.HorzScrollBar.Position, sbPreview.VertScrollBar.Position);
bmp:=TBitmap.Create();
bmp.Width:=pbPreview.Width;
bmp.Height:=pbPreview.Height;
//Canvas:=imgPreview.Canvas;
//Canvas:=pbPreview.Canvas;
Canvas:=bmp.Canvas;
Canvas.Lock();
// Clear canvas
SetBrush(Canvas, clWhite, bsSolid);
Canvas.FillRect(Bounds(0, 0, CanvasSize.cx, CanvasSize.cy));
//SetPen(Canvas, clBlack, pmCopy, psSolid, 1);
//SetBrush(Canvas, clWhite, bsSolid);
//Canvas.Rectangle(PreviewParams.BordersRect);
// Draw pages
ic:=0;
for ix:=0 to PagesArray.Layout.X-1 do
begin
for iy:=0 to PagesArray.Layout.Y-1 do
begin
VisNumPage:=PagesArray[ix, iy];
if not Assigned(VisNumPage) then Continue;
// Page rectangle
x:=BordersRect.Left+(Round(PagesArray.SizeX[ix]*k)*ix)+(BetweenPages*ix);
y:=BordersRect.Top+(Round(PagesArray.SizeY[iy]*k)*iy)+(BetweenPages*iy);
sx:=Round(VisNumPage.Size.X*k);
sy:=Round(VisNumPage.Size.Y*k);
r:=Bounds(x, y, sx, sy);
VisNumPage.Visible:=IntersectRect(r1, VisibleRect, r);
if not VisNumPage.Visible then Continue;
SetPen(Canvas, clBlack, pmCopy, psSolid, 1);
SetBrush(Canvas, clInfoBk, bsSolid);
Canvas.Rectangle(r);
VisNumPage.DrawRect:=r;
if ShowPageTplName then
begin
s:=IntToStr(VisNumPage.Order)+' - '+VisNumPage.Name;
Canvas.TextOut(x, y+Canvas.Font.Height, s);
end;
// Draw tickets
for i:=0 to VisNumPage.VisTicketList.Count-1 do
begin
DrawTicket(Canvas, Point(x, y), (VisNumPage.VisTicketList[i] as TVisTicket), '');
end;
Inc(ic);
end;
end;
// Draw arrows
if actShowArrows.Checked then
begin
VisTicket2:=nil;
VisTicket:=nil;
for m:=0 to VisTicketList.Count-1 do
begin
if m>0 then VisTicket2:=VisTicket;
VisTicket:=VisTicketList.GetItem(m);
if not Assigned(VisTicket) then Continue;
if not Assigned(VisTicket2) then Continue;
if not VisTicket.VisNumPage.Visible then Continue;
if not VisTicket2.VisNumPage.Visible then Continue;
if m>0 then
begin
x:=VisTicket.DrawRect.Left+(VisTicket.DrawRect.Right-VisTicket.DrawRect.Left) div 2;
y:=VisTicket.DrawRect.Top+(VisTicket.DrawRect.Bottom-VisTicket.DrawRect.Top) div 2;
sx:=VisTicket2.DrawRect.Left+(VisTicket2.DrawRect.Right-VisTicket2.DrawRect.Left) div 2;
sy:=VisTicket2.DrawRect.Top+(VisTicket2.DrawRect.Bottom-VisTicket2.DrawRect.Top) div 2;
DrawArrowLine(Canvas, Point(x, y), Point(sx, sy), k);
end;
end;
end;
{$IFDEF DEBUG}
{s:='VisibleRect=('
+IntToStr(VisibleRect.Left)+','
+IntToStr(VisibleRect.Top)+','
+IntToStr(VisibleRect.Right)+','
+IntToStr(VisibleRect.Bottom)+')';
s:=s+' VisiblePages='+IntToStr(ic);
Core.StatusMsg(s);}
{$ENDIF}
BitBlt(pbPreview.Canvas.Handle, 0, 0, bmp.Width, bmp.Height, bmp.Canvas.Handle, 0, 0, SRCCOPY );
// BitBlt(pbPreview.Canvas.Handle,
// VisibleRect.Left,
// VisibleRect.Top,
// VisibleRect.Right-VisibleRect.Left,
// VisibleRect.Bottom-VisibleRect.Top,
// bmp.Canvas.Handle,
// VisibleRect.Left,
// VisibleRect.Top,
// SRCCOPY );
end;
Canvas.Unlock();
FreeAndNil(bmp);
end;
procedure TframeNumOrder.pbPreviewPaint(Sender: TObject);
begin
UpdatePreview();
end;
procedure TframeNumOrder.pbPreviewMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
VisTicket, VisTicket2: TVisTicket;
s: string;
n: Integer;
begin
if Assigned(self.Parent) then Self.sbPreview.SetFocus(); // For mouse wheel handling
VisTicket:=GetTicketFromPos(Point(X, Y));
if not Assigned(VisTicket) then Exit;
s:='x='+IntToStr(VisTicket.Pos.X)+' y='+IntToStr(VisTicket.Pos.Y)+' order='+IntToStr(VisTicket.Order);
Core.AddCmd('STATUS '+s);
if (ssLeft in Shift) then
begin
if (ssShift in Shift) or (actInvalidate.Checked) then
begin
if not VisTicket.Ordered then Exit;
VisTicket.Ordered:=False;
UndoList.Extract(VisTicket);
end
else
begin
if VisTicket.Ordered then Exit;
VisTicket.Ordered:=True;
n:=StrToIntDef(cbbCurNum.Text, 1);
VisTicket2:=VisTicketList.GetItemByOrder(n);
if Assigned(VisTicket2) then VisTicket2.Order:=VisTicket.Order;
VisTicket.Order:=n;
Inc(n);
cbbCurNum.Text:=IntToStr(n);
VisTicketList.SortByOrder();
UndoList.Add(VisTicket);
if UndoList.Count>0 then actUndo1.Enabled:=True;
end;
UpdatePreview();
end;
end;
procedure TframeNumOrder.DummyAction(Sender: TObject);
begin
//
end;
procedure TframeNumOrder.actlstNumOrderExecute(Action: TBasicAction;
var Handled: Boolean);
var
VisTicket: TVisTicket;
begin
if Action = actOK then
begin
PagesArray.Save();
OptionsMod('save');
NumProject.NumPlanItems.SortByOrder();
Core.AddCmd('REFRESH TICKETS_LIST');
Core.AddCmd('REFRESH NUM_PLAN');
Core.AddCmd('CLOSE '+IntToStr(PageID));
end
else if Action = actClose then
begin
Core.AddCmd('CLOSE '+IntToStr(PageID));
end
else if Action = actHelp then
begin
Application.HelpCommand(HELP_CONTEXT, 11);
end
else if Action = actZoomPlus then
begin
Scale:=Scale+0.2;
SetPreviewParams();
UpdatePreview();
end
else if Action = actZoomMinus then
begin
Scale:=Scale-0.2;
if Scale=0 then Scale:=0.2;
SetPreviewParams();
UpdatePreview();
end
else if Action = actZoomFit then
begin
Scale:=1;
SetPreviewParams();
UpdatePreview();
end
else if Action = actOptions then
begin
rgLayout.ItemIndex:=Ord(LayoutDirection);
nsePagesInLine.AsInteger:=PagesInLine;
nseMinPageSizeX.AsInteger:=MinPageSize.X;
nseMinPageSizeY.AsInteger:=MinPageSize.Y;
nseBetweenPages.AsInteger:=BetweenPages;
panOptions.Visible:=True;
end
else if Action = actOptionsOK then
begin
LayoutDirection:=ldUpDown;
if rgLayout.ItemIndex=1 then LayoutDirection:=ldLeftRight;
PagesInLine:=nsePagesInLine.AsInteger;
MinPageSize.X:=nseMinPageSizeX.AsInteger;
MinPageSize.Y:=nseMinPageSizeY.AsInteger;
BetweenPages:=nseBetweenPages.AsInteger;
panOptions.Visible:=False;
SetPreviewParams();
UpdatePreview();
end
else if Action = actOptionsCancel then
begin
panOptions.Visible:=False;
end
else if Action = actShowArrows then
begin
UpdatePreview();
end
else if Action = actInvalidate then
begin
end
else if Action = actUndo1 then
begin
if UndoList.Count=0 then Exit;
VisTicket:=UndoList.GetItem(UndoList.Count-1);
if not VisTicket.Ordered then Exit;
VisTicket.Ordered:=False;
UndoList.Extract(VisTicket);
if UndoList.Count=0 then actUndo1.Enabled:=False;
UpdatePreview();
end;
end;
procedure TframeNumOrder.sbPreviewMouseWheel(Sender: TObject;
Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint;
var Handled: Boolean);
begin
//sbPreview.VertScrollBar.Position:=sbPreview.VertScrollBar.Position-WheelDelta;
if WheelDelta > 0 then
begin
sbPreview.VertScrollBar.Position:=sbPreview.VertScrollBar.Position-20;
end
else if WheelDelta < 0 then
begin
sbPreview.VertScrollBar.Position:=sbPreview.VertScrollBar.Position+20;
end;
end;
procedure TframeNumOrder.OptionsMod(Action: string);
var
n: Integer;
Options: TProjectOptionList;
begin
if Action = 'load' then
begin
if not Assigned(NumProject) then Exit;
Options:=NumProject.Options;
n:=Ord(LayoutDirection);
n:=StrToIntDef(Options.Params['order_layout_direction'], n);
LayoutDirection := ldUpDown;
if n = 1 then LayoutDirection := ldLeftRight;
PagesInLine:=StrToIntDef(Options.Params['order_pages_in_line'], PagesInLine);
MinPageSize.X:=StrToIntDef(Options.Params['order_min_page_size_x'], MinPageSize.X);
MinPageSize.Y:=StrToIntDef(Options.Params['order_min_page_size_y'], MinPageSize.Y);
BetweenPages:=StrToIntDef(Options.Params['order_between_pages'], BetweenPages);
end
else if Action = 'save' then
begin
if not Assigned(NumProject) then Exit;
Options:=NumProject.Options;
Options.Params['order_layout_direction']:=IntToStr(Ord(LayoutDirection));
Options.Params['order_pages_in_line']:=IntToStr(PagesInLine);
Options.Params['order_min_page_size_x']:=IntToStr(MinPageSize.X);
Options.Params['order_min_page_size_y']:=IntToStr(MinPageSize.Y);
Options.Params['order_between_pages']:=IntToStr(BetweenPages);
Options.SaveToBase();
end
else if Action = 'init' then
begin
LayoutDirection := ldUpDown;
PagesInLine:=5;
MinPageSize:=Point(MIN_PAGE_X_PP, MIN_PAGE_Y_PP);
BetweenPages:=BETWEEN_PAGES;
end;
end;
end.
|
unit ARCH_REG_Estadisticas;
interface
uses FUNC_REG_Estadisticas;
Const
Directorio_Estadisticas = '.\Datos\Datos Estadisticas.dat';
type
ARCHIVO_Estadisticas = File of REG_Estadisticas;
procedure Abrir_archivo_estadisticas_para_lectura_escritura(VAR ARCH_Estadisticas: ARCHIVO_Estadisticas);
procedure cargar_un_elemento_del_archivo_estadisticas_una_posicion_especifica(VAR ARCH_Estadisticas: ARCHIVO_Estadisticas; VAR R_Estadisticas : REG_Estadisticas; pos: LongInt);
procedure Guarda_Registro_Estadisticas(VAR ARCH_Estadisticas: ARCHIVO_Estadisticas; R_Estadisticas : REG_Estadisticas);
procedure Sobre_escribir_un_elemento_en_archivo_Estadisticas(VAR ARCH_Estadisticas: ARCHIVO_Estadisticas; R_Estadisticas : REG_Estadisticas; pos: LongInt);
implementation
procedure Abrir_archivo_estadisticas_para_lectura_escritura(VAR ARCH_Estadisticas: ARCHIVO_Estadisticas);
const
Directorio = Directorio_Estadisticas;
begin
assign(ARCH_Estadisticas, Directorio);
{$I-} reset(ARCH_Estadisticas); {$I+}
end;
procedure Sobre_escribir_un_elemento_en_archivo_Estadisticas(VAR ARCH_Estadisticas: ARCHIVO_Estadisticas; R_Estadisticas : REG_Estadisticas; pos: LongInt);
begin
seek(ARCH_Estadisticas, pos);
write(ARCH_Estadisticas, R_Estadisticas);
end;
procedure cargar_un_elemento_del_archivo_estadisticas_una_posicion_especifica(VAR ARCH_Estadisticas: ARCHIVO_Estadisticas; VAR R_Estadisticas : REG_Estadisticas; pos: LongInt);
begin
Seek(ARCH_Estadisticas, pos);
Read(ARCH_Estadisticas, R_Estadisticas);
end;
procedure Guarda_Registro_Estadisticas(VAR ARCH_Estadisticas: ARCHIVO_Estadisticas; R_Estadisticas : REG_Estadisticas);
begin
Abrir_archivo_estadisticas_para_lectura_escritura(ARCH_Estadisticas);
if ioresult <> 0 then
begin
rewrite(ARCH_Estadisticas);
R_Estadisticas.ID:= FileSize(ARCH_Estadisticas) + 1;
Sobre_escribir_un_elemento_en_archivo_Estadisticas(ARCH_Estadisticas, R_Estadisticas, 0);
end
else
begin
R_Estadisticas.ID:= FileSize(ARCH_Estadisticas) + 1;
Sobre_escribir_un_elemento_en_archivo_Estadisticas(ARCH_Estadisticas, R_Estadisticas, filesize(ARCH_Estadisticas));
end;
close(ARCH_Estadisticas);
end;
end. |
program ProcessorInformation;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, TypInfo, SysUtils, uSMBIOS
{ you can add units after this };
//http://tondrej.blogspot.com/2007/10/settostring-stringtoset.html
function GetOrdValue(Info: PTypeInfo; const SetParam): Integer;
begin
Result := 0;
case GetTypeData(Info)^.OrdType of
otSByte, otUByte:
Result := Byte(SetParam);
otSWord, otUWord:
Result := Word(SetParam);
otSLong, otULong:
Result := Integer(SetParam);
end;
end;
function SetToString(Info: PTypeInfo; const SetParam; Brackets: Boolean): String;
var
S: TIntegerSet;
TypeInfo: PTypeInfo;
I: Integer;
begin
Result := '';
Integer(S) := GetOrdValue(Info, SetParam);
TypeInfo := GetTypeData(Info)^.CompType;
for I := 0 to SizeOf(Integer) * 8 - 1 do
if I in S then
begin
if Result <> '' then
Result := Result + ',';
Result := Result + GetEnumName(TypeInfo, I);
end;
if Brackets then
Result := '[' + Result + ']';
end;
procedure GetPtrocessorInfo;
Var
SMBios: TSMBios;
LProcessorInfo: TProcessorInformation;
LSRAMTypes: TCacheSRAMTypes;
begin
SMBios:=TSMBios.Create;
try
WriteLn('Processor Information');
if SMBios.HasProcessorInfo then
for LProcessorInfo in SMBios.ProcessorInfo do
begin
WriteLn('Manufacter '+LProcessorInfo.ProcessorManufacturerStr);
WriteLn('Socket Designation '+LProcessorInfo.SocketDesignationStr);
WriteLn('Type '+LProcessorInfo.ProcessorTypeStr);
WriteLn('Familiy '+LProcessorInfo.ProcessorFamilyStr);
WriteLn('Version '+LProcessorInfo.ProcessorVersionStr);
WriteLn(Format('Processor ID %x',[LProcessorInfo.RAWProcessorInformation^.ProcessorID]));
WriteLn(Format('Voltaje %n',[LProcessorInfo.GetProcessorVoltaje]));
WriteLn(Format('External Clock %d Mhz',[LProcessorInfo.RAWProcessorInformation^.ExternalClock]));
WriteLn(Format('Maximum processor speed %d Mhz',[LProcessorInfo.RAWProcessorInformation^.MaxSpeed]));
WriteLn(Format('Current processor speed %d Mhz',[LProcessorInfo.RAWProcessorInformation^.CurrentSpeed]));
WriteLn('Processor Upgrade '+LProcessorInfo.ProcessorUpgradeStr);
WriteLn(Format('External Clock %d Mhz',[LProcessorInfo.RAWProcessorInformation^.ExternalClock]));
if SMBios.SmbiosVersion>='2.3' then
begin
WriteLn('Serial Number '+LProcessorInfo.SerialNumberStr);
WriteLn('Asset Tag '+LProcessorInfo.AssetTagStr);
WriteLn('Part Number '+LProcessorInfo.PartNumberStr);
if SMBios.SmbiosVersion>='2.5' then
begin
WriteLn(Format('Core Count %d',[LProcessorInfo.RAWProcessorInformation^.CoreCount]));
WriteLn(Format('Cores Enabled %d',[LProcessorInfo.RAWProcessorInformation^.CoreEnabled]));
WriteLn(Format('Threads Count %d',[LProcessorInfo.RAWProcessorInformation^.ThreadCount]));
WriteLn(Format('Processor Characteristics %.4x',[LProcessorInfo.RAWProcessorInformation^.ProcessorCharacteristics]));
end;
end;
Writeln;
if (LProcessorInfo.RAWProcessorInformation^.L1CacheHandle>0) and (LProcessorInfo.L2Chache<>nil) then
begin
WriteLn('L1 Cache Handle Info');
WriteLn('--------------------');
WriteLn(' Socket Designation '+LProcessorInfo.L1Chache.SocketDesignationStr);
WriteLn(Format(' Cache Configuration %.4x',[LProcessorInfo.L1Chache.RAWCacheInformation^.CacheConfiguration]));
WriteLn(Format(' Maximum Cache Size %d Kb',[LProcessorInfo.L1Chache.GetMaximumCacheSize]));
WriteLn(Format(' Installed Cache Size %d Kb',[LProcessorInfo.L1Chache.GetInstalledCacheSize]));
LSRAMTypes:=LProcessorInfo.L1Chache.GetSupportedSRAMType;
WriteLn(Format(' Supported SRAM Type %s',[SetToString(TypeInfo(TCacheSRAMTypes), LSRAMTypes, True)]));
LSRAMTypes:=LProcessorInfo.L1Chache.GetCurrentSRAMType;
WriteLn(Format(' Current SRAM Type %s',[SetToString(TypeInfo(TCacheSRAMTypes), LSRAMTypes, True)]));
WriteLn(Format(' Error Correction Type %s',[ErrorCorrectionTypeStr[LProcessorInfo.L1Chache.GetErrorCorrectionType]]));
WriteLn(Format(' System Cache Type %s',[SystemCacheTypeStr[LProcessorInfo.L1Chache.GetSystemCacheType]]));
WriteLn(Format(' Associativity %s',[LProcessorInfo.L1Chache.AssociativityStr]));
end;
if (LProcessorInfo.RAWProcessorInformation^.L2CacheHandle>0) and (LProcessorInfo.L2Chache<>nil) then
begin
WriteLn('L2 Cache Handle Info');
WriteLn('--------------------');
WriteLn(' Socket Designation '+LProcessorInfo.L2Chache.SocketDesignationStr);
WriteLn(Format(' Cache Configuration %.4x',[LProcessorInfo.L2Chache.RAWCacheInformation^.CacheConfiguration]));
WriteLn(Format(' Maximum Cache Size %d Kb',[LProcessorInfo.L2Chache.GetMaximumCacheSize]));
WriteLn(Format(' Installed Cache Size %d Kb',[LProcessorInfo.L2Chache.GetInstalledCacheSize]));
LSRAMTypes:=LProcessorInfo.L2Chache.GetSupportedSRAMType;
WriteLn(Format(' Supported SRAM Type %s',[SetToString(TypeInfo(TCacheSRAMTypes), LSRAMTypes, True)]));
LSRAMTypes:=LProcessorInfo.L2Chache.GetCurrentSRAMType;
WriteLn(Format(' Current SRAM Type %s',[SetToString(TypeInfo(TCacheSRAMTypes), LSRAMTypes, True)]));
WriteLn(Format(' Error Correction Type %s',[ErrorCorrectionTypeStr[LProcessorInfo.L2Chache.GetErrorCorrectionType]]));
WriteLn(Format(' System Cache Type %s',[SystemCacheTypeStr[LProcessorInfo.L2Chache.GetSystemCacheType]]));
WriteLn(Format(' Associativity %s',[LProcessorInfo.L2Chache.AssociativityStr]));
end;
if (LProcessorInfo.RAWProcessorInformation^.L3CacheHandle>0) and (LProcessorInfo.L3Chache<>nil) then
begin
WriteLn('L3 Cache Handle Info');
WriteLn('--------------------');
WriteLn(' Socket Designation '+LProcessorInfo.L3Chache.SocketDesignationStr);
WriteLn(Format(' Cache Configuration %.4x',[LProcessorInfo.L3Chache.RAWCacheInformation^.CacheConfiguration]));
WriteLn(Format(' Maximum Cache Size %d Kb',[LProcessorInfo.L3Chache.GetMaximumCacheSize]));
WriteLn(Format(' Installed Cache Size %d Kb',[LProcessorInfo.L3Chache.GetInstalledCacheSize]));
LSRAMTypes:=LProcessorInfo.L3Chache.GetSupportedSRAMType;
WriteLn(Format(' Supported SRAM Type %s',[SetToString(TypeInfo(TCacheSRAMTypes), LSRAMTypes, True)]));
LSRAMTypes:=LProcessorInfo.L3Chache.GetCurrentSRAMType;
WriteLn(Format(' Current SRAM Type %s',[SetToString(TypeInfo(TCacheSRAMTypes), LSRAMTypes, True)]));
WriteLn(Format(' Error Correction Type %s',[ErrorCorrectionTypeStr[LProcessorInfo.L3Chache.GetErrorCorrectionType]]));
WriteLn(Format(' System Cache Type %s',[SystemCacheTypeStr[LProcessorInfo.L3Chache.GetSystemCacheType]]));
WriteLn(Format(' Associativity %s',[LProcessorInfo.L3Chache.AssociativityStr]));
end;
Readln;
end
else
Writeln('No Processor Info was found');
finally
SMBios.Free;
end;
end;
begin
try
GetPtrocessorInfo;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
|
// Ported CrystalDiskInfo (The MIT License, http://crystalmark.info)
unit SMARTSupport.Toshiba;
interface
uses
BufferInterpreter, Device.SMART.List, SMARTSupport, Support;
type
TToshibaSMARTSupport = class(TSMARTSupport)
public
function IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean; override;
function GetTypeName: String; override;
function IsSSD: Boolean; override;
function IsInsufficientSMART: Boolean; override;
function GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted; override;
function IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean; override;
end;
implementation
{ TToshibaSMARTSupport }
function TToshibaSMARTSupport.GetTypeName: String;
begin
result := 'SmartToshiba';
end;
function TToshibaSMARTSupport.IsInsufficientSMART: Boolean;
begin
result := false;
end;
function TToshibaSMARTSupport.IsSSD: Boolean;
begin
result := true;
end;
function TToshibaSMARTSupport.IsThisStorageMine(
const IdentifyDevice: TIdentifyDeviceResult;
const SMARTList: TSMARTValueList): Boolean;
begin
result :=
FindAtFirst('TOSHIBA', IdentifyDevice.Model) and
CheckIsSSDInCommonWay(IdentifyDevice);
end;
function TToshibaSMARTSupport.IsWriteValueSupported(
const SMARTList: TSMARTValueList): Boolean;
begin
result := false;
end;
function TToshibaSMARTSupport.GetSMARTInterpreted(
const SMARTList: TSMARTValueList): TSMARTInterpreted;
const
ReadError = true;
EraseError = false;
UsedHourID = $09;
ThisErrorType = ReadError;
ErrorID = $01;
ReplacedSectorsID = $05;
begin
FillChar(result, SizeOf(result), 0);
result.UsedHour := SMARTList.ExceptionFreeGetRAWByID(UsedHourID);
result.ReadEraseError.TrueReadErrorFalseEraseError := ReadError;
result.ReadEraseError.Value := SMARTList.ExceptionFreeGetRAWByID(ErrorID);
result.ReplacedSectors :=
SMARTList.ExceptionFreeGetRAWByID(ReplacedSectorsID);
end;
end.
|
unit Util;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ChildFrm, ComCtrls, StdCtrls, ExtCtrls, ImgList;
function GetStdDirectory(Dir: string): string;
procedure SetStdDirectory(var Dir: string);
procedure FindFiles(APath, AFileName: string; LV: TListView);
function AddAListItem({intImgIndex: integer;}
Values: array of string; SubImgIndexs: array of integer;
{intStaIndex: integer; }LV: TListView; Data: Pointer = nil;
InsertIndex: integer = -1): TListItem;
implementation
function GetStdDirectory(Dir: string): string;
begin
if Dir[Length(Dir)] <> '\' then
Result := Dir + '\'
else
Result := Dir;
end;
procedure SetStdDirectory(var Dir: string);
begin
if Dir[Length(Dir)] <> '\' then
Dir := Dir + '\'
end;
procedure FindFiles(APath, AFileName: string; LV: TListView);
var
FSearchRec, DsearchRec: TSearchRec;
FindResult: Integer;
i: Integer;
ch: Char;
wn: WideString;
wh: WideChar;
function IsDirNotation(ADirName: string): Boolean;
begin
Result := (ADirName = '.') or (ADirName = '..');
end;
begin
APath := GetStdDirectory(APath);
FindResult := FindFirst(APath + AFileName, faAnyFile + faHidden + faSysFile +
faReadOnly, FSearchRec);
try
while FindResult = 0 do
begin
//lvDetail.Columns[0].Caption := LowerCase(APath + FSearchRec.Name);
AddAListItem([LowerCase(APath + FSearchRec.Name)],[],LV);
{ wn := widestring(FSearchRec.Name);
showmessage(inttostr(Length(FSearchRec.Name))+#13#10+inttostr(length(wn)));
for i:=1 to Length(FSearchRec.Name) do
begin
ch := FSearchRec.Name[i];
wh := WideChar(wn[i]);
showmessage(FSearchRec.Name[i]+#13#10+inttostr(ord(FSearchRec.Name[i]))
+#13#10+ch+#13#10+wh);
end;}
FindResult := FindNext(FSearchRec);
end;
FindResult := FindFirst(APath + '*.*', faDirectory, DSearchRec);
while FindResult = 0 do
begin
if ((DSearchRec.Attr and faDirectory) = faDirectory) and not
IsDirNotation(DsearchRec.Name) then
FindFiles(APath + DSearchRec.Name, '*.*', LV);
FindResult := FindNext(DsearchRec);
end;
finally
FindClose(FSearchRec);
end;
end;
function AddAListItem({intImgIndex: integer;}
Values: array of string; SubImgIndexs: array of integer;
{intStaIndex: integer; }LV: TListView; Data: Pointer = nil;
InsertIndex: integer = -1): TListItem;
var
i: integer;
bHasSubImg: Boolean;
begin
if High(SubImgIndexs) = -1 then
bHasSubImg := False
else
bHasSubImg := True;
if InsertIndex = -1 then
result := TListItem(LV.items.Add)
else
result := TListItem(LV.items.Insert(InsertIndex));
with result do
begin
Caption := Values[Low(Values)];
//ImageIndex := intImgIndex;
//StateIndex := intStaIndex;
for i := Low(Values) + 1 to High(Values) do
begin
SubItems.Add(Values[i]);
if bHasSubImg then
SubItemImages[i - 1] := SubImgIndexs[i - 1];
end;
end;
Result.Data := Data;
end;
end.
|
unit Loan;
interface
uses
SysUtils, Entity, LoanClient, AppConstants, DB, System.Rtti, ADODB, Variants,
LoanClassification, Comaker, FinInfo, MonthlyExpense, ReleaseRecipient,
LoanCharge, LoanClassCharge, Assessment, Math, Ledger;
type
TLoanAction = (laNone,laCreating,laAssessing,laApproving,laRejecting,laReleasing,laCancelling,laClosing);
TLoanState = (lsNone,lsAssessed,lsApproved,lsActive,lsCancelled,lsRejected,lsClosed);
TLoanStatus = (A,C,P,R,F,J,S,X);
TAdvancePayment = class
strict private
FPrincipal: currency;
FInterest: currency;
FBalance: currency;
public
property Principal: currency read FPrincipal write FPrincipal;
property Interest: currency read FInterest write FInterest;
property Balance: currency read FBalance write FBalance;
end;
{ ****** Loan Status *****
-- 0 = all
-- 1 = pending = P
-- 2 = assessed = S
-- 3 = approved = A
-- 4 = active / released = R
-- 5 = cancelled = C
-- 6 = denied / rejected = J
-- 7 = closed = X
***** Loan Status ***** }
TLoan = class(TEntity)
private
FClient: TLoanClient;
FStatus: string;
FAction: TLoanAction;
FLoanClass: TLoanClassification;
FComakers: array of TComaker;
FFinancialInfo: array of TFinInfo;
FMonthlyExpenses: array of TMonthlyExpense;
FAppliedAmout: currency;
FLoanStatusHistory: array of TLoanState;
FReleaseRecipients: array of TReleaseRecipient;
FLoanCharges: array of TLoanCharge;
FApprovedAmount: currency;
FDesiredTerm: integer;
FAssessment: TAssessment;
FReleaseAmount: currency;
FApprovedTerm: integer;
FBalance: currency;
FAdvancePayments: array of TAdvancePayment;
FPromissoryNote: string;
FIsBacklog: boolean;
FDateApplied: TDateTime;
FLastTransactionDate: TDateTime;
FAmortisation: currency;
FInterestDeficit: currency;
FLastInterestPostDate: TDateTime;
procedure SaveComakers;
procedure SaveAssessments;
procedure SaveApproval;
procedure SaveCancellation;
procedure SaveRejection;
procedure SaveRelease;
procedure SaveClosure;
procedure SetAdvancePayment(const i: integer; const Value: TAdvancePayment);
procedure UpdateLoan;
procedure SaveBacklog;
function GetIsPending: boolean;
function GetIsAssessed: boolean;
function GetIsApproved: boolean;
function GetIsActive: boolean;
function GetIsCancelled: boolean;
function GetIsRejected: boolean;
function GetIsClosed: boolean;
function GetComakerCount: integer;
function GetNew: boolean;
function GetStatusName: string;
function GetComaker(const i: integer): TComaker;
function GetFinancialInfo(const i: integer): TFinInfo;
function GetFinancialInfoCount: integer;
function GetMonthlyExpense(const i: integer): TMonthlyExpense;
function GetMonthlyExpenseCount: integer;
function GetLoanState(const i: integer): TLoanState;
function GetLoanStateCount: integer;
function GetReleaseRecipient(const i: integer): TReleaseRecipient;
function GetReleaseRecipientCount: integer;
function GetLoanCharge(const i: integer): TLoanCharge;
function GetLoanChargeCount: integer;
function GetIsFinalised: boolean;
function GetTotalCharges: currency;
function GetTotalReleased: currency;
function GetNetProceeds: currency;
function GetFactorWithInterest: currency;
function GetFactorWithoutInterest: currency;
function GetAmortisation: currency;
function GetTotalAdvancePayment: currency;
function GetAdvancePayment(const i: integer): TAdvancePayment;
function GetAdvancePaymentCount: integer;
function GetDaysFromLastTransaction: integer;
function GetInterestDueAsOfDate: currency;
function GetTotalInterestDue: currency;
function GetLastTransactionDate: TDateTime;
function GetNextPayment: TDateTime;
public
procedure Add; override;
procedure Save; override;
procedure Edit; override;
procedure Cancel; override;
procedure Retrieve(const closeDataSources: boolean = false);
procedure SetDefaultValues;
procedure AddComaker(cmk: TComaker; const append: boolean = false);
procedure RemoveComaker(cmk: TComaker);
procedure AppendFinancialInfo;
procedure AddFinancialInfo(const financialInfo: TFinInfo; const overwrite: boolean = false);
procedure RemoveFinancialInfo(const compId: string);
procedure AppendMonthlyExpense;
procedure AddMonthlyExpense(const monthExp: TMonthlyExpense; const overwrite: boolean = false);
procedure RemoveMonthlyExpense(const expType: string);
procedure ClearFinancialInfo;
procedure ClearMonthlyExpenses;
procedure AddLoanState(const loanState: TLoanState);
procedure GetAlerts;
procedure AddReleaseRecipient(const rec: TReleaseRecipient; const overwrite: boolean = false);
procedure AppendReleaseRecipient(const rec: TReleaseRecipient = nil);
procedure ClearReleaseRecipients;
procedure AddLoanCharge(const charge: TLoanCharge; const append: boolean = false);
procedure ClearLoanCharges;
procedure ComputeCharges;
procedure RemoveReleaseRecipient(const rec: TReleaseRecipient);
procedure ChangeLoanStatus;
procedure ClearComakers;
procedure AddAdvancePayment(const adv: TAdvancePayment);
procedure ClearAdvancePayments;
function ComakerExists(cmk: TComaker): boolean;
function FinancialInfoExists(const compId: string): boolean;
function MonthlyExpenseExists(const expType: string): boolean;
function ReleaseRecipientExists(const recipient, location, method: string): boolean;
function LoanChargeExists(const charge: TLoanCharge): boolean;
function LoanStateExists(const state: TLoanState): boolean;
function HasLoanState(const ls: TLoanState): boolean;
property Client: TLoanClient read FClient write FClient;
property Status: string read FStatus write FStatus;
property StatusName: string read GetStatusName;
property Action: TLoanAction read FAction write FAction;
property LoanClass: TLoanClassification read FLoanClass write FLoanClass;
property IsPending: boolean read GetIsPending;
property IsAssessed: boolean read GetIsAssessed;
property IsApproved: boolean read GetIsApproved;
property IsActive: boolean read GetIsActive;
property IsCancelled: boolean read GetIsCancelled;
property IsRejected: boolean read GetIsRejected;
property IsClosed: boolean read GetIsClosed;
property ComakerCount: integer read GetComakerCount;
property New: boolean read GetNew;
property Comaker[const i: integer]: TComaker read GetComaker;
property AppliedAmount: currency read FAppliedAmout write FAppliedAmout;
property FinancialInfoCount: integer read GetFinancialInfoCount;
property FinancialInfo[const i: integer]: TFinInfo read GetFinancialInfo;
property MonthlyExpenseCount: integer read GetMonthlyExpenseCount;
property MonthlyExpense[const i: integer]: TMonthlyExpense read GetMonthlyExpense;
property LoanStatusHistory[const i: integer]: TLoanState read GetLoanState;
property LoanSatusCount: integer read GetLoanStateCount;
property ReleaseRecipients[const i: integer]: TReleaseRecipient read GetReleaseRecipient;
property ReleaseRecipientCount: integer read GetReleaseRecipientCount;
property LoanCharges[const i: integer]: TLoanCharge read GetLoanCharge;
property LoanChargeCount: integer read GetLoanChargeCount;
property ApprovedAmount: currency read FApprovedAmount write FApprovedAmount;
property DesiredTerm: integer read FDesiredTerm write FDesiredTerm;
property IsFinalised: boolean read GetIsFinalised;
property TotalCharges: currency read GetTotalCharges;
property TotalReleased: currency read GetTotalReleased;
property Assessment: TAssessment read FAssessment write FAssessment;
property ReleaseAmount: currency read FReleaseAmount write FReleaseAmount;
property ApprovedTerm: integer read FApprovedTerm write FApprovedTerm;
property NetProceeds: currency read GetNetProceeds;
property FactorWithInterest: currency read GetFactorWithInterest;
property FactorWithoutInterest: currency read GetFactorWithoutInterest;
property Amortisation: currency read GetAmortisation;
property Balance: currency read FBalance write FBalance;
property TotalAdvancePayment: currency read GetTotalAdvancePayment;
property AdvancePayment[const i: integer]: TAdvancePayment read GetAdvancePayment write SetAdvancePayment;
property AdvancePaymentCount: integer read GetAdvancePaymentCount;
property PromissoryNote: string read FPromissoryNote write FPromissoryNote;
property IsBacklog: boolean read FIsBacklog write FIsBacklog;
property DateApplied: TDateTime read FDateApplied write FDateApplied;
property LastTransactionDate: TDateTime read FLastTransactionDate write FLastTransactionDate;
property DaysFromLastTransaction: integer read GetDaysFromLastTransaction;
property InterestDueAsOfDate: currency read GetInterestDueAsOfDate;
property TotalInterestDue: currency read GetTotalInterestDue;
property InterestDeficit: currency read FInterestDeficit write FInterestDeficit;
property LastInterestPostDate: TDateTime read FLastInterestPostDate write FLastInterestPostDate;
property NextPaymentDate: TDateTime read GetNextPayment;
constructor Create;
destructor Destroy; reintroduce;
end;
var
ln: TLoan;
implementation
uses
LoanData, IFinanceGlobal, Posting, IFinanceDialogs, DateUtils;
constructor TLoan.Create;
begin
if ln <> nil then
Abort
else
begin
ln := self;
FAction := laCreating;
end;
end;
destructor TLoan.Destroy;
begin
if ln = self then
ln := nil;
end;
procedure TLoan.Add;
begin
with dmLoan.dstLoan do
begin
Open;
Append;
end;
with dmLoan.dstLoanComaker do
Open;
end;
procedure TLoan.Save;
begin
with dmLoan.dstLoan do
if State in [dsInsert,dsEdit] then
Post;
if (ln.Action = laCreating) or (ln.IsPending) then
SaveComakers;
if ln.IsBacklog then
SaveBacklog
else if ln.Action = laAssessing then
SaveAssessments
else if ln.Action = laApproving then
SaveApproval
else if ln.Action = laCancelling then
SaveCancellation
else if ln.Action = laRejecting then
SaveRejection
else if ln.Action = laClosing then
SaveClosure
else if ln.Action = laReleasing then
begin
SaveRelease;
// if FLoanClass.HasAdvancePayment then UpdateLoan;
UpdateLoan;
end;
ln.Action := laNone;
end;
procedure TLoan.Edit;
begin
end;
procedure TLoan.Cancel;
begin
with dmLoan, dmLoan.dstLoan do
begin
if (ln.Action = laCreating) or (ln.IsPending) then
begin
if State in [dsInsert,dsEdit] then
Cancel;
dstLoanComaker.CancelBatch;
// close loan class
if ln.Action = laCreating then dstLoanClass.Close;
end;
if ln.Action = laAssessing then
begin
dstLoanAss.Cancel;
dstFinInfo.Close;
dstFinInfo.Open;
dstMonExp.Close;
dstMonExp.Open;
end
else if ln.Action = laApproving then
begin
if dstLoanAppv.State in [dsInsert,dsEdit] then
dstLoanAppv.Cancel;
end
else if ln.Action = laCancelling then
begin
if dstLoanCancel.State in [dsInsert,dsEdit] then
dstLoanCancel.Cancel;
end
else if ln.Action = laRejecting then
begin
if dstLoanReject.State in [dsInsert,dsEdit] then
dstLoanReject.Cancel;
end
else if ln.Action = laReleasing then
begin
if dstLoanRelease.State in [dsInsert,dsEdit] then
dstLoanRelease.Cancel;
dstLoanRelease.CancelBatch;
dstLoanCharge.CancelBatch;
end;
end;
ln.Action := laNone;
end;
procedure TLoan.Retrieve(const closeDataSources: boolean = false);
var
i: integer;
tags: set of 1..6;
begin
// clear loan state history
if closeDataSources then SetLength(FLoanStatusHistory,0);
// set tags according to loan status and action
if ln.IsPending then tags := [1]
else if ln.IsAssessed then tags := [1,2]
else if ln.IsApproved then tags := [1,2,3]
else if ln.IsActive then tags := [1,2,3,4]
else if ln.IsCancelled then tags := [1,2,3,5]
else if ln.IsRejected then tags := [1,2,3,6]
else if ln.IsClosed then tags := [1,2,3,7];
// add tags depending on action
if ln.Action = laAssessing then tags := tags + [2]
else if ln.Action = laApproving then tags := tags + [3]
else if ln.Action = laReleasing then tags := tags + [4]
else if ln.Action = laCancelling then tags := tags + [5]
else if ln.Action = laRejecting then tags := tags + [6]
else if ln.Action = laClosing then tags := tags + [7];
with dmLoan do
begin
for i:=0 to ComponentCount - 1 do
begin
if Components[i] is TADODataSet then
if (Components[i] as TADODataSet).Tag in tags then
begin
if closeDataSources then
(Components[i] as TADODataSet).Close;
(Components[i] as TADODataSet).DisableControls;
(Components[i] as TADODataSet).Open;
(Components[i] as TADODataSet).EnableControls;
end;
end;
end;
end;
procedure TLoan.SetAdvancePayment(const i: integer;
const Value: TAdvancePayment);
begin
FAdvancePayments[i] := Value;
end;
procedure TLoan.SetDefaultValues;
begin
with dmLoan do
begin
if ln.Action = laAssessing then
begin
if dstLoanAss.RecordCount = 0 then
begin
dstLoanAss.Append;
dstLoanAss.FieldByName('date_ass').AsDateTime := ifn.AppDate;
dstLoanAss.FieldByName('ass_by').AsString := ifn.User.UserId;
end;
end
else if ln.Action = laApproving then
begin
if dstLoanAppv.RecordCount = 0 then
begin
dstLoanAppv.Append;
dstLoanAppv.FieldByName('date_appv').AsDateTime := ifn.AppDate;
dstLoanAppv.FieldByName('appv_by').AsString := ifn.User.UserId;
end;
end
else if ln.Action = laCancelling then
begin
if dstLoanCancel.RecordCount = 0 then
begin
dstLoanCancel.Append;
dstLoanCancel.FieldByName('cancelled_date').AsDateTime := ifn.AppDate;
dstLoanCancel.FieldByName('cancelled_by').AsString := ifn.User.UserId;
end;
end
else if ln.Action = laRejecting then
begin
if dstLoanReject.RecordCount = 0 then
begin
dstLoanReject.Append;
dstLoanReject.FieldByName('date_rejected').AsDateTime := ifn.AppDate;
dstLoanReject.FieldByName('rejected_by').AsString := ifn.User.UserId;
end;
end
else if ln.Action = laClosing then
begin
if dstLoanClose.RecordCount = 0 then
begin
dstLoanClose.Append;
dstLoanClose.FieldByName('date_closed').AsDateTime := ifn.AppDate;
dstLoanClose.FieldByName('closed_by').AsString := ifn.User.UserId;
end;
end
end;
end;
procedure TLoan.UpdateLoan;
var
adv: TAdvancePayment;
balance, intDeficit, prcDeficit: currency;
begin
// update the principal balance (field loan_balance)
// update the last transaction date
// update the loan status for full payment
try
with dmLoan.dstLoan do
begin
intDeficit := 0;
prcDeficit := 0;
for adv in FAdvancePayments do
begin
intDeficit := intDeficit - adv.Interest;
prcDeficit := prcDeficit - adv.Principal;
end;
balance := FReleaseAmount - TotalAdvancePayment;
Edit;
FieldByName('balance').AsCurrency := balance;
FieldByName('prc_deficit').AsCurrency := prcDeficit;
FieldByName('int_deficit').AsCurrency := intDeficit;
FieldByName('amort').AsCurrency := Amortisation;
FieldByName('last_trans_date').AsDateTime := GetLastTransactionDate;
Post;
Requery;
end;
except
end;
end;
procedure TLoan.AddAdvancePayment(const adv: TAdvancePayment);
begin
SetLength(FAdvancePayments,Length(FAdvancePayments) + 1);
FAdvancePayments[Length(FAdvancePayments) - 1] := adv;
end;
procedure TLoan.AddComaker(cmk: TComaker; const append: boolean);
begin
if not ComakerExists(cmk) then
begin
SetLength(FComakers,Length(FComakers) + 1);
FComakers[Length(FComakers) - 1] := cmk;
// add in db
if (append) and (ln.IsPending) then
with dmLoan.dstLoanComaker do
begin
Append;
FieldByName('entity_id').AsString := cmk.Id;
Post;
end;
end;
end;
procedure TLoan.RemoveComaker(cmk: TComaker);
var
i, ii, len: integer;
co: TComaker;
begin
len := Length(FComakers);
ii := 0;
for i := 0 to len - 1 do
begin
co := FComakers[i];
if co.Id <> cmk.Id then
begin
FComakers[ii] := co;
Inc(ii);
end;
end;
SetLength(FComakers,Length(FComakers) - 1);
// delete from db
with dmLoan.dstLoanComaker do
begin
if RecordCount > 0 then
begin
Locate('entity_id',cmk.Id,[]);
Delete;
end;
end;
end;
procedure TLoan.AppendFinancialInfo;
begin
with dmLoan.dstFinInfo do
Append;
end;
procedure TLoan.AppendMonthlyExpense;
begin
with dmLoan.dstMonExp do
Append;
end;
procedure TLoan.AddFinancialInfo(const financialInfo: TFinInfo; const overwrite: boolean = false);
var
index: integer;
begin
if not FinancialInfoExists(financialInfo.CompanyId) then
begin
SetLength(FFinancialInfo,Length(FFinancialInfo) + 1);
FFinancialInfo[Length(FFinancialInfo) - 1] := financialInfo;
end
else if overwrite then
begin
with dmLoan.dstFinInfo do
index := RecNo;
FFinancialInfo[index - 1] := financialInfo;
end;
end;
procedure TLoan.RemoveFinancialInfo(const compId: string);
var
i, len, ii: integer;
fin: TFinInfo;
begin
len := Length(FFinancialInfo);
ii := -1;
for i := 0 to len - 1 do
begin
fin := FFinancialInfo[i];
if fin.CompanyId = compId then ii := i + 1
else Inc(ii);
FFinancialInfo[i] := FFinancialInfo[ii];
end;
SetLength(FFinancialInfo,Length(FFinancialInfo) - 1);
// remove from db
with dmLoan.dstFinInfo do
Delete;
end;
procedure TLoan.AddMonthlyExpense(const monthExp: TMonthlyExpense; const overwrite: boolean = false);
var
index: integer;
begin
if not MonthlyExpenseExists(monthExp.ExpenseType) then
begin
SetLength(FMonthlyExpenses,Length(FMonthlyExpenses) + 1);
FMonthlyExpenses[Length(FMonthlyExpenses) - 1] := monthExp;
end
else if overwrite then
begin
with dmLoan.dstMonExp do
index := RecNo;
FMonthlyExpenses[index - 1] := monthExp;
end;
end;
procedure TLoan.RemoveMonthlyExpense(const expType: string);
var
i, len, ii: integer;
exp: TMonthlyExpense;
begin
len := Length(FMonthlyExpenses);
ii := -1;
for i := 0 to len - 1 do
begin
exp := FMonthlyExpenses[i];
if exp.ExpenseType = expType then ii := i + 1
else Inc(ii);
FMonthlyExpenses[i] := FMonthlyExpenses[ii];
end;
SetLength(FMonthlyExpenses,Length(FMonthlyExpenses) - 1);
// remove from db
with dmLoan.dstMonExp do
Delete;
end;
procedure TLoan.SaveComakers;
var
i, cnt: integer;
begin
with dmLoan.dstLoanComaker do
begin
cnt := ln.ComakerCount - 1;
if ln.Action = laCreating then
begin
for i := 0 to cnt do
begin
Append;
FieldByName('entity_id').AsString := ln.Comaker[i].Id;
Post;
end;
end;
UpdateBatch;
end;
end;
procedure TLoan.SaveAssessments;
begin
with dmLoan do
begin
if dstLoanAss.State in [dsInsert,dsEdit] then
dstLoanAss.Post;
dstFinInfo.UpdateBatch;
dstMonExp.UpdateBatch;
// requery to refresh dataset
dstLoanAss.Requery;
dstFinInfo.Requery;
dstMonExp.Requery;
end;
end;
procedure TLoan.SaveBacklog;
begin
try
with dmLoan.dstLoan do FAmortisation := FieldByName('amort').AsCurrency;
// create assessment
with dmLoan.dstLoanAss do
begin
Open;
Append;
FieldByName('rec_code').AsInteger := 0;
FieldByName('rec_amt').AsCurrency := ln.AppliedAmount;
FieldByName('date_ass').AsDateTime := ln.DateApplied;
Post;
end;
// create approval
with dmLoan.dstLoanAppv do
begin
Open;
Append;
FieldByName('amt_appv').AsCurrency := ln.AppliedAmount;
FieldByName('date_appv').AsDateTime := ln.DateApplied;
FieldByName('terms').AsInteger := ln.DesiredTerm;
FieldByName('appv_method').AsString := 'S';
Post;
end;
// create relesase
with dmLoan.dstLoanRelease do
begin
Open;
Append;
FieldByName('recipient').AsString := ln.Client.Id;
FieldByName('rel_method').AsString := 'C';
FieldByName('rel_amt').AsCurrency := ln.AppliedAmount;
FieldByName('date_rel').AsDateTime := ln.DateApplied;
FieldByName('loc_code').AsString := ifn.LocationCode;
SaveRelease;
end;
except
on E: exception do ShowErrorBox(E.Message);
end;
end;
procedure TLoan.SaveApproval;
begin
with dmLoan.dstLoanAppv do
if State in [dsInsert,dsEdit] then
begin
Post;
Requery;
end;
end;
procedure TLoan.SaveCancellation;
begin
with dmLoan.dstLoanCancel do
if State in [dsInsert,dsEdit] then
begin
Post;
Requery;
end;
end;
procedure TLoan.SaveClosure;
begin
with dmLoan.dstLoanClose do
if State in [dsInsert,dsEdit] then
begin
Post;
Requery;
end;
end;
procedure TLoan.SaveRejection;
begin
with dmLoan.dstLoanReject do
if State in [dsInsert,dsEdit] then
begin
Post;
Requery;
end;
end;
procedure TLoan.SaveRelease;
var
LPosting: TPosting;
begin
with dmLoan do
begin
dstLoanRelease.UpdateBatch;
if not ln.IsBacklog then
begin
dstLoanCharge.UpdateBatch;
dstLoanCharge.Requery;
end;
dstLoanRelease.Requery;
if not ln.HasLoanState(lsActive) then
begin
ln.ChangeLoanStatus;
ln.AddLoanState(lsActive);
LPosting := TPosting.Create;
try
LPosting.Post(self);
finally
LPosting.Free;
end;
end
end;
end;
procedure TLoan.ChangeLoanStatus;
begin
with dmLoan.dstLoan do
begin
Edit;
if ln.IsBacklog then FieldByName('status_id').AsString :=
TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.R)
else if ln.Action = laAssessing then
FieldByName('status_id').AsString :=
TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.S)
else if ln.Action = laApproving then
FieldByName('status_id').AsString :=
TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.A)
else if ln.Action = laReleasing then
begin
FieldByName('balance').AsCurrency := FReleaseAmount;
FieldByName('pn_no').AsString := FPromissoryNote;
FieldByName('status_id').AsString :=
TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.R)
end
else if ln.Action = laCancelling then
FieldByName('status_id').AsString :=
TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.C)
else if ln.Action = laClosing then
FieldByName('status_id').AsString :=
TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.X)
else if ln.Action = laRejecting then
FieldByName('status_id').AsString :=
TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.J);
Post;
end;
end;
procedure TLoan.ClearFinancialInfo;
begin
SetLength(FFinancialInfo,0);
end;
procedure TLoan.ClearMonthlyExpenses;
begin
SetLength(FMonthlyExpenses,0);
end;
procedure TLoan.AddLoanState(const loanState: TLoanState);
begin
if not LoanStateExists(loanState) then
begin
SetLength(FLoanStatusHistory,Length(FLoanStatusHistory) + 1);
FLoanStatusHistory[Length(FLoanStatusHistory) - 1] := loanState;
end;
end;
function TLoan.GetTotalAdvancePayment: currency;
var
principal, interest, balance, total: currency;
i, cnt: integer;
adv: TAdvancePayment;
begin
Result := 0;
total := 0;
// if loan is BEING release.. compute the advance payment
if ln.Action = laReleasing then
begin
ClearAdvancePayments;
if FLoanClass.HasAdvancePayment then
begin
if FReleaseAmount <= 0 then
begin
Result := 0;
Exit;
end;
balance := FReleaseAmount;
cnt := FLoanClass.AdvancePayment.NumberOfMonths;
for i := 1 to cnt do
begin
adv := TAdvancePayment.Create;
// interest
if FLoanClass.IsDiminishing then interest := balance * FLoanClass.InterestInDecimal
else interest := FReleaseAmount * FLoanClass.InterestInDecimal;
// round off to 2 decimal places
interest := RoundTo(interest,-2);
if i <= FLoanClass.AdvancePayment.Interest then adv.Interest := interest;
total := total + adv.Interest;
// principal
if FLoanClass.AdvancePayment.IncludePrincipal then
begin
if FLoanClass.IsDiminishing then principal := Amortisation - interest
else principal := FReleaseAmount / FApprovedTerm;
if i <= FLoanClass.AdvancePayment.Principal then adv.Principal := principal;
total := total + adv.Principal;
// get balance
balance := balance - principal;
adv.Balance := balance;
end;
ln.AddAdvancePayment(adv);
end; // end for
Result := total;
end
else Result := 0;
end
else
begin
dmLoan.dstAdvancePayment.Open;
for adv in FAdvancePayments do total := total + adv.Interest + adv.Principal;
Result := total;
end;
end;
function TLoan.GetAdvancePayment(const i: integer): TAdvancePayment;
begin
Result := FAdvancePayments[i];
end;
function TLoan.GetAdvancePaymentCount: integer;
begin
Result := Length(FAdvancePayments);
end;
procedure TLoan.GetAlerts;
begin
with dmLoan.dstAlerts do
Open;
end;
function TLoan.GetAmortisation: currency;
var
amort: currency;
begin
if IsBacklog then Result := FAmortisation
else
begin
if FLoanClass.IsDiminishing then amort := FReleaseAmount * GetFactorWithInterest
else amort := ((FReleaseAmount * FLoanClass.InterestInDecimal * FApprovedTerm) + FReleaseAmount) / FApprovedTerm;
// Note: Round off the AMORTISATION to "nearest peso" .. ex. 1.25 to 2.00
if amort <> Trunc(amort) then Result := Trunc(amort) + 1
else Result := amort;
end;
end;
procedure TLoan.AddReleaseRecipient(const rec: TReleaseRecipient; const overwrite: boolean);
var
index: integer;
begin
if not ReleaseRecipientExists(rec.Recipient.Id,rec.LocationCode, rec.ReleaseMethod.Id) then
begin
SetLength(FReleaseRecipients,Length(FReleaseRecipients) + 1);
FReleaseRecipients[Length(FReleaseRecipients) - 1] := rec;
end
else if overwrite then
begin
// get the record no
// Note: DataSet.Locate has been called prior to opening the detail window
with dmLoan.dstLoanRelease do
index := RecNo;
FReleaseRecipients[index - 1] := rec;
end;
end;
procedure TLoan.AppendReleaseRecipient(const rec: TReleaseRecipient = nil);
begin
with dmLoan.dstLoanRelease, rec do
begin
Append;
if Assigned(rec) then
begin
FieldByName('recipient').AsString := Recipient.Id;
FieldByName('rel_method').AsString := ReleaseMethod.Id;
FieldByName('rel_amt').AsCurrency := Amount;
FieldByName('date_rel').AsDateTime := rec.Date;
Post;
end;
end;
end;
procedure TLoan.ClearReleaseRecipients;
begin
FReleaseRecipients := [];
end;
procedure TLoan.AddLoanCharge(const charge: TLoanCharge; const append: boolean);
var
lc: TLoanCharge;
begin
if not LoanChargeExists(charge) then
begin
SetLength(FLoanCharges,Length(FLoanCharges) + 1);
FLoanCharges[Length(FLoanCharges) - 1] := charge;
if append then
begin
with dmLoan.dstLoanCharge do
begin
Append;
FieldByName('loan_id').AsString := FId;
FieldByName('charge_type').AsString := charge.ChargeType;
FieldByName('charge_amt').AsCurrency := charge.Amount;
Post;
end;
end;
end
else
begin
// update if charge exists
for lc in FLoanCharges do
if lc.ChargeType = charge.ChargeType then
lc.Amount := charge.Amount;
if append then
begin
with dmLoan.dstLoanCharge do
begin
Locate('charge_type',charge.ChargeType,[]);
Edit;
FieldByName('charge_amt').AsCurrency := charge.Amount;
Post;
end;
end;
end;
end;
procedure TLoan.ClearLoanCharges;
begin
FLoanCharges := [];
end;
procedure TLoan.ComputeCharges;
var
i, cnt: integer;
charge: TLoanCharge;
classCharge: TLoanClassCharge;
begin
cnt := FLoanClass.ClassChargesCount - 1;
for i := 0 to cnt do
begin
classCharge := FLoanClass.ClassCharge[i];
charge := TLoanCharge.Create;
charge.ChargeType := classCharge.ChargeType;
charge.ChargeName := classCharge.ChargeName;
if FReleaseAmount > 0 then
begin
if classCharge.ValueType = vtFixed then
charge.Amount := classCharge.ChargeValue
else if classCharge.ValueType = vtPercentage then
charge.Amount := (classCharge.ChargeValue * FReleaseAmount) / 100
else if classCharge.ValueType = vtRatio then
begin
if classCharge.MaxValueType = mvtAmount then
begin
charge.Amount := classCharge.ChargeValue * (FReleaseAmount / classCharge.RatioAmount) * FApprovedTerm;
if charge.Amount > classCharge.MaxValue then
charge.Amount := classCharge.MaxValue;
end
else
begin
if classCharge.MaxValue > FApprovedTerm then
charge.Amount := classCharge.ChargeValue * (FReleaseAmount / classCharge.RatioAmount) * FApprovedTerm
else
charge.Amount := classCharge.ChargeValue * (FReleaseAmount / classCharge.RatioAmount) * classCharge.MaxValue
end;
end;
end
else charge.Amount := 0;
AddLoanCharge(charge,true);
end;
end;
procedure TLoan.RemoveReleaseRecipient(const rec: TReleaseRecipient);
var
i, len, ii: integer;
rcp: TReleaseRecipient;
begin
len := Length(FReleaseRecipients);
ii := 0;
for i := 0 to len - 1 do
begin
rcp := FReleaseRecipients[i];
if (rcp.Recipient.Id = rec.Recipient.Id) and (rcp.ReleaseMethod.Id = rec.ReleaseMethod.Id) then
Continue
else
begin
FReleaseRecipients[ii] := rcp;
Inc(ii);
end;
end;
SetLength(FReleaseRecipients,Length(FReleaseRecipients) - 1);
// remove from db
with dmLoan.dstLoanRelease do
Delete;
end;
procedure TLoan.ClearAdvancePayments;
var
adv: TAdvancePayment;
// i: integer;
begin
//for i := Low(FAdvancePayments) to High(FAdvancePayments) do
//begin
// adv := FAdvancePayments[i];
// if Assigned(adv) then FreeAndNil(adv);
//end;
SetLength(FAdvancePayments,0);
end;
procedure TLoan.ClearComakers;
begin
FComakers := [];
end;
function TLoan.HasLoanState(const ls: TLoanState): boolean;
var
i, len: integer;
begin
Result := false;
len := Length(FLoanStatusHistory);
for i := 0 to len - 1 do
begin
if FLoanStatusHistory[i] = ls then
begin
Result := true;
Exit;
end;
end;
end;
function TLoan.GetIsPending: boolean;
begin
Result := FStatus = TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.P);
end;
function TLoan.GetIsAssessed: boolean;
begin
Result := FStatus = TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.S);
end;
function TLoan.GetIsApproved: boolean;
begin
Result := FStatus = TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.A);
end;
function TLoan.GetIsActive: boolean;
begin
Result := FStatus = TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.R);
end;
function TLoan.GetIsCancelled: boolean;
begin
Result := FStatus = TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.C);
end;
function TLoan.GetIsClosed: boolean;
begin
Result := FStatus = TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.X);
end;
function TLoan.GetIsRejected: boolean;
begin
Result := FStatus = TRttiEnumerationType.GetName<TLoanStatus>(TLoanStatus.J);
end;
function TLoan.GetComakerCount: integer;
begin
Result := Length(FComakers);
end;
function TLoan.GetDaysFromLastTransaction: integer;
begin
Result := DaysBetween(ifn.AppDate,FLastTransactionDate);
end;
function TLoan.GetInterestDueAsOfDate: currency;
var
days: integer;
LInterest: currency;
mm, dd, yy, fm, fd, fy: word;
begin
Result := 0;
if FLoanClass.IsDiminishing then
begin
days := GetDaysFromLastTransaction;
if days > 0 then
begin
if ifn.AppDate = FLastInterestPostDate then
begin
LInterest := FBalance * FLoanClass.InterestInDecimal;
Result := RoundTo(LInterest,-2);
end
else if ifn.AppDate > FLastInterestPostDate then
begin
DecodeDate(FLastInterestPostDate,fy,fm,fd);
DecodeDate(ifn.AppDate,yy,mm,dd);
if (fd <> dd) and (FLastInterestPostDate > 0) then
days := DaysBetween(ifn.AppDate,FLastInterestPostDate);
LInterest := (FBalance * FLoanClass.InterestInDecimal) / ifn.DaysInAMonth;
LInterest := RoundTo(LInterest,-2) * days;
end;
Result := LInterest;
end;
end;
end;
function TLoan.GetFinancialInfoCount: integer;
begin
Result := Length(FFinancialInfo);
end;
function TLoan.GetMonthlyExpenseCount: integer;
begin
Result := Length(FMonthlyExpenses);
end;
function TLoan.ComakerExists(cmk: TComaker): boolean;
var
i, len: integer;
co: TComaker;
begin
Result := false;
len := Length(FComakers);
for i := 0 to len - 1 do
begin
co := FComakers[i];
if co.Id = cmk.Id then
begin
Result := true;
Exit;
end;
end;
end;
function TLoan.GetNetProceeds: currency;
begin
Result := FReleaseAmount - GetTotalCharges - GetTotalAdvancePayment;
end;
function TLoan.GetNew: boolean;
begin
Result := FId = '';
end;
function TLoan.GetNextPayment: TDateTime;
var
LNextPayment: TDateTime;
mm, dd, yy, fm, fd, fy: word;
begin
// if (IsFirstPayment) and (HasAdvancePayment) then
// LNextPayment := IncMonth(FLastTransactionDate,FPaymentsAdvance)
// else
begin
LNextPayment := IncMonth(FLastTransactionDate);
DecodeDate(FLastTransactionDate,fy,fm,fd);
DecodeDate(LNextPayment,yy,mm,dd);
if fd <> dd then
if DaysBetween(LNextPayment,FLastTransactionDate) < ifn.DaysInAMonth then
LNextPayment := IncDay(LNextPayment); // IncDay(FLastTransactionDate,ifn.DaysInAMonth);
// if day falls on a 31 and succeeding date is not 31.. add 1 day
// else if dd < fd then LNextPayment := IncDay(LNextPayment);
end;
Result := LNextPayment;
end;
function TLoan.GetStatusName: string;
begin
if IsPending then Result := 'Pending'
else if IsAssessed then Result := 'Assessed'
else if IsApproved then Result := 'Approved'
else if IsActive then Result := 'Active'
else if IsCancelled then Result := 'Cancelled'
else if IsRejected then Result := 'Rejected'
else if IsClosed then Result := 'Closed';
end;
function TLoan.FinancialInfoExists(const compId: string): boolean;
var
i, len: integer;
fin: TFinInfo;
begin
Result := false;
len := Length(FFinancialInfo);
for i := 0 to len - 1 do
begin
fin := FFinancialInfo[i];
if fin.CompanyId = compId then
begin
Result := true;
Exit;
end;
end;
end;
function TLoan.MonthlyExpenseExists(const expType: string): boolean;
var
i, len: integer;
exp: TMonthlyExpense;
begin
Result := false;
len := Length(FMonthlyExpenses);
for i := 0 to len - 1 do
begin
exp := FMonthlyExpenses[i];
if exp.ExpenseType = expType then
begin
Result := true;
Exit;
end;
end;
end;
function TLoan.GetComaker(const i: Integer): TComaker;
begin
Result := FComakers[i];
end;
function TLoan.GetFactorWithInterest: currency;
var
divisor: currency;
begin
divisor := 1 - (1 / Power(1 + FLoanClass.InterestInDecimal, FApprovedTerm));
Result := FLoanClass.InterestInDecimal / divisor;
end;
function TLoan.GetFactorWithoutInterest: currency;
begin
if FLoanClass.IsDiminishing then Result := GetFactorWithInterest - FLoanClass.InterestInDecimal
else Result := 1;
end;
function TLoan.GetFinancialInfo(const i: integer): TFinInfo;
begin
Result := FFinancialInfo[i];
end;
function TLoan.GetMonthlyExpense(const i: Integer): TMonthlyExpense;
begin
Result := FMonthlyExpenses[i];
end;
function TLoan.GetLoanState(const i: integer): TLoanState;
begin
Result := FLoanStatusHistory[i];
end;
function TLoan.GetLoanStateCount;
begin
Result := Length(FLoanStatusHistory);
end;
function TLoan.ReleaseRecipientExists(const recipient, location, method: string): boolean;
var
i, len: integer;
rcp: TReleaseRecipient;
begin
Result := false;
len := Length(FReleaseRecipients);
for i := 0 to len - 1 do
begin
rcp := FReleaseRecipients[i];
if (rcp.Recipient.Id = recipient) and
(Trim(rcp.LocationCode) = Trim(location)) and
(rcp.ReleaseMethod.Id = method) then
begin
Result := true;
Exit;
end;
end;
end;
function TLoan.GetReleaseRecipientCount;
begin
Result := Length(FReleaseRecipients);
end;
function TLoan.GetReleaseRecipient(const i: integer): TReleaseRecipient;
begin
Result := FReleaseRecipients[i];
end;
function TLoan.GetLastTransactionDate: TDateTime;
var
LRecipient: TReleaseRecipient;
i, cnt: integer;
begin
cnt := Length(FReleaseRecipients) - 1;
for i := 0 to cnt do
begin
LRecipient := FReleaseRecipients[0];
if i = 0 then Result := LRecipient.Date
else if LRecipient.Date < Result then
Result := LRecipient.Date;
end;
end;
function TLoan.GetLoanCharge(const i: Integer): TLoanCharge;
begin
Result := FLoanCharges[i];
end;
function TLoan.GetLoanChargeCount;
begin
Result := Length(FLoanCharges);
end;
function TLoan.LoanChargeExists(const charge: TLoanCharge): boolean;
var
i, len: integer;
ch: TLoanCharge;
begin
Result := false;
len := Length(FLoanCharges);
for i := 0 to len - 1 do
begin
ch := FLoanCharges[i];
if ch.ChargeType = charge.ChargeType then
begin
Result := true;
Exit;
end;
end;
end;
function TLoan.LoanStateExists(const state: TLoanState): boolean;
var
i, len: integer;
st: TLoanState;
begin
Result := false;
len := Length(FLoanStatusHistory);
for i := 0 to len - 1 do
begin
st := FLoanStatusHistory[i];
if st = state then
begin
Result := true;
Exit;
end;
end;
end;
function TLoan.GetIsFinalised: boolean;
begin
Result := IsRejected or IsCancelled or IsActive or IsClosed;
end;
function TLoan.GetTotalCharges: currency;
var
i, cnt: integer;
total: currency;
begin
cnt := GetLoanChargeCount - 1;
total := 0;
for i := 0 to cnt do total := FLoanCharges[i].Amount + total;
Result := total;
end;
function TLoan.GetTotalInterestDue: currency;
begin
Result := GetInterestDueAsOfDate + FInterestDeficit;
end;
function TLoan.GetTotalReleased: currency;
var
rr: TReleaseRecipient;
total: currency;
begin
total := 0;
for rr in FReleaseRecipients do
total := total + rr.Amount;
Result := total;
end;
end.
|
unit uNexSignAC_Svc;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, SvcMgr, ncDebug;
type
TSvcThread = class (TThread)
protected
procedure ProcessMessages;
public
constructor Create;
destructor Destroy; override;
procedure Execute; override;
end;
TNexSignAC = class(TService)
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
procedure ServiceStart(Sender: TService; var Started: Boolean);
procedure ServiceExecute(Sender: TService);
private
{ Private declarations }
public
function GetServiceController: TServiceController; override;
{ Public declarations }
end;
var
NexSignAC: TNexSignAC;
SvcThread : TSvcThread = nil;
implementation
{$R *.DFM}
uses uDMGeraSignAC;
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
NexSignAC.Controller(CtrlCode);
end;
function TNexSignAC.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
{ TSvcThread }
constructor TSvcThread.Create;
begin
inherited Create(True);
SvcThread := Self;
end;
destructor TSvcThread.Destroy;
begin
SvcThread := nil;
inherited;
end;
procedure TSvcThread.Execute;
var Dummy: Integer;
begin
dmSignAC := nil;
try
try
dmSignAC := TDMSignAC.Create(nil);
while (not Terminated) do begin
MsgWaitForMultipleObjects(0, Dummy, False, 500, QS_ALLINPUT);
try
ProcessMessages;
except
end;
end;
except
on E: Exception do
DebugMsgEsp('TSvcThread.Execute - E.Message: ' + E.Message, False, True);
end;
if dmSignAC<>nil then
FreeAndNil(dmSignAC);
except
on E: Exception do
DebugMsgEsp('TSvcThread.Execute - E.Message: ' + E.Message, False, True);
end;
end;
procedure TSvcThread.ProcessMessages;
var Msg : TMsg;
begin
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
procedure TNexSignAC.ServiceExecute(Sender: TService);
begin
try SvcThread.Resume; except end;
while not Terminated do begin
ServiceThread.ProcessRequests(False);
Sleep(5);
end;
try SvcThread.Suspend; except end;
end;
procedure TNexSignAC.ServiceStart(Sender: TService;
var Started: Boolean);
begin
SvcThread := TSvcThread.Create;
Started := True;
end;
procedure TNexSignAC.ServiceStop(Sender: TService;
var Stopped: Boolean);
begin
if SvcThread <> nil then
SvcThread.Resume;
if SvcThread <> nil then
SvcThread.Terminate;
if SvcThread <> nil then
SvcThread.WaitFor;
Stopped := True;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLSmoothNavigator<p>
An extention of TGLNavigator, which allows to move objects with inertia
Note: it is not completely FPS-independant. Only Moving code is, but
MoveAroundTarget, Turn[Vertical/Horizontal] and AdjustDistanceTo[..] is not.
Don't know why, but when I make their code identical, these function stop
working completely. So you probably have to call the AutoScaleParameters
procedure once in a while for it to adjust to the current framerate.
If someone knows a better way to solve this issue, please contact me via
glscene newsgroups.<p>
<b>History : </b><font size=-1><ul>
<li>30/06/11 - DaStr - Converted many procedures to functions
Bugfixed Assign() in some places
Added "Cutoff" property instead of fixed EPS values
<li>02/06/11 - DaStr - DeltaTime is now Double, like in Cadencer
Added CustomAnimatedItems
<li>28/05/11 - DaStr - Added the AdjustDistanceTo[..]Ex procedures
<li>25/02/07 - DaStr - Added the AdjustDistanceTo[..] procedures
<li>23/02/07 - DaStr - Initial version (contributed to GLScene)
TODO:
1) Scale "Old values" too, when callin the Scale parameter procedure to
avoid the temporary "freeze" of controls.
2) AddImpulse procedures.
Previous version history:
v1.0 10 December '2005 Creation
v1.0.2 11 December '2005 TurnMaxAngle added
v1.1 04 March '2006 Inertia became FPS-independant
TGLSmoothNavigatorParameters added
v1.1.6 18 February '2007 Merged with GLInertedUserInterface.pas
All parameters moved into separate classes
Added MoveAroudTargetWithInertia
v1.2 23 February '2007 Finally made it trully FPS-independant
Added default values to every property
Contributed to GLScene
}
unit GLSmoothNavigator;
interface
{$I GLScene.inc}
uses
System.Classes,
// GLS
GLScene, GLVectorTypes, GLNavigator, GLVectorGeometry, GLCrossPlatform,
GLCoordinates, GLScreen, XCollection;
type
{: TGLNavigatorAdjustDistanceParameters includes a basic set of parameters
that control the smoothness of movement.<p>
}
TGLNavigatorAbstractParameters = class(TPersistent)
private
FOwner: TPersistent;
FInertia: Single;
FSpeed: Single;
FCutoff: Single;
function StoreCutoff: Boolean;
protected
function StoreInertia: Boolean; virtual;
function StoreSpeed: Boolean; virtual;
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); virtual;
published
property Inertia: Single read FInertia write FInertia stored StoreInertia;
property Speed: Single read FSpeed write FSpeed stored StoreSpeed;
property Cutoff: Single read FCutoff write FCutoff stored StoreCutoff;
end;
TGLSmoothNavigator = class;
{: TGLNavigatorSmoothChangeItem includes a basic set of parameters
that control the smoothness of movement.<p>
}
TGLNavigatorSmoothChangeItem = class(TXCollectionItem)
private
FInertia: Single;
FSpeed: Single;
FEnabled: Boolean;
FSpeedLimit: Single;
FCutoff: Double;
function StoreInertia: Boolean;
function StoreSpeed: Boolean;
function StoreSpeedLimit: Boolean;
function StoreCutoff: Boolean;
protected
function GetNavigator: TGLSmoothNavigator;
public
{: Returns False if there was no change. }
function Proceed(ADeltaTime: Double): Boolean; virtual; abstract;
constructor Create(aOwner: TXCollection); override;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); virtual;
procedure ResetTargetValue(); virtual; abstract;
published
property Inertia: Single read FInertia write FInertia stored StoreInertia;
property Speed: Single read FSpeed write FSpeed stored StoreSpeed;
property SpeedLimit: Single read FSpeedLimit write FSpeedLimit stored StoreSpeedLimit;
property Cutoff: Double read FCutoff write FCutoff stored StoreCutoff;
property Enabled: Boolean read FEnabled write FEnabled default True;
end;
TGLNavigatorSmoothChangeSingle = class;
TGLNavigatorSmoothChangeSingleGetEvent = function(const ASender: TGLNavigatorSmoothChangeSingle): Single of object;
TGLNavigatorSmoothChangeSingleSetEvent = procedure(const ASender: TGLNavigatorSmoothChangeSingle; const AValue: Single) of object;
{: Smoothly change any Single value, so it will become TargetValue in the end.<p> }
TGLNavigatorSmoothChangeSingle = class(TGLNavigatorSmoothChangeItem)
private
FTargetValue: Single;
FOnGetCurrentValue: TGLNavigatorSmoothChangeSingleGetEvent;
FOnSetCurrentValue: TGLNavigatorSmoothChangeSingleSetEvent;
public
class function FriendlyName: string; override;
function Proceed(ADeltaTime: Double): Boolean; override;
procedure Assign(Source: TPersistent); override;
procedure ResetTargetValue(); override;
published
property TargetValue: Single read FTargetValue write FTargetValue;
property OnGetCurrentValue: TGLNavigatorSmoothChangeSingleGetEvent read FOnGetCurrentValue write FOnGetCurrentValue;
property OnSetCurrentValue: TGLNavigatorSmoothChangeSingleSetEvent read FOnSetCurrentValue write FOnSetCurrentValue;
end;
TGLNavigatorSmoothChangeVector = class;
TGLNavigatorSmoothChangeVectorGetEvent = function(const ASender: TGLNavigatorSmoothChangeVector): TVector of object;
TGLNavigatorSmoothChangeVectorSetEvent = procedure(const ASender: TGLNavigatorSmoothChangeVector; const AValue: TVector) of object;
{: Smoothly change any Vector4f value, so it will become TargetValue in the end.<p> }
TGLNavigatorSmoothChangeVector = class(TGLNavigatorSmoothChangeItem)
private
FTargetValue: TGLCoordinates;
FOnGetCurrentValue: TGLNavigatorSmoothChangeVectorGetEvent;
FOnSetCurrentValue: TGLNavigatorSmoothChangeVectorSetEvent;
procedure SetTargetValue(const Value: TGLCoordinates);
public
class function FriendlyName: string; override;
function Proceed(ADeltaTime: Double): Boolean; override;
procedure Assign(Source: TPersistent); override;
constructor Create(aOwner: TXCollection); override;
destructor Destroy; override;
procedure ResetTargetValue(); override;
published
property TargetValue: TGLCoordinates read FTargetValue write SetTargetValue;
property OnGetCurrentValue: TGLNavigatorSmoothChangeVectorGetEvent read FOnGetCurrentValue write FOnGetCurrentValue;
property OnSetCurrentValue: TGLNavigatorSmoothChangeVectorSetEvent read FOnSetCurrentValue write FOnSetCurrentValue;
end;
TGLNavigatorSmoothChangeItemClass = class of TGLNavigatorSmoothChangeItem;
{: XCollection of TGLNavigatorSmoothChangeItem. }
TGLNavigatorSmoothChangeItems = class(TXCollection)
private
function GetItems(const Index : Integer): TGLNavigatorSmoothChangeItem;
procedure SetItems(const Index : Integer; const Value: TGLNavigatorSmoothChangeItem);
protected
procedure DoProceed(ADeltaTime: Double);
public
function Add(AClass : TGLNavigatorSmoothChangeItemClass): TGLNavigatorSmoothChangeItem;
function CanAdd(AClass: TXCollectionItemClass): Boolean; override;
class function ItemsClass: TXCollectionItemClass; override;
property Items[const Index : Integer]: TGLNavigatorSmoothChangeItem read GetItems write
SetItems; default;
end;
{: TGLNavigatorAdjustDistanceParameters is wrapper for all parameters that
affect how the AdjustDisanceTo[...] methods work<p>
}
TGLNavigatorAdjustDistanceParameters = class(TGLNavigatorAbstractParameters)
private
FOldDistanceRatio: Single;
FImpulseSpeed: Single;
function StoreImpulseSpeed: Boolean;
public
constructor Create(AOwner: TPersistent); override;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); override;
procedure AddImpulse(const Impulse: Single); virtual;
published
property ImpulseSpeed: Single read FImpulseSpeed write FImpulseSpeed stored StoreImpulseSpeed;
end;
{: TGLNavigatorAdjustDistanceParameters is wrapper for all parameters that
affect how the AdjustDisanceTo[...]Ex methods work<p>
You need to set the TargetObject and desired distance to it,
then call AdjustDisanceTo[...]Ex() in your Cadencer.OnProgress code.
}
TGLNavigatorAdjustDistanceParametersEx = class(TGLNavigatorAbstractParameters)
private
FSpeedLimit: Single;
FTargetDistance: Single;
function StoreSpeedLimit: Boolean;
function StoreTargetDistance: Boolean;
protected
function StoreSpeed: Boolean; override;
function StoreInertia: Boolean; override;
public
constructor Create(AOwner: TPersistent); override;
procedure Assign(Source: TPersistent); override;
published
property TargetDistance: Single read FTargetDistance write FTargetDistance stored StoreTargetDistance;
property SpeedLimit: Single read FSpeedLimit write FSpeedLimit stored StoreSpeedLimit;
end;
{: TGLNavigatorInertiaParameters is wrapper for all parameters that affect the
smoothness of movement<p>
}
TGLNavigatorInertiaParameters = class(TPersistent)
private
FOwner: TPersistent;
OldTurnHorizontalAngle: Single;
OldTurnVerticalAngle: Single;
OldMoveForwardDistance: Single;
OldStrafeHorizontalDistance: Single;
OldStrafeVerticalDistance: Single;
FTurnInertia: Single;
FTurnSpeed: Single;
FTurnMaxAngle: Single;
FMovementAcceleration: Single;
FMovementInertia: Single;
FMovementSpeed: Single;
function StoreTurnMaxAngle: Boolean;
function StoreMovementAcceleration: Boolean;
function StoreMovementInertia: Boolean;
function StoreMovementSpeed: Boolean;
function StoreTurnInertia: Boolean;
function StoreTurnSpeed: Boolean;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); virtual;
published
property MovementAcceleration: Single read FMovementAcceleration write FMovementAcceleration stored StoreMovementAcceleration;
property MovementInertia: Single read FMovementInertia write FMovementInertia stored StoreMovementInertia;
property MovementSpeed: Single read FMovementSpeed write FMovementSpeed stored StoreMovementSpeed;
property TurnMaxAngle: Single read FTurnMaxAngle write FTurnMaxAngle stored StoreTurnMaxAngle;
property TurnInertia: Single read FTurnInertia write FTurnInertia stored StoreTurnInertia;
property TurnSpeed: Single read FTurnSpeed write FTurnSpeed stored StoreTurnSpeed;
end;
{: TGLNavigatorGeneralParameters is a wrapper for all general inertia parameters.
These properties mean that if ExpectedMaxFPS is 100, FAutoScaleMin is 0.1,
FAutoScaleMax is 0.75 then the "safe range" for it to change is [10..75].
If these bounds are violated, then ExpectedMaxFPS is automaticly increased
or decreased by AutoScaleMult.
}
TGLNavigatorGeneralParameters = class(TPersistent)
private
FOwner: TPersistent;
FAutoScaleMin: Single;
FAutoScaleMax: Single;
FAutoScaleMult: Single;
function StoreAutoScaleMax: Boolean;
function StoreAutoScaleMin: Boolean;
function StoreAutoScaleMult: Boolean;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
published
property AutoScaleMin: Single read FAutoScaleMin write FAutoScaleMin stored StoreAutoScaleMin;
property AutoScaleMax: Single read FAutoScaleMax write FAutoScaleMax stored StoreAutoScaleMax;
property AutoScaleMult: Single read FAutoScaleMult write FAutoScaleMult stored StoreAutoScaleMult;
end;
{: TGLNavigatorMoveAroundParameters is a wrapper for all parameters that
effect how the TGLBaseSceneObject.MoveObjectAround() procedure works
}
TGLNavigatorMoveAroundParameters = class(TPersistent)
private
FOwner: TPersistent;
FTargetObject: TGLBaseSceneObject;
FOldPitchInertiaAngle : Single;
FOldTurnInertiaAngle : Single;
FPitchSpeed : Single;
FTurnSpeed : Single;
FInertia : Single;
FMaxAngle : Single;
FCutoff: Double;
function StoreInertia: Boolean;
function StoreMaxAngle: Boolean;
function StorePitchSpeed: Boolean;
function StoreTurnSpeed: Boolean;
procedure SetTargetObject(const Value: TGLBaseSceneObject);
function StoreCutoff: Boolean;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent); virtual;
procedure Assign(Source: TPersistent); override;
procedure ScaleParameters(const Value: Single); virtual;
published
property Inertia: Single read FInertia write FInertia stored StoreInertia;
property MaxAngle: Single read FMaxAngle write FMaxAngle stored StoreMaxAngle;
property PitchSpeed: Single read FPitchSpeed write FPitchSpeed stored StorePitchSpeed;
property TurnSpeed: Single read FTurnSpeed write FTurnSpeed stored StoreTurnSpeed;
property TargetObject: TGLBaseSceneObject read FTargetObject write SetTargetObject;
property Cutoff: Double read FCutoff write FCutoff stored StoreCutoff;
end;
// TGLSmoothNavigator
//
{: TGLSmoothNavigator is the component for moving a TGLBaseSceneObject, and all
classes based on it, this includes all the objects from the Scene Editor.<p>
It uses complex smoothing algorithms, most of which are FPS-dependant.
Make sure your limit your FPS and set MaxExpectedDeltaTime to a value
that is aproximatly 5 times less than your usual deltatime.
}
TGLSmoothNavigator = class(TGLNavigator)
private
FMaxExpectedDeltaTime: Double;
FInertiaParams: TGLNavigatorInertiaParameters;
FGeneralParams: TGLNavigatorGeneralParameters;
FMoveAroundParams: TGLNavigatorMoveAroundParameters;
FAdjustDistanceParams: TGLNavigatorAdjustDistanceParameters;
FAdjustDistanceParamsEx: TGLNavigatorAdjustDistanceParametersEx;
FCustomAnimatedItems: TGLNavigatorSmoothChangeItems;
procedure SetInertiaParams(const Value: TGLNavigatorInertiaParameters);
function StoreMaxExpectedDeltaTime: Boolean;
procedure SetGeneralParams(const Value: TGLNavigatorGeneralParameters);
procedure SetMoveAroundParams(const Value: TGLNavigatorMoveAroundParameters);
procedure SetAdjustDistanceParams(const Value: TGLNavigatorAdjustDistanceParameters);
procedure SetAdjustDistanceParamsEx(
const Value: TGLNavigatorAdjustDistanceParametersEx);
procedure SetCustomAnimatedItems(
const Value: TGLNavigatorSmoothChangeItems);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
//: Constructors-destructors.
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
//: From TGLNavigator. Probably, should not be public.
procedure SetObject(Value: TGLBaseSceneObject); override;
//: Uses InertiaParams.
procedure TurnHorizontal(Angle: Single; ADeltaTime: Double); virtual;
procedure TurnVertical(Angle: Single; ADeltaTime: Double); virtual;
procedure FlyForward(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False); virtual;
procedure MoveForward(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False); virtual;
procedure StrafeHorizontal(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False); virtual;
procedure StrafeVertical(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False); virtual;
//: Uses MoveAroundParams. Returns True, if object was actually moved.
function MoveAroundTarget(const PitchDelta, TurnDelta : Single; const ADeltaTime: Double): Boolean; virtual;
function MoveObjectAround(const AObject: TGLBaseSceneObject; PitchDelta, TurnDelta : Single; ADeltaTime: Double): Boolean; virtual;
//: Uses AdjustDistanceParams.
function AdjustDistanceToPoint(const APoint: TVector; const DistanceRatio : Single; ADeltaTime: Double): Boolean; virtual;
function AdjustDistanceToTarget(const DistanceRatio : Single; const ADeltaTime: Double): Boolean; virtual;
//: Uses AdjustDistanceParamsEx.
function AdjustDistanceToPointEx(const APoint: TVector; ADeltaTime: Double): Boolean; virtual;
function AdjustDistanceToTargetEx(const ADeltaTime: Double): Boolean; virtual;
//: Uses CustomAnimatedItems.
procedure AnimateCustomItems(const ADeltaTime: Double); virtual;
//: Uses GeneralParams.
{: In ScaleParameters, Value should be around 1. }
procedure ScaleParameters(const Value: Single); virtual;
procedure AutoScaleParameters(const FPS: Single); virtual;
procedure AutoScaleParametersUp(const FPS: Single); virtual;
published
property MaxExpectedDeltaTime: Double read FMaxExpectedDeltaTime write FMaxExpectedDeltaTime stored StoreMaxExpectedDeltaTime;
property InertiaParams: TGLNavigatorInertiaParameters read FInertiaParams write SetInertiaParams;
property GeneralParams: TGLNavigatorGeneralParameters read FGeneralParams write SetGeneralParams;
property MoveAroundParams: TGLNavigatorMoveAroundParameters read FMoveAroundParams write SetMoveAroundParams;
property AdjustDistanceParams: TGLNavigatorAdjustDistanceParameters read FAdjustDistanceParams write SetAdjustDistanceParams;
property AdjustDistanceParamsEx: TGLNavigatorAdjustDistanceParametersEx read FAdjustDistanceParamsEx write SetAdjustDistanceParamsEx;
property CustomAnimatedItems: TGLNavigatorSmoothChangeItems read FCustomAnimatedItems write SetCustomAnimatedItems;
end;
// TGLSmoothUserInterface
//
{: TGLSmoothUserInterface is the component which reads the userinput and transform it into action.<p>
<ul>
<li>Mouselook(ADeltaTime: double) : handles mouse look... Should be called
in the Cadencer event. (Though it works everywhere!)
</ul>
The four properties to get you started are:
<ul>
<li>InvertMouse : Inverts the mouse Y axis.
<li>AutoUpdateMouse : If enabled (by defaul), than handles all mouse updates.
<li>GLNavigator : The Navigator which receives the user movement.
<li>GLVertNavigator : The Navigator which if set receives the vertical user
movement. Used mostly for cameras....
</ul>
}
TGLSmoothUserInterface = class(TComponent)
private
FAutoUpdateMouse: Boolean;
FMouseLookActive: Boolean;
FSmoothNavigator: TGLSmoothNavigator;
FSmoothVertNavigator: TGLSmoothNavigator;
FInvertMouse: Boolean;
FOriginalMousePos: TGLCoordinates2;
procedure SetSmoothNavigator(const Value: TGLSmoothNavigator); virtual;
procedure SetOriginalMousePos(const Value: TGLCoordinates2); virtual;
procedure SetSmoothVertNavigator(const Value: TGLSmoothNavigator); virtual;
procedure SetMouseLookActive(const Value: Boolean); virtual;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure TurnHorizontal(const Angle : Single; const ADeltaTime: Double); virtual;
procedure TurnVertical(const Angle : Single; const ADeltaTime: Double); virtual;
procedure MouseLookActiveToggle; virtual;
function MouseLook(const ADeltaTime: Double): Boolean; overload;
function MouseLook(const NewXY: TGLPoint; const ADeltaTime: Double): Boolean; overload;
function MouseLook(const NewX, NewY: Integer; const ADeltaTime: Double): Boolean; overload;
published
property AutoUpdateMouse: Boolean read FAutoUpdateMouse write FAutoUpdateMouse default True;
property MouseLookActive: Boolean read FMouseLookActive write SetMouseLookActive default False;
property SmoothVertNavigator: TGLSmoothNavigator read FSmoothVertNavigator write SetSmoothVertNavigator;
property SmoothNavigator: TGLSmoothNavigator read FSmoothNavigator write SetSmoothNavigator;
property InvertMouse: Boolean read FInvertMouse write FInvertMouse default False;
property OriginalMousePos: TGLCoordinates2 read FOriginalMousePos write SetOriginalMousePos;
end;
implementation
const
EPS = 0.001;
EPS2 = 0.0001;
EPS8 = 0.00000001;
{ TGLSmoothNavigator }
constructor TGLSmoothNavigator.Create(AOwner: TComponent);
begin
inherited;
FMaxExpectedDeltaTime := 0.001;
FInertiaParams := TGLNavigatorInertiaParameters.Create(Self);
FGeneralParams := TGLNavigatorGeneralParameters.Create(Self);
FMoveAroundParams := TGLNavigatorMoveAroundParameters.Create(Self);
FAdjustDistanceParams := TGLNavigatorAdjustDistanceParameters.Create(Self);
FAdjustDistanceParamsEx := TGLNavigatorAdjustDistanceParametersEx.Create(Self);
FCustomAnimatedItems := TGLNavigatorSmoothChangeItems.Create(Self);
end;
destructor TGLSmoothNavigator.Destroy;
begin
FInertiaParams.Free;
FGeneralParams.Free;
FMoveAroundParams.Free;
FAdjustDistanceParams.Free;
FAdjustDistanceParamsEx.Free;
FCustomAnimatedItems.Free;
inherited;
end;
procedure TGLSmoothNavigator.SetInertiaParams(
const Value: TGLNavigatorInertiaParameters);
begin
FInertiaParams.Assign(Value);
end;
procedure TGLSmoothNavigator.TurnHorizontal(Angle: Single; ADeltaTime: Double);
var
FinalAngle: Single;
begin
with FInertiaParams do
begin
FinalAngle := 0;
Angle := Angle * FTurnSpeed;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
Angle := ClampValue((Angle * FMaxExpectedDeltaTime + OldTurnHorizontalAngle * FTurnInertia) / (FTurnInertia + 1), -FTurnMaxAngle, FTurnMaxAngle);
OldTurnHorizontalAngle := Angle;
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalAngle := FinalAngle + Angle;
end;
end;
if (Abs(FinalAngle) > EPS) then
inherited TurnHorizontal(FinalAngle);
end;
procedure TGLSmoothNavigator.TurnVertical(Angle: Single; ADeltaTime: Double);
var
FinalAngle: Single;
begin
with FInertiaParams do
begin
FinalAngle := 0;
Angle := Angle * FTurnSpeed;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
Angle := ClampValue((Angle * FMaxExpectedDeltaTime + OldTurnVerticalAngle * FTurnInertia) / (FTurnInertia + 1), -FTurnMaxAngle, FTurnMaxAngle);
OldTurnVerticalAngle := Angle;
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalAngle := FinalAngle + Angle;
end;
end;
if (Abs(FinalAngle) > EPS) then
inherited TurnVertical(FinalAngle);
end;
procedure TGLSmoothNavigator.MoveForward(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
OldMoveForwardDistance := (Distance * FMaxExpectedDeltaTime + OldMoveForwardDistance * FMovementInertia) / (FMovementInertia + 1);
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldMoveForwardDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited MoveForward(FinalDistance);
end;
procedure TGLSmoothNavigator.FlyForward(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
OldMoveForwardDistance := (Distance * FMaxExpectedDeltaTime + OldMoveForwardDistance * FMovementInertia) / (FMovementInertia + 1);
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldMoveForwardDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited FlyForward(FinalDistance);
end;
procedure TGLSmoothNavigator.StrafeHorizontal(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
OldStrafeHorizontalDistance := (Distance * FMaxExpectedDeltaTime + OldStrafeHorizontalDistance * FMovementInertia) / (FMovementInertia + 1);
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldStrafeHorizontalDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited StrafeHorizontal(FinalDistance);
end;
procedure TGLSmoothNavigator.StrafeVertical(const Plus, Minus: Boolean; ADeltaTime: Double; const Accelerate: Boolean = False);
var
FinalDistance: Single;
Distance: Single;
begin
with FInertiaParams do
begin
if Plus then
Distance := FMovementSpeed
else if Minus then
Distance := -FMovementSpeed
else
Distance := 0;
if Accelerate then
Distance := Distance * FMovementAcceleration;
FinalDistance := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
OldStrafeVerticalDistance := (Distance * FMaxExpectedDeltaTime + OldStrafeVerticalDistance * FMovementInertia) / (FMovementInertia + 1);
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalDistance := FinalDistance + OldStrafeVerticalDistance;
end;
end;
if Abs(FinalDistance) > EPS then
inherited StrafeVertical(FinalDistance);
end;
procedure TGLSmoothNavigator.AutoScaleParameters(const FPS: Single);
begin
with FGeneralParams do
begin
if FPS > FAutoScaleMax / FMaxExpectedDeltatime then
ScaleParameters(FAutoScaleMult)
else if FPS < FAutoScaleMin / FMaxExpectedDeltatime then
ScaleParameters(1/FAutoScaleMult);
end;
end;
procedure TGLSmoothNavigator.AutoScaleParametersUp(const FPS: Single);
begin
with FGeneralParams do
begin
if FPS > FAutoScaleMax / FMaxExpectedDeltatime then
ScaleParameters(FAutoScaleMult)
end;
end;
procedure TGLSmoothNavigator.ScaleParameters(const Value: Single);
begin
Assert(Value > 0);
FMaxExpectedDeltatime := FMaxExpectedDeltatime / Value;
FInertiaParams.ScaleParameters(Value);
FMoveAroundParams.ScaleParameters(Value);
FAdjustDistanceParams.ScaleParameters(Value);
end;
function TGLSmoothNavigator.StoreMaxExpectedDeltaTime: Boolean;
begin
Result := Abs(FMaxExpectedDeltaTime - 0.001) > EPS2;
end;
procedure TGLSmoothNavigator.SetGeneralParams(
const Value: TGLNavigatorGeneralParameters);
begin
FGeneralParams.Assign(Value);
end;
procedure TGLSmoothNavigator.SetMoveAroundParams(
const Value: TGLNavigatorMoveAroundParameters);
begin
FMoveAroundParams.Assign(Value);
end;
procedure TGLSmoothNavigator.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation = opRemove then
begin
if AComponent = FMoveAroundParams.FTargetObject then
FMoveAroundParams.FTargetObject := nil;
end;
end;
procedure TGLSmoothNavigator.SetObject(Value: TGLBaseSceneObject);
var
I: Integer;
begin
inherited;
// Try to detect a TargetObject.
if Value <> nil then
if FMoveAroundParams.TargetObject = nil then
begin
// May be it is a camera...
if Value is TGLCamera then
FMoveAroundParams.TargetObject := TGLCamera(Value).TargetObject
else
begin
// May be it has camera children...
if Value.Count <> 0 then
for I := 0 to Value.Count - 1 do
if Value.Children[I] is TGLCamera then
begin
FMoveAroundParams.TargetObject := TGLCamera(Value.Children[I]).TargetObject;
Exit;
end;
end;
end;
end;
function TGLSmoothNavigator.MoveAroundTarget(const PitchDelta, TurnDelta: Single;
const ADeltaTime: Double): Boolean;
begin
Result := MoveObjectAround(FMoveAroundParams.FTargetObject, PitchDelta, TurnDelta, ADeltaTime);
end;
function TGLSmoothNavigator.MoveObjectAround(
const AObject: TGLBaseSceneObject; PitchDelta, TurnDelta: Single;
ADeltaTime: Double): Boolean;
var
FinalPitch: Single;
FinalTurn: Single;
lUp: TVector;
begin
Result := False;
FinalPitch := 0;
FinalTurn := 0;
with FMoveAroundParams do
begin
PitchDelta := PitchDelta * FPitchSpeed;
TurnDelta := TurnDelta * FTurnSpeed;
while ADeltaTime > FMaxExpectedDeltatime do
begin
PitchDelta := ClampValue((PitchDelta * FMaxExpectedDeltatime + FOldPitchInertiaAngle * FInertia) / (FInertia + 1), - FMaxAngle, FMaxAngle);
FOldPitchInertiaAngle := PitchDelta;
FinalPitch := FinalPitch + PitchDelta;
TurnDelta := ClampValue((TurnDelta * FMaxExpectedDeltatime + FOldTurnInertiaAngle * FInertia) / (FInertia + 1), - FMaxAngle, FMaxAngle);
FOldTurnInertiaAngle := TurnDelta;
FinalTurn := FinalTurn + TurnDelta;
ADeltaTime := ADeltaTime - FMaxExpectedDeltatime;
end;
if UseVirtualUp then
lUp := VirtualUp.AsVector
else
lUp := MovingObject.AbsoluteUp;
if (Abs(FinalPitch) > FCutOff) or (Abs(FinalTurn) > FCutOff) then
begin
MovingObject.AbsolutePosition := GLVectorGeometry.MoveObjectAround(
MovingObject.AbsolutePosition, lUp, AObject.AbsolutePosition, FinalPitch, FinalTurn);
Result := True;
end;
end;
end;
function TGLSmoothNavigator.AdjustDistanceToPoint(const APoint: TVector;
const DistanceRatio: Single; ADeltaTime: Double): Boolean;
// Based on TGLCamera.AdjustDistanceToTarget
procedure DoAdjustDistanceToPoint(const DistanceRatio: Single);
var
vect: TVector;
begin
vect := VectorSubtract(MovingObject.AbsolutePosition, APoint);
ScaleVector(vect, (distanceRatio - 1));
AddVector(vect, MovingObject.AbsolutePosition);
if Assigned(MovingObject.Parent) then
vect := MovingObject.Parent.AbsoluteToLocal(vect);
MovingObject.Position.AsVector := vect;
Result := True;
end;
var
FinalDistanceRatio: Single;
TempDistanceRatio: Single;
begin
with FAdjustDistanceParams do
begin
TempDistanceRatio := DistanceRatio * FSpeed;
FinalDistanceRatio := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
TempDistanceRatio := (TempDistanceRatio * FMaxExpectedDeltaTime + FOldDistanceRatio * FInertia) / (FInertia + 1);
FOldDistanceRatio := TempDistanceRatio;
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
FinalDistanceRatio := FinalDistanceRatio + FOldDistanceRatio / FMaxExpectedDeltaTime;
end;
if Abs(FinalDistanceRatio) > FCutoff then
begin
if FinalDistanceRatio > 0 then
DoAdjustDistanceToPoint(1 / (1 + FinalDistanceRatio))
else
DoAdjustDistanceToPoint(1 * (1 - FinalDistanceRatio))
end
else
Result := False;
end;
end;
function TGLSmoothNavigator.AdjustDistanceToTarget(const DistanceRatio: Single;
const ADeltaTime: Double): Boolean;
begin
Assert(FMoveAroundParams.FTargetObject <> nil);
Result := AdjustDistanceToPoint(FMoveAroundParams.FTargetObject.AbsolutePosition,
DistanceRatio, ADeltaTime);
end;
procedure TGLSmoothNavigator.SetAdjustDistanceParams(
const Value: TGLNavigatorAdjustDistanceParameters);
begin
FAdjustDistanceParams.Assign(Value);
end;
function TGLSmoothNavigator.AdjustDistanceToPointEx(const APoint: TVector;
ADeltaTime: Double): Boolean;
var
lAbsolutePosition: TVector;
lCurrentDistance: Single;
lDistanceDifference, lTempCurrentDistance: Single;
procedure DoAdjustDistanceToPoint(const DistanceValue: Single);
var
vect: TVector;
begin
vect := VectorSubtract(APoint, lAbsolutePosition);
NormalizeVector(vect);
ScaleVector(vect, DistanceValue);
MovingObject.AbsolutePosition := VectorAdd(lAbsolutePosition, vect);
Result := True;
end;
begin
lAbsolutePosition := MovingObject.AbsolutePosition;
lCurrentDistance := VectorDistance(lAbsolutePosition, APoint);
lDistanceDifference := lCurrentDistance - FAdjustDistanceParamsEx.FTargetDistance;
with FAdjustDistanceParamsEx do
begin
lTempCurrentDistance := 0;
while ADeltaTime > FMaxExpectedDeltaTime do
begin
lTempCurrentDistance := (FSpeed * FMaxExpectedDeltaTime * lDistanceDifference * FInertia) / (FInertia + 1);
// lTempCurrentDistance := (FSpeed * FMaxExpectedDeltaTime + lDistanceDifference * FInertia) / (FInertia + 1);- this also works, but a bit different.
ADeltaTime := ADeltaTime - FMaxExpectedDeltaTime;
end;
lTempCurrentDistance := ClampValue(lTempCurrentDistance, -FSpeedLimit * ADeltaTime, FSpeedLimit * ADeltaTime);
if Abs(lTempCurrentDistance) > FCutoff then
DoAdjustDistanceToPoint(lTempCurrentDistance)
else
Result := False;
end;
end;
function TGLSmoothNavigator.AdjustDistanceToTargetEx(
const ADeltaTime: Double): Boolean;
begin
Assert(FMoveAroundParams.FTargetObject <> nil);
Result := AdjustDistanceToPointEx(FMoveAroundParams.FTargetObject.AbsolutePosition,
ADeltaTime);
end;
procedure TGLSmoothNavigator.SetAdjustDistanceParamsEx(
const Value: TGLNavigatorAdjustDistanceParametersEx);
begin
FAdjustDistanceParamsEx.Assign(Value);
end;
procedure TGLSmoothNavigator.AnimateCustomItems(const ADeltaTime: Double);
begin
FCustomAnimatedItems.DoProceed(ADeltaTime);
end;
procedure TGLSmoothNavigator.SetCustomAnimatedItems(
const Value: TGLNavigatorSmoothChangeItems);
begin
FCustomAnimatedItems.Assign(Value);
end;
{ TGLSmoothUserInterface }
function TGLSmoothUserInterface.MouseLook(
const ADeltaTime: Double): Boolean;
var
MousePos: TGLPoint;
begin
Assert(FAutoUpdateMouse, 'AutoUpdateMouse must be True to use this function');
if FMouseLookActive then
begin
GLGetCursorPos(MousePos);
Result := Mouselook(MousePos.X, MousePos.Y, ADeltaTime);
GLSetCursorPos(Round(OriginalMousePos.X), Round(OriginalMousePos.Y));
end
else
Result := False;
end;
function TGLSmoothUserInterface.Mouselook(const NewX, NewY: Integer; const ADeltaTime: Double): Boolean;
var
DeltaX, DeltaY: Single;
begin
Result := False;
if FMouseLookActive then
begin
Deltax := (NewX - FOriginalMousePos.X);
Deltay := (FOriginalMousePos.Y - NewY);
if InvertMouse then
DeltaY := -DeltaY;
SmoothNavigator.TurnHorizontal(DeltaX, ADeltaTime);
SmoothNavigator.TurnVertical(DeltaY, ADeltaTime);
Result := (DeltaX <> 0) or (DeltaY <> 0);
end;
end;
function TGLSmoothUserInterface.MouseLook(const NewXY: TGLPoint; const ADeltaTime: Double): Boolean;
begin
Result := Mouselook(NewXY.X, NewXY.Y, ADeltaTime);
end;
constructor TGLSmoothUserInterface.Create(AOwner: TComponent);
begin
inherited;
FMouseLookActive := False;
FAutoUpdateMouse := True;
FOriginalMousePos := TGLCoordinates2.CreateInitialized(Self,
VectorMake(GLGetScreenWidth div 2,
GLGetScreenHeight div 2, 0, 0), csPoint2D);
end;
procedure TGLSmoothUserInterface.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
begin
if AComponent = FSmoothNavigator then
FSmoothNavigator := nil;
if AComponent = FSmoothVertNavigator then
FSmoothNavigator := nil;
end;
end;
procedure TGLSmoothUserInterface.SetSmoothNavigator(
const Value: TGLSmoothNavigator);
begin
if FSmoothNavigator <> nil then
FSmoothNavigator.RemoveFreeNotification(Self);
FSmoothNavigator := Value;
if FSmoothNavigator <> nil then
FSmoothNavigator.FreeNotification(Self);
end;
destructor TGLSmoothUserInterface.Destroy;
begin
FOriginalMousePos.Destroy;
inherited;
end;
procedure TGLSmoothUserInterface.SetOriginalMousePos(
const Value: TGLCoordinates2);
begin
FOriginalMousePos.Assign(Value);
end;
procedure TGLSmoothUserInterface.SetSmoothVertNavigator(
const Value: TGLSmoothNavigator);
begin
if FSmoothVertNavigator <> nil then
FSmoothVertNavigator.RemoveFreeNotification(Self);
FSmoothVertNavigator := Value;
if FSmoothVertNavigator <> nil then
FSmoothVertNavigator.FreeNotification(Self);
end;
procedure TGLSmoothUserInterface.MouseLookActiveToggle;
begin
if FMouseLookActive then
SetMouseLookActive(False)
else
SetMouseLookActive(True)
end;
procedure TGLSmoothUserInterface.SetMouseLookActive(const Value: Boolean);
var
MousePos: TGLPoint;
begin
if FMouseLookActive = Value then Exit;
FMouseLookActive := Value;
if FMouseLookActive then
begin
if FAutoUpdateMouse then
begin
GLGetCursorPos(MousePos);
FOriginalMousePos.SetPoint2D(MousePos.X, MousePos.Y);
GLShowCursor(False);
end;
end
else
begin
if FAutoUpdateMouse then
GLShowCursor(True);
end;
end;
procedure TGLSmoothUserInterface.TurnHorizontal(const Angle: Single;
const ADeltaTime: Double);
begin
FSmoothNavigator.TurnHorizontal(Angle, ADeltaTime);
end;
procedure TGLSmoothUserInterface.TurnVertical(const Angle: Single;
const ADeltaTime: Double);
begin
if Assigned(FSmoothNavigator) then
FSmoothNavigator.TurnVertical(Angle, ADeltaTime)
else
FSmoothVertNavigator.TurnVertical(Angle, ADeltaTime);
end;
{ TGLNavigatorInertiaParameters }
procedure TGLNavigatorInertiaParameters.Assign(Source: TPersistent);
begin
if Source is TGLNavigatorInertiaParameters then
begin
FMovementAcceleration := TGLNavigatorInertiaParameters(Source).FMovementAcceleration;
FMovementInertia := TGLNavigatorInertiaParameters(Source).FMovementInertia;
FMovementSpeed := TGLNavigatorInertiaParameters(Source).FMovementSpeed;
FTurnMaxAngle := TGLNavigatorInertiaParameters(Source).FTurnMaxAngle;
FTurnInertia := TGLNavigatorInertiaParameters(Source).FTurnInertia;
FTurnSpeed := TGLNavigatorInertiaParameters(Source).FTurnSpeed;
end
else
inherited; //to the pit of doom ;)
end;
constructor TGLNavigatorInertiaParameters.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
FTurnInertia := 150;
FTurnSpeed := 50;
FTurnMaxAngle := 0.5;
FMovementAcceleration := 7;
FMovementInertia := 200;
FMovementSpeed := 200;
end;
function TGLNavigatorInertiaParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TGLNavigatorInertiaParameters.ScaleParameters(
const Value: Single);
begin
Assert(Value > 0);
if Value > 1 then
begin
FMovementInertia := FMovementInertia * PowerSingle(2, 1 / Value);
FTurnInertia := FTurnInertia * PowerSingle(2, 1 / Value);
end
else
begin
FMovementInertia := FMovementInertia / PowerSingle(2, Value);
FTurnInertia := FTurnInertia / PowerSingle(2, Value);
end;
FTurnMaxAngle := FTurnMaxAngle / Value;
FTurnSpeed := FTurnSpeed * Value;
end;
function TGLNavigatorInertiaParameters.StoreTurnMaxAngle: Boolean;
begin
Result := Abs(FTurnMaxAngle - 0.5) > EPS;
end;
function TGLNavigatorInertiaParameters.StoreMovementAcceleration: Boolean;
begin
Result := Abs(FMovementAcceleration - 7) > EPS;
end;
function TGLNavigatorInertiaParameters.StoreMovementInertia: Boolean;
begin
Result := Abs(FMovementInertia - 200) > EPS;
end;
function TGLNavigatorInertiaParameters.StoreMovementSpeed: Boolean;
begin
Result := Abs(FMovementSpeed - 200) > EPS;
end;
function TGLNavigatorInertiaParameters.StoreTurnInertia: Boolean;
begin
Result := Abs(FTurnInertia - 150) > EPS;
end;
function TGLNavigatorInertiaParameters.StoreTurnSpeed: Boolean;
begin
Result := Abs(FTurnSpeed - 50) > EPS;
end;
{ TGLNavigatorGeneralParameters }
procedure TGLNavigatorGeneralParameters.Assign(Source: TPersistent);
begin
if Source is TGLNavigatorGeneralParameters then
begin
FAutoScaleMin := TGLNavigatorGeneralParameters(Source).FAutoScaleMin;
FAutoScaleMax := TGLNavigatorGeneralParameters(Source).FAutoScaleMax;
FAutoScaleMult := TGLNavigatorGeneralParameters(Source).FAutoScaleMult;
end
else
inherited; //die!
end;
constructor TGLNavigatorGeneralParameters.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
FAutoScaleMin := 0.1;
FAutoScaleMax := 0.75;
FAutoScaleMult := 2;
end;
function TGLNavigatorGeneralParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TGLNavigatorGeneralParameters.StoreAutoScaleMax: Boolean;
begin
Result := Abs(FAutoScaleMax - 0.75) > EPS;
end;
function TGLNavigatorGeneralParameters.StoreAutoScaleMin: Boolean;
begin
Result := Abs(FAutoScaleMin - 0.1) > EPS;
end;
function TGLNavigatorGeneralParameters.StoreAutoScaleMult: Boolean;
begin
Result := Abs(FAutoScaleMult - 2) > EPS;
end;
{ TGLNavigatorMoveAroundParameters }
procedure TGLNavigatorMoveAroundParameters.Assign(Source: TPersistent);
begin
if Source is TGLNavigatorMoveAroundParameters then
begin
FMaxAngle := TGLNavigatorMoveAroundParameters(Source).FMaxAngle;
FInertia := TGLNavigatorMoveAroundParameters(Source).FInertia;
FPitchSpeed := TGLNavigatorMoveAroundParameters(Source).FPitchSpeed;
FTurnSpeed := TGLNavigatorMoveAroundParameters(Source).FTurnSpeed;
FCutoff := TGLNavigatorMoveAroundParameters(Source).FCutoff;
SetTargetObject(TGLNavigatorMoveAroundParameters(Source).FTargetObject);
end
else
inherited; //die
end;
constructor TGLNavigatorMoveAroundParameters.Create(AOwner: TPersistent);
begin
FOwner := AOwner;
FPitchSpeed := 500;
FTurnSpeed := 500;
FInertia := 65;
FMaxAngle := 1.5;
FCutoff := EPS2;
end;
function TGLNavigatorMoveAroundParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TGLNavigatorMoveAroundParameters.ScaleParameters(
const Value: Single);
begin
Assert(Value > 0);
if Value < 1 then
FInertia := FInertia / PowerSingle(2, Value)
else
FInertia := FInertia * PowerSingle(2, 1 / Value);
FMaxAngle := FMaxAngle / Value;
FPitchSpeed := FPitchSpeed * Value;
FTurnSpeed := FTurnSpeed * Value;
end;
procedure TGLNavigatorMoveAroundParameters.SetTargetObject(
const Value: TGLBaseSceneObject);
begin
if FTargetObject <> nil then
if FOwner is TGLSmoothNavigator then
FTargetObject.RemoveFreeNotification(TGLSmoothNavigator(FOwner));
FTargetObject := Value;
if FTargetObject <> nil then
if FOwner is TGLSmoothNavigator then
FTargetObject.FreeNotification(TGLSmoothNavigator(FOwner));
end;
function TGLNavigatorMoveAroundParameters.StoreCutoff: Boolean;
begin
Result := Abs(FCutoff - EPS2) > EPS8;
end;
function TGLNavigatorMoveAroundParameters.StoreInertia: Boolean;
begin
Result := Abs(FInertia - 65) > EPS;
end;
function TGLNavigatorMoveAroundParameters.StoreMaxAngle: Boolean;
begin
Result := Abs(FMaxAngle - 1.5) > EPS;
end;
function TGLNavigatorMoveAroundParameters.StorePitchSpeed: Boolean;
begin
Result := Abs(FPitchSpeed - 500) > EPS;
end;
function TGLNavigatorMoveAroundParameters.StoreTurnSpeed: Boolean;
begin
Result := Abs(FTurnSpeed - 500) > EPS;
end;
{ TGLNavigatorAdjustDistanceParameters }
procedure TGLNavigatorAdjustDistanceParameters.AddImpulse(
const Impulse: Single);
begin
FOldDistanceRatio := FOldDistanceRatio + Impulse * FSpeed / FInertia * FImpulseSpeed;
end;
procedure TGLNavigatorAdjustDistanceParameters.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if Source is TGLNavigatorAdjustDistanceParameters then
begin
FImpulseSpeed := TGLNavigatorAdjustDistanceParameters(Source).FImpulseSpeed;
end;
end;
constructor TGLNavigatorAdjustDistanceParameters.Create(
AOwner: TPersistent);
begin
inherited;
FImpulseSpeed := 0.02;
end;
procedure TGLNavigatorAdjustDistanceParameters.ScaleParameters(
const Value: Single);
begin
inherited;
FImpulseSpeed := FImpulseSpeed / Value;
end;
function TGLNavigatorAdjustDistanceParameters.StoreImpulseSpeed: Boolean;
begin
Result := Abs(FImpulseSpeed - 0.02) > EPS;
end;
{ TGLNavigatorAbstractParameters }
procedure TGLNavigatorAbstractParameters.Assign(Source: TPersistent);
begin
if Source is TGLNavigatorAbstractParameters then
begin
FInertia := TGLNavigatorAbstractParameters(Source).FInertia;
FSpeed := TGLNavigatorAbstractParameters(Source).FSpeed;
FCutoff := TGLNavigatorAbstractParameters(Source).FCutoff;
end
else
inherited; //to the pit of doom ;)
end;
constructor TGLNavigatorAbstractParameters.Create(
AOwner: TPersistent);
begin
FOwner := AOwner;
FInertia := 100;
FSpeed := 0.005;
FCutoff := EPS;
end;
function TGLNavigatorAbstractParameters.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TGLNavigatorAbstractParameters.ScaleParameters(
const Value: Single);
begin
Assert(Value > 0);
if Value < 1 then
FInertia := FInertia / PowerSingle(2, Value)
else
FInertia := FInertia * PowerSingle(2, 1 / Value);
end;
function TGLNavigatorAbstractParameters.StoreCutoff: Boolean;
begin
Result := Abs(FCutoff - EPS) > EPS2;
end;
function TGLNavigatorAbstractParameters.StoreInertia: Boolean;
begin
Result := Abs(FInertia - 100) > EPS;
end;
function TGLNavigatorAbstractParameters.StoreSpeed: Boolean;
begin
Result := Abs(FSpeed - 0.005) > EPS2;
end;
{ TGLNavigatorAdjustDistanceParametersEx }
procedure TGLNavigatorAdjustDistanceParametersEx.Assign(
Source: TPersistent);
begin
if Source is TGLNavigatorAdjustDistanceParametersEx then
begin
FTargetDistance := TGLNavigatorAdjustDistanceParametersEx(Source).FTargetDistance;
FSpeedLimit := TGLNavigatorAdjustDistanceParametersEx(Source).FSpeedLimit;
end
else
inherited;
end;
constructor TGLNavigatorAdjustDistanceParametersEx.Create(
AOwner: TPersistent);
begin
inherited;
FInertia := 0.5;
FTargetDistance := 100;
FSpeed := 100;
FSpeedLimit := 20000;
end;
function TGLNavigatorAdjustDistanceParametersEx.StoreInertia: Boolean;
begin
Result := Abs(FInertia - 0.5) > EPS2;
end;
function TGLNavigatorAdjustDistanceParametersEx.StoreSpeed: Boolean;
begin
Result := Abs(FSpeed - 100) > EPS2;
end;
function TGLNavigatorAdjustDistanceParametersEx.StoreSpeedLimit: Boolean;
begin
Result := Abs(FSpeedLimit - 20000) > EPS2;
end;
function TGLNavigatorAdjustDistanceParametersEx.StoreTargetDistance: Boolean;
begin
Result := Abs(FTargetDistance - 100) > EPS2;
end;
{ TGLNavigatorSmoothChangeItem }
procedure TGLNavigatorSmoothChangeItem.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if Source is TGLNavigatorSmoothChangeItem then
begin
FInertia := TGLNavigatorSmoothChangeItem(Source).FInertia;
FSpeed := TGLNavigatorSmoothChangeItem(Source).FSpeed;
FSpeedLimit := TGLNavigatorSmoothChangeItem(Source).FSpeedLimit;
FCutoff := TGLNavigatorSmoothChangeItem(Source).FCutoff;
FEnabled := TGLNavigatorSmoothChangeItem(Source).FEnabled;
end;
end;
constructor TGLNavigatorSmoothChangeItem.Create(aOwner: TXCollection);
begin
inherited;
FInertia := 1;
FSpeed := 5.5;
FSpeedLimit := 20000;
FCutoff := EPS;
FEnabled := True;
end;
function TGLNavigatorSmoothChangeItem.GetNavigator: TGLSmoothNavigator;
begin
Result := TGLSmoothNavigator(TGLNavigatorSmoothChangeItems(GetOwner).Owner);
end;
procedure TGLNavigatorSmoothChangeItem.ScaleParameters(
const Value: Single);
begin
Assert(Value > 0);
if Value < 1 then
FInertia := FInertia / PowerSingle(2, Value)
else
FInertia := FInertia * PowerSingle(2, 1 / Value);
end;
function TGLNavigatorSmoothChangeItem.StoreCutoff: Boolean;
begin
Result := Abs(FCutoff - EPS) > EPS8;
end;
function TGLNavigatorSmoothChangeItem.StoreInertia: Boolean;
begin
Result := Abs(FInertia - 1) > EPS;
end;
function TGLNavigatorSmoothChangeItem.StoreSpeed: Boolean;
begin
Result := Abs(FSpeed - 5.5) > EPS2;
end;
function TGLNavigatorSmoothChangeItem.StoreSpeedLimit: Boolean;
begin
Result := Abs(FSpeedLimit - 20000) > EPS2;
end;
{ TGLNavigatorSmoothChangeItems }
function TGLNavigatorSmoothChangeItems.Add(AClass : TGLNavigatorSmoothChangeItemClass): TGLNavigatorSmoothChangeItem;
begin
Result := AClass.Create(Self);
end;
function TGLNavigatorSmoothChangeItems.CanAdd(AClass: TXCollectionItemClass): Boolean;
begin
Result := AClass.InheritsFrom(TGLNavigatorSmoothChangeItem);
end;
procedure TGLNavigatorSmoothChangeItems.DoProceed(ADeltaTime: Double);
var
I: Integer;
begin
for I := 0 to Count - 1 do
GetItems(I).Proceed(ADeltaTime);
end;
function TGLNavigatorSmoothChangeItems.GetItems(const Index : Integer): TGLNavigatorSmoothChangeItem;
begin
Result := TGLNavigatorSmoothChangeItem(inherited GetItems(Index));
end;
class function TGLNavigatorSmoothChangeItems.ItemsClass: TXCollectionItemClass;
begin
Result := TGLNavigatorSmoothChangeItem;
end;
procedure TGLNavigatorSmoothChangeItems.SetItems(const Index : Integer; const Value:
TGLNavigatorSmoothChangeItem);
begin
GetItems(Index).Assign(Value);
end;
{ TGLNavigatorSmoothChangeSingle }
procedure TGLNavigatorSmoothChangeSingle.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if Source is TGLNavigatorSmoothChangeVector then
begin
FTargetValue := TGLNavigatorSmoothChangeSingle(Source).TargetValue;
FOnGetCurrentValue := TGLNavigatorSmoothChangeSingle(Source).FOnGetCurrentValue;
FOnSetCurrentValue := TGLNavigatorSmoothChangeSingle(Source).FOnSetCurrentValue;
end;
end;
class function TGLNavigatorSmoothChangeSingle.FriendlyName: string;
begin
Result := 'Navigator SmoothChange Single';
end;
function TGLNavigatorSmoothChangeSingle.Proceed(ADeltaTime: Double): Boolean;
var
lCurrentValue: Single;
lCurrentDifference: Single;
lTotalDistanceToTravelThisTime, lDistanceToTravelThisTime: Single;
lMaxExpectedDeltaTime: Double;
begin
Result := False;
if not FEnabled then Exit;
if not Assigned(FOnGetCurrentValue) then Exit;
if not Assigned(FOnSetCurrentValue) then Exit;
lMaxExpectedDeltaTime := GetNavigator.FMaxExpectedDeltaTime;
lCurrentValue := FOnGetCurrentValue(Self);
lCurrentDifference := FTargetValue - lCurrentValue;
lTotalDistanceToTravelThisTime := 0;
while ADeltaTime > lMaxExpectedDeltaTime do
begin
lDistanceToTravelThisTime := MinFloat((lCurrentDifference * ADeltaTime * FSpeed * FInertia) / (FInertia + 1), FSpeedLimit);
// lDistanceToTravelThisTime := (lCurrentDistance * ADeltaTime + FSpeed * FInertia) / (FInertia + 1);- this also works, but a bit different.
lCurrentDifference := lCurrentDifference - lDistanceToTravelThisTime;
lTotalDistanceToTravelThisTime := lTotalDistanceToTravelThisTime + lDistanceToTravelThisTime;
ADeltaTime := ADeltaTime - lMaxExpectedDeltaTime;
end;
if Abs(lTotalDistanceToTravelThisTime) > FCutoff then
begin
FOnSetCurrentValue(Self, lCurrentValue + lTotalDistanceToTravelThisTime);
Result := True;
end;
end;
procedure TGLNavigatorSmoothChangeSingle.ResetTargetValue;
begin
FTargetValue := FOnGetCurrentValue(Self);
end;
{ TGLNavigatorSmoothChangeVector }
procedure TGLNavigatorSmoothChangeVector.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if Source is TGLNavigatorSmoothChangeVector then
begin
FTargetValue.Assign(TGLNavigatorSmoothChangeVector(Source).TargetValue);
FOnGetCurrentValue := TGLNavigatorSmoothChangeVector(Source).FOnGetCurrentValue;
FOnSetCurrentValue := TGLNavigatorSmoothChangeVector(Source).FOnSetCurrentValue;
end;
end;
constructor TGLNavigatorSmoothChangeVector.Create(aOwner: TXCollection);
begin
inherited;
FTargetValue := TGLCoordinates.CreateInitialized(Self, NullHmgVector, csVector);
end;
destructor TGLNavigatorSmoothChangeVector.Destroy;
begin
FTargetValue.Free;
inherited;
end;
class function TGLNavigatorSmoothChangeVector.FriendlyName: string;
begin
Result := 'Navigator SmoothChange Vector';
end;
function TGLNavigatorSmoothChangeVector.Proceed(ADeltaTime: Double): Boolean;
var
lAbsolutePosition: TVector;
lCurrentDistance: Single;
lTotalDistanceToTravelThisTime, lDistanceToTravelThisTime: Single;
lMaxExpectedDeltaTime: Double;
procedure DoAdjustDistanceToPoint();
var
vect: TVector;
begin
vect := VectorScale(VectorNormalize(VectorSubtract(FTargetValue.DirectVector, lAbsolutePosition)), lTotalDistanceToTravelThisTime);
AddVector(vect, lAbsolutePosition);
// Did we go too far?
if VectorDistance(vect, FTargetValue.DirectVector) > VectorDistance(lAbsolutePosition, FTargetValue.DirectVector) then
vect := FTargetValue.DirectVector;
FOnSetCurrentValue(Self, vect);
Result := True;
end;
begin
Result := False;
if not FEnabled then Exit;
if not Assigned(FOnGetCurrentValue) then Exit;
if not Assigned(FOnSetCurrentValue) then Exit;
lMaxExpectedDeltaTime := GetNavigator.FMaxExpectedDeltaTime;
lAbsolutePosition := FOnGetCurrentValue(Self);
lCurrentDistance := VectorDistance(lAbsolutePosition, FTargetValue.DirectVector);
lTotalDistanceToTravelThisTime := 0;
while ADeltaTime > lMaxExpectedDeltaTime do
begin
lDistanceToTravelThisTime := MinFloat((lCurrentDistance * ADeltaTime * FSpeed * FInertia) / (FInertia + 1), FSpeedLimit);
// lDistanceToTravelThisTime := (lCurrentDistance * ADeltaTime + FSpeed * FInertia) / (FInertia + 1);- this also works, but a bit different.
lCurrentDistance := lCurrentDistance - lDistanceToTravelThisTime;
lTotalDistanceToTravelThisTime := lTotalDistanceToTravelThisTime + lDistanceToTravelThisTime;
ADeltaTime := ADeltaTime - lMaxExpectedDeltaTime;
end;
if Abs(lTotalDistanceToTravelThisTime) > FCutoff then
DoAdjustDistanceToPoint();
end;
procedure TGLNavigatorSmoothChangeVector.ResetTargetValue;
begin
FTargetValue.DirectVector := FOnGetCurrentValue(Self);
end;
procedure TGLNavigatorSmoothChangeVector.SetTargetValue(
const Value: TGLCoordinates);
begin
FTargetValue.Assign(Value);
end;
initialization
RegisterClasses([
TGLSmoothNavigator, TGLSmoothUserInterface,
TGLNavigatorInertiaParameters, TGLNavigatorGeneralParameters,
TGLNavigatorMoveAroundParameters,
TGLNavigatorAdjustDistanceParameters, TGLNavigatorAdjustDistanceParametersEx
]);
RegisterXCollectionItemClass(TGLNavigatorSmoothChangeSingle);
RegisterXCollectionItemClass(TGLNavigatorSmoothChangeVector);
end.
|
unit util;
interface
function WinVersion: string;
function MD5(const Texto: string): string;
implementation
uses
Winapi.Windows, IdHashMessageDigest;
{ ============================================================================== }
function WinVersion: string;
var
VersionInfo: TOSVersionInfo;
begin
Result := '';
VersionInfo.dwOSVersionInfoSize := SizeOf(VersionInfo);
GetVersionEx(VersionInfo);
case VersionInfo.dwPlatformId of
1:
case VersionInfo.dwMinorVersion of
0:
Result := 'Windows 95';
10:
Result := 'Windows 98';
90:
Result := 'Windows Me';
end;
2:
case VersionInfo.dwMajorVersion of
3:
Result := 'Windows NT 3.51';
4:
Result := 'Windows NT 4.0';
5:
case VersionInfo.dwMinorVersion of
0:
Result := 'Windows 2000';
1:
Result := 'Windows XP';
2:
Result := 'Windows XP'; // x64
end;
6:
case VersionInfo.dwMinorVersion of
0:
Result := 'Windows Vista';
1:
Result := 'Windows 7';
2:
Result := 'Windows 8';
end;
end;
end;
end;
{ ============================================================================== }
function MD5(const Texto: string): string;
var
idmd5: TIdHashMessageDigest5;
begin
idmd5 := TIdHashMessageDigest5.Create;
try
Result := idmd5.HashStringAsHex(Texto);
finally
idmd5.Free;
end;
end;
end.
|
(*!------------------------------------------------------------
* [[APP_NAME]] ([[APP_URL]])
*
* @link [[APP_REPOSITORY_URL]]
* @copyright Copyright (c) [[COPYRIGHT_YEAR]] [[COPYRIGHT_HOLDER]]
* @license [[LICENSE_URL]] ([[LICENSE]])
*------------------------------------------------------------- *)
unit AuthController;
interface
{$MODE OBJFPC}
{$H+}
uses
fano;
type
(*!-----------------------------------------------
* controller that handle route :
* /auth
*
* See Routes/Auth/routes.inc
*
* @author [[AUTHOR_NAME]] <[[AUTHOR_EMAIL]]>
*------------------------------------------------*)
TAuthController = class(TAbstractController)
public
function handleRequest(
const request : IRequest;
const response : IResponse;
const args : IRouteArgsReader
) : IResponse; override;
end;
implementation
uses
sysutils;
function TAuthController.handleRequest(
const request : IRequest;
const response : IResponse;
const args : IRouteArgsReader
) : IResponse;
var
postParams : IReadOnlyList;
i, j : integer;
keyName : string;
respBody : IResponseStream;
uploadFiles : IUploadedFileArray;
begin
respBody := response.body();
respBody.write('<html><head><title>Auth controller</title></head><body>');
respBody.write('<h1>Auth controller</h1>');
respBody.write('<ul>');
postParams := request.parsedBodyParams;
for i := 0 to postParams.count() - 1 do
begin
keyName := postParams.keyOfIndex(i);
respBody.write(
format(
'<li>%s=%s</li>',
[
keyName,
request.getParsedBodyParam(keyName)
])
);
end;
respBody.write('</ul>');
respBody.write('<ul>');
for i:= 0 to request.uploadedFiles.count() - 1 do
begin
uploadFiles := request.uploadedFiles.getUploadedFile(i);
for j:=0 to length(uploadFiles) - 1 do
begin
uploadFiles[j].moveTo(
GetCurrentDir() + '/storages/uploads/' + uploadFiles[j].getClientFilename()
);
respBody.write('<li>' + uploadFiles[j].getClientFilename() + '</li>');
end;
end;
respBody.write('</ul>');
respBody.write('</body></html>');
result := response;
end;
end.
|
unit Financas.Model.Connections.ConnectionFiredac;
interface
uses Financas.Model.Connections.Interfaces, FireDAC.Comp.Client, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.FMXUI.Wait, FireDAC.Phys.FBDef, FireDAC.Phys.IBBase, FireDAC.Phys.FB, FireDAC.Comp.UI, Data.DB, FireDAC.DApt,
FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.Phys.SQLite;
Type
TModelConnectionFiredac = class(TInterfacedObject, iModelConnection, iModelConnectionParams)
private
FConnection: TFDConnection;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDPhysFBDriverLink1: TFDPhysFBDriverLink;
FDatabase: String;
FUserName: String;
FPassword: String;
FDriverID: String;
FServer: String;
FPorta: Integer;
procedure ReadParams;
public
constructor Create;
destructor Destroy; override;
class function New: iModelConnection;
function EndConnection: TComponent;
function Database(Value: String): iModelConnectionParams;
function UserName(Value: String): iModelConnectionParams;
function Password(Value: String): iModelConnectionParams;
function DriverID(Value: String): iModelConnectionParams;
function Server(Value: String): iModelConnectionParams;
function Porta(Value: Integer): iModelConnectionParams;
function EndParams: iModelConnection;
function Params: iModelConnectionParams;
function Conectar: iModelConnection;
end;
implementation
uses System.SysUtils;
{ TModelConnectionFiredac }
function TModelConnectionFiredac.Conectar: iModelConnection;
begin
Result := Self;
//
ReadParams;
//
try
FConnection.LoginPrompt := False;
FConnection.Connected := True;
except
on E: Exception do
raise Exception.Create(E.Message);
end;
end;
constructor TModelConnectionFiredac.Create;
begin
FConnection := TFDConnection.Create(nil);
FDGUIxWaitCursor1 := TFDGUIxWaitCursor.Create(nil);
FDPhysFBDriverLink1 := TFDPhysFBDriverLink.Create(nil);
end;
function TModelConnectionFiredac.Database(Value: String): iModelConnectionParams;
begin
Result := Self;
//
FDatabase := Value;
end;
destructor TModelConnectionFiredac.Destroy;
begin
FDGUIxWaitCursor1.Free;
FDPhysFBDriverLink1.Free;
FConnection.Free;
//
inherited;
end;
function TModelConnectionFiredac.DriverID(Value: String): iModelConnectionParams;
begin
Result := Self;
//
FDriverID := Value;
end;
function TModelConnectionFiredac.EndConnection: TComponent;
begin
Result := FConnection;
end;
function TModelConnectionFiredac.EndParams: iModelConnection;
begin
Result := Self;
end;
procedure TModelConnectionFiredac.ReadParams;
begin
FConnection.Params.Database := FDatabase;
FConnection.Params.UserName := FUserName;
FConnection.Params.Password := FPassword;
FConnection.Params.DriverID := FDriverID;
FConnection.Params.Add('Server=' + FServer);
FConnection.Params.Add('Port=' + IntToStr(FPorta));
end;
class function TModelConnectionFiredac.New: iModelConnection;
begin
Result := Self.Create;
end;
function TModelConnectionFiredac.Params: iModelConnectionParams;
begin
Result := Self;
end;
function TModelConnectionFiredac.Password(Value: String): iModelConnectionParams;
begin
Result := Self;
//
FPassword := Value;
end;
function TModelConnectionFiredac.Porta(Value: Integer): iModelConnectionParams;
begin
Result := Self;
//
FPorta := Value;
end;
function TModelConnectionFiredac.Server(Value: String): iModelConnectionParams;
begin
Result := Self;
//
FServer := Value;
end;
function TModelConnectionFiredac.UserName(Value: String): iModelConnectionParams;
begin
Result := Self;
//
FUserName := Value;
end;
end.
|
unit SimConnect;
{
This translation follows the convention of SimConnect.h, where the API
definitions are mapped directly to the SimConnect.Dll library
This means that any application built using this interface will fail to load
on any PC that does not have SimConnect.Dll installed, with the OS reporting
that the application has not been properly installed.
The alternative version uses run-time dynamic loading, which requires an
explicit initialisation call in the application, but can fail gracefully, or
disable FS X connectivity if SimConnect.Dll is not installed.
First translated from SimConnect.h (plus .res, .rc and manifest files)
by Dick "rhumbaflappy" on the AVSim forum
Partly checked (in process) by Jacky Brouze / JAB
Comments welcome to jacky.brouze@vtx.ch
Further updates by Ken Adam (KA) ken@akadamia.co.uk
- Formatted using DelForExp
- Some types corrected
- Delphi style equivalent types added
- Further testing with SDK examples
- Support passsing method to CallDispatch
- Pack records to ensure correct size and location of fields
Updates for FSX SP1A: (Ken Adam)
- Changed manifest
- Additional constants
- Additional enumerated types
- Emended API declarations for AddToClientdataDefinition, RequestClientData,
SetClientData
- Added API declarations for Text and Facilties
}
{$R 'SimConnect.res' 'SimConnect.rc'}
interface
uses Windows, Messages, SysUtils, Classes;
//----------------------------------------------------------------------------
// Constants
//----------------------------------------------------------------------------
type
SIMCONNECT_OBJECT_ID = DWORD;
const
DWORD_MAX = $FFFFFFFF;
FLT_MAX = 3.402823466E+38;
SIMCONNECT_UNUSED = DWORD_MAX; // special value to indicate unused event, ID
SIMCONNECT_OBJECT_ID_USER = 0; // proxy value for User vehicle ObjectID
SIMCONNECT_CAMERA_IGNORE_FIELD = FLT_MAX;
//Used to tell the Camera API to NOT modify the value in this part Of the argument.
SIMCONNECT_CLIENTDATA_MAX_SIZE = 8192; // SP1A
// Notification Group priority values
SIMCONNECT_GROUP_PRIORITY_HIGHEST = 1; // highest priority
SIMCONNECT_GROUP_PRIORITY_HIGHEST_MASKABLE = 10000000;
// highest priority that allows events to be masked
SIMCONNECT_GROUP_PRIORITY_STANDARD = 1900000000; // standard priority
SIMCONNECT_GROUP_PRIORITY_DEFAULT = 2000000000; // default priority
SIMCONNECT_GROUP_PRIORITY_LOWEST = 4000000000;
// priorities lower than this will be ignored
//Weather observations Metar strings
MAX_METAR_LENGTH = 2000;
// Maximum thermal size is 100 km.
MAX_THERMAL_SIZE = 100000.0;
MAX_THERMAL_RATE = 1000.0;
// SIMCONNECT_DATA_INITPOSITION.Airspeed
INITPOSITION_AIRSPEED_CRUISE = -1; // aircraft's cruise airspeed
INITPOSITION_AIRSPEED_KEEP = -2; // keep current airspeed
// AddToClientDataDefinition dwSizeOrType parameter type values (SP1A)
SIMCONNECT_CLIENTDATATYPE_INT8 = -1; // 8-bit integer number
SIMCONNECT_CLIENTDATATYPE_INT16 = -2; // 16-bit integer number
SIMCONNECT_CLIENTDATATYPE_INT32 = -3; // 32-bit integer number
SIMCONNECT_CLIENTDATATYPE_INT64 = -4; // 64-bit integer number
SIMCONNECT_CLIENTDATATYPE_FLOAT32 = -5; // 32-bit floating-point number (float)
SIMCONNECT_CLIENTDATATYPE_FLOAT64 = -6; // 64-bit floating-point number (double)
// AddToClientDataDefinition dwOffset parameter special values
SIMCONNECT_CLIENTDATAOFFSET_AUTO = -1; // automatically compute offset of the ClientData variable
//----------------------------------------------------------------------------
// Type enumerations
//----------------------------------------------------------------------------
type
// Receive data Types
SIMCONNECT_RECV_ID = (
SIMCONNECT_RECV_ID_NULL,
SIMCONNECT_RECV_ID_EXCEPTION,
SIMCONNECT_RECV_ID_OPEN,
SIMCONNECT_RECV_ID_QUIT,
SIMCONNECT_RECV_ID_EVENT,
SIMCONNECT_RECV_ID_EVENT_OBJECT_ADDREMOVE,
SIMCONNECT_RECV_ID_EVENT_FILENAME,
SIMCONNECT_RECV_ID_EVENT_FRAME,
SIMCONNECT_RECV_ID_SIMOBJECT_DATA,
SIMCONNECT_RECV_ID_SIMOBJECT_DATA_BYTYPE,
SIMCONNECT_RECV_ID_WEATHER_OBSERVATION,
SIMCONNECT_RECV_ID_CLOUD_STATE,
SIMCONNECT_RECV_ID_ASSIGNED_OBJECT_ID,
SIMCONNECT_RECV_ID_RESERVED_KEY,
SIMCONNECT_RECV_ID_CUSTOM_ACTION,
SIMCONNECT_RECV_ID_SYSTEM_STATE,
SIMCONNECT_RECV_ID_CLIENT_DATA,
SIMCONNECT_RECV_ID_EVENT_WEATHER_MODE,
SIMCONNECT_RECV_ID_AIRPORT_LIST,
SIMCONNECT_RECV_ID_VOR_LIST,
SIMCONNECT_RECV_ID_NDB_LIST,
SIMCONNECT_RECV_ID_WAYPOINT_LIST
);
TSimConnectRecvId = SIMCONNECT_RECV_ID;
// Data data Types
SIMCONNECT_DATAType = (
SIMCONNECT_DATAType_INVALID, // invalid data Type
SIMCONNECT_DATAType_INT32, // 32-bit integer number
SIMCONNECT_DATAType_INT64, // 64-bit integer number
SIMCONNECT_DATAType_FLOAT32, // 32-bit floating-point number (Single)
SIMCONNECT_DATAType_FLOAT64, // 64-bit floating-point number (Double)
SIMCONNECT_DATAType_STRING8, // 8-byte String
SIMCONNECT_DATAType_STRING32, // 32-byte String
SIMCONNECT_DATAType_STRING64, // 64-byte String
SIMCONNECT_DATAType_STRING128, // 128-byte String
SIMCONNECT_DATAType_STRING256, // 256-byte String
SIMCONNECT_DATAType_STRING260, // 260-byte String
SIMCONNECT_DATAType_STRINGV, // variable-length String
SIMCONNECT_DATAType_INITPOSITION, // see SIMCONNECT_DATA_INITPOSITION
SIMCONNECT_DATAType_MARKERSTATE, // see SIMCONNECT_DATA_MARKERSTATE
SIMCONNECT_DATAType_WAYPOINT, // see SIMCONNECT_DATA_WAYPOINT
SIMCONNECT_DATAType_LATLONALT, // see SIMCONNECT_DATA_LATLONALT
SIMCONNECT_DATAType_XYZ, // see SIMCONNECT_DATA_XYZ
SIMCONNECT_DATAType_MAX // enum limit
);
TSimConnectDataType = SIMCONNECT_DATAType;
// Exception error Types
SIMCONNECT_EXCEPTION = (
SIMCONNECT_EXCEPTION_NONE,
SIMCONNECT_EXCEPTION_ERROR,
SIMCONNECT_EXCEPTION_SIZE_MISMATCH,
SIMCONNECT_EXCEPTION_UNRECOGNIZED_ID,
SIMCONNECT_EXCEPTION_UNOPENED,
SIMCONNECT_EXCEPTION_VERSION_MISMATCH,
SIMCONNECT_EXCEPTION_TOO_MANY_GROUPS,
SIMCONNECT_EXCEPTION_NAME_UNRECOGNIZED,
SIMCONNECT_EXCEPTION_TOO_MANY_EVENT_NAMES,
SIMCONNECT_EXCEPTION_EVENT_ID_DUPLICATE,
SIMCONNECT_EXCEPTION_TOO_MANY_MAPS,
SIMCONNECT_EXCEPTION_TOO_MANY_OBJECTS,
SIMCONNECT_EXCEPTION_TOO_MANY_REQUESTS,
SIMCONNECT_EXCEPTION_WEATHER_INVALID_PORT,
SIMCONNECT_EXCEPTION_WEATHER_INVALID_METAR,
SIMCONNECT_EXCEPTION_WEATHER_UNABLE_TO_GET_OBSERVATION,
SIMCONNECT_EXCEPTION_WEATHER_UNABLE_TO_CREATE_STATION,
SIMCONNECT_EXCEPTION_WEATHER_UNABLE_TO_REMOVE_STATION,
SIMCONNECT_EXCEPTION_INVALID_DATA_Type,
SIMCONNECT_EXCEPTION_INVALID_DATA_SIZE,
SIMCONNECT_EXCEPTION_DATA_ERROR,
SIMCONNECT_EXCEPTION_INVALID_ARRAY,
SIMCONNECT_EXCEPTION_CREATE_OBJECT_FAILED,
SIMCONNECT_EXCEPTION_LOAD_FLIGHTPLAN_FAILED,
SIMCONNECT_EXCEPTION_OPERATION_INVALID_FOR_OBJECT_Type,
SIMCONNECT_EXCEPTION_ILLEGAL_OPERATION,
SIMCONNECT_EXCEPTION_ALREADY_SUBSCRIBED,
SIMCONNECT_EXCEPTION_INVALID_ENUM,
SIMCONNECT_EXCEPTION_DEFINITION_ERROR,
SIMCONNECT_EXCEPTION_DUPLICATE_ID,
SIMCONNECT_EXCEPTION_DATUM_ID,
SIMCONNECT_EXCEPTION_OUT_OF_BOUNDS,
SIMCONNECT_EXCEPTION_ALREADY_CREATED,
SIMCONNECT_EXCEPTION_OBJECT_OUTSIDE_REALITY_BUBBLE,
SIMCONNECT_EXCEPTION_OBJECT_CONTAINER,
SIMCONNECT_EXCEPTION_OBJECT_AI,
SIMCONNECT_EXCEPTION_OBJECT_ATC,
SIMCONNECT_EXCEPTION_OBJECT_SCHEDULE
);
TSimConnectException = SIMCONNECT_EXCEPTION;
// Object Types
SIMCONNECT_SIMOBJECT_Type = (
SIMCONNECT_SIMOBJECT_Type_USER,
SIMCONNECT_SIMOBJECT_Type_ALL,
SIMCONNECT_SIMOBJECT_Type_AIRCRAFT,
SIMCONNECT_SIMOBJECT_Type_HELICOPTER,
SIMCONNECT_SIMOBJECT_Type_BOAT,
SIMCONNECT_SIMOBJECT_Type_GROUND
);
TSimConnectSimObjectType = SIMCONNECT_SIMOBJECT_Type;
// EventState values
SIMCONNECT_STATE = (
SIMCONNECT_STATE_OFF,
SIMCONNECT_STATE_ON
);
TSimConnectState = SIMCONNECT_STATE;
// Object Data Request Period values
SIMCONNECT_PERIOD = (
SIMCONNECT_PERIOD_NEVER,
SIMCONNECT_PERIOD_ONCE,
SIMCONNECT_PERIOD_VISUAL_FRAME,
SIMCONNECT_PERIOD_SIM_FRAME,
SIMCONNECT_PERIOD_SECOND
);
TSimConnectPeriod = SIMCONNECT_PERIOD;
// Mission End values
SIMCONNECT_MISSION_END = (
SIMCONNECT_MISSION_FAILED,
SIMCONNECT_MISSION_CRASHED,
SIMCONNECT_MISSION_SUCCEEDED
);
TSimConnectMissionEnd = SIMCONNECT_MISSION_END;
// SP1A Additions
// ClientData Request Period values
SIMCONNECT_CLIENT_DATA_PERIOD = (
SIMCONNECT_CLIENT_DATA_PERIOD_NEVER,
SIMCONNECT_CLIENT_DATA_PERIOD_ONCE,
SIMCONNECT_CLIENT_DATA_PERIOD_VISUAL_FRAME,
SIMCONNECT_CLIENT_DATA_PERIOD_ON_SET,
SIMCONNECT_CLIENT_DATA_PERIOD_SECOND
);
TSimConnectClientDataPeriod = SIMCONNECT_CLIENT_DATA_PERIOD;
SIMCONNECT_TEXT_TYPE = (
SIMCONNECT_TEXT_TYPE_SCROLL_BLACK,
SIMCONNECT_TEXT_TYPE_SCROLL_WHITE,
SIMCONNECT_TEXT_TYPE_SCROLL_RED,
SIMCONNECT_TEXT_TYPE_SCROLL_GREEN,
SIMCONNECT_TEXT_TYPE_SCROLL_BLUE,
SIMCONNECT_TEXT_TYPE_SCROLL_YELLOW,
SIMCONNECT_TEXT_TYPE_SCROLL_MAGENTA,
SIMCONNECT_TEXT_TYPE_SCROLL_CYAN,
SIMCONNECT_TEXT_TYPE_PRINT_BLACK = $0100,
SIMCONNECT_TEXT_TYPE_PRINT_WHITE,
SIMCONNECT_TEXT_TYPE_PRINT_RED,
SIMCONNECT_TEXT_TYPE_PRINT_GREEN,
SIMCONNECT_TEXT_TYPE_PRINT_BLUE,
SIMCONNECT_TEXT_TYPE_PRINT_YELLOW,
SIMCONNECT_TEXT_TYPE_PRINT_MAGENTA,
SIMCONNECT_TEXT_TYPE_PRINT_CYAN,
SIMCONNECT_TEXT_TYPE_MENU = $0200
);
TSimConnectTextType = SIMCONNECT_TEXT_TYPE;
SIMCONNECT_TEXT_RESULT = (
SIMCONNECT_TEXT_RESULT_MENU_SELECT_1,
SIMCONNECT_TEXT_RESULT_MENU_SELECT_2,
SIMCONNECT_TEXT_RESULT_MENU_SELECT_3,
SIMCONNECT_TEXT_RESULT_MENU_SELECT_4,
SIMCONNECT_TEXT_RESULT_MENU_SELECT_5,
SIMCONNECT_TEXT_RESULT_MENU_SELECT_6,
SIMCONNECT_TEXT_RESULT_MENU_SELECT_7,
SIMCONNECT_TEXT_RESULT_MENU_SELECT_8,
SIMCONNECT_TEXT_RESULT_MENU_SELECT_9,
SIMCONNECT_TEXT_RESULT_MENU_SELECT_10,
SIMCONNECT_TEXT_RESULT_DISPLAYED = $00010000,
SIMCONNECT_TEXT_RESULT_QUEUED,
SIMCONNECT_TEXT_RESULT_REMOVED,
SIMCONNECT_TEXT_RESULT_REPLACED,
SIMCONNECT_TEXT_RESULT_TIMEOUT
);
TSimConnectTextResult = SIMCONNECT_TEXT_RESULT;
SIMCONNECT_WEATHER_MODE = (
SIMCONNECT_WEATHER_MODE_THEME,
SIMCONNECT_WEATHER_MODE_RWW,
SIMCONNECT_WEATHER_MODE_CUSTOM,
SIMCONNECT_WEATHER_MODE_GLOBAL
);
TSimConnectWeatherMode = SIMCONNECT_WEATHER_MODE;
SIMCONNECT_FACILITY_LIST_TYPE = (
SIMCONNECT_FACILITY_LIST_TYPE_AIRPORT,
SIMCONNECT_FACILITY_LIST_TYPE_WAYPOINT,
SIMCONNECT_FACILITY_LIST_TYPE_NDB,
SIMCONNECT_FACILITY_LIST_TYPE_VOR,
SIMCONNECT_FACILITY_LIST_TYPE_COUNT // invalid
);
TSimConnectFacilityListType = SIMCONNECT_FACILITY_LIST_TYPE;
type
SIMCONNECT_VOR_FLAGS = DWORD; // flags for SIMCONNECT_RECV_ID_VOR_LIST
TSimConnectVorFlags = SIMCONNECT_VOR_FLAGS;
const
SIMCONNECT_RECV_ID_VOR_LIST_HAS_NAV_SIGNAL = $00000001; // Has Nav signal
SIMCONNECT_RECV_ID_VOR_LIST_HAS_LOCALIZER = $00000002; // Has localizer
SIMCONNECT_RECV_ID_VOR_LIST_HAS_GLIDE_SLOPE = $00000004; // Has Nav signal
SIMCONNECT_RECV_ID_VOR_LIST_HAS_DME = $00000008; // Station has DME
// end of SP1A Additions
// bits for the Waypoint Flags field: may be combined
type
SIMCONNECT_WAYPOINT_FLAGS = DWORD;
TSimConnectWaypointFlags = SIMCONNECT_WAYPOINT_FLAGS;
const
SIMCONNECT_WAYPOINT_NONE = $00;
SIMCONNECT_WAYPOINT_SPEED_REQUESTED = $04;
// requested speed at waypoint is valid
SIMCONNECT_WAYPOINT_THROTTLE_REQUESTED = $08;
// request a specific throttle percentage
SIMCONNECT_WAYPOINT_COMPUTE_VERTICAL_SPEED = $10;
// compute vertical to speed to reach waypoint altitude when crossing the waypoint
SIMCONNECT_WAYPOINT_ALTITUDE_IS_AGL = $20; // AltitudeIsAGL
SIMCONNECT_WAYPOINT_ON_GROUND = $00100000; // place this waypoint on the ground
SIMCONNECT_WAYPOINT_REVERSE = $00200000;
// Back up to this waypoint. Only valid on first waypoint
SIMCONNECT_WAYPOINT_WRAP_TO_FIRST = $00400000;
// Wrap around back to first waypoint. Only valid on last waypoint.
type
SIMCONNECT_EVENT_FLAG = DWORD;
TSimConnectEventFlag = SIMCONNECT_EVENT_FLAG;
const
SIMCONNECT_EVENT_FLAG_DEFAULT = $00000000;
SIMCONNECT_EVENT_FLAG_FAST_REPEAT_TIMER = $00000001;
// set event repeat timer to simulate fast repeat
SIMCONNECT_EVENT_FLAG_SLOW_REPEAT_TIMER = $00000002;
// set event repeat timer to simulate slow repeat
SIMCONNECT_EVENT_FLAG_GROUPID_IS_PRIORITY = $00000010;
// interpret GroupID parameter as priority value
type
SIMCONNECT_DATA_REQUEST_FLAG = DWORD;
TSimConnectDataRequestFlag = SIMCONNECT_DATA_REQUEST_FLAG;
const
SIMCONNECT_DATA_REQUEST_FLAG_DEFAULT = $00000000;
SIMCONNECT_DATA_REQUEST_FLAG_CHANGED = $00000001;
// send requested data when value(s) change
SIMCONNECT_DATA_REQUEST_FLAG_TAGGED = $00000002;
// send requested data in tagged format
type
SIMCONNECT_DATA_SET_FLAG = DWORD;
TSimConnectDataSetFlag = SIMCONNECT_DATA_SET_FLAG;
const
SIMCONNECT_DATA_SET_FLAG_DEFAULT = $00000000; // data is in tagged format
SIMCONNECT_DATA_SET_FLAG_TAGGED = $00000001; // data is in tagged format
type
SIMCONNECT_CREATE_CLIENT_DATA_FLAG = DWORD;
TSimConnectCreateClientDataFlag = SIMCONNECT_CREATE_CLIENT_DATA_FLAG;
const
SIMCONNECT_CREATE_CLIENT_DATA_FLAG_DEFAULT = $00000000;
SIMCONNECT_CREATE_CLIENT_DATA_FLAG_READ_ONLY = $00000001;
// permit only ClientData creator to write into ClientData
// SP1A additions
type
SIMCONNECT_CLIENT_DATA_REQUEST_FLAG = DWORD;
TSimConnectClientDataRequestFlag = SIMCONNECT_CLIENT_DATA_REQUEST_FLAG;
const
SIMCONNECT_CLIENT_DATA_REQUEST_FLAG_DEFAULT = $00000000;
SIMCONNECT_CLIENT_DATA_REQUEST_FLAG_CHANGED = $00000001; // send requested ClientData when value(s) change
SIMCONNECT_CLIENT_DATA_REQUEST_FLAG_TAGGED = $00000002; // send requested ClientData in tagged format
type
SIMCONNECT_CLIENT_DATA_SET_FLAG = DWORD;
TSimConnectClientDataSetFlag = SIMCONNECT_CLIENT_DATA_SET_FLAG;
const
SIMCONNECT_CLIENT_DATA_SET_FLAG_DEFAULT = $00000000;
SIMCONNECT_CLIENT_DATA_SET_FLAG_TAGGED = $00000001; // data is in tagged format
// End of SP1A additions
type
SIMCONNECT_VIEW_SYSTEM_EVENT_DATA = DWORD;
TSimConnectViewSystemEventData = SIMCONNECT_VIEW_SYSTEM_EVENT_DATA;
const
SIMCONNECT_VIEW_SYSTEM_EVENT_DATA_COCKPIT_2D = $00000001;
// 2D Panels in cockpit view
SIMCONNECT_VIEW_SYSTEM_EVENT_DATA_COCKPIT_VIRTUAL = $00000002;
// Virtual (3D) panels in cockpit view
SIMCONNECT_VIEW_SYSTEM_EVENT_DATA_ORTHOGONAL = $00000004;
// Orthogonal (Map) view
type
SIMCONNECT_SOUND_SYSTEM_EVENT_DATA = DWORD;
TSimConnectSoundSystemEventData = SIMCONNECT_SOUND_SYSTEM_EVENT_DATA;
const
SIMCONNECT_SOUND_SYSTEM_EVENT_DATA_MASTER = $00000001; // Sound Master
//----------------------------------------------------------------------------
// User-defined enums
//----------------------------------------------------------------------------
type
SIMCONNECT_NOTIFICATION_GROUP_ID = DWORD;
SIMCONNECT_INPUT_GROUP_ID = DWORD;
SIMCONNECT_DATA_DEFINITION_ID = DWORD;
SIMCONNECT_DATA_REQUEST_ID = DWORD;
SIMCONNECT_CLIENT_EVENT_ID = DWORD;
SIMCONNECT_CLIENT_DATA_ID = DWORD;
SIMCONNECT_CLIENT_DATA_DEFINITION_ID = DWORD;
//----------------------------------------------------------------------------
// Structure Types
//----------------------------------------------------------------------------
type
PSIMCONNECT_RECV = ^SIMCONNECT_RECV;
SIMCONNECT_RECV = packed record
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
end;
TSimConnectRecv = SIMCONNECT_RECV;
PSimConnectRecv = PSIMCONNECT_RECV;
PSIMCONNECT_RECV_EXCEPTION = ^SIMCONNECT_RECV_EXCEPTION;
SIMCONNECT_RECV_EXCEPTION = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
dwException: DWORD;
dwSendID: DWORD;
dwIndex: DWORD;
end;
TSimConnectRecvException = SIMCONNECT_RECV_EXCEPTION;
PSimConnectRecvException = PSIMCONNECT_RECV_EXCEPTION;
PSIMCONNECT_RECV_OPEN = ^SIMCONNECT_RECV_OPEN;
SIMCONNECT_RECV_OPEN = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
szApplicationName: array[0..255] of Char;
dwApplicationVersionMajor: DWORD;
dwApplicationVersionMinor: DWORD;
dwApplicationBuildMajor: DWORD;
dwApplicationBuildMinor: DWORD;
dwSimConnectVersionMajor: DWORD;
dwSimConnectVersionMinor: DWORD;
dwSimConnectBuildMajor: DWORD;
dwSimConnectBuildMinor: DWORD;
dwReserved1: DWORD;
dwReserved2: DWORD;
end;
TSimConnectRecvOpen = SIMCONNECT_RECV_OPEN;
PSimConnectRecvOpen = PSIMCONNECT_RECV_OPEN;
PSIMCONNECT_RECV_QUIT = ^SIMCONNECT_RECV_QUIT;
SIMCONNECT_RECV_QUIT = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
end;
TSimConnectRecvQuit = SIMCONNECT_RECV_QUIT;
PSimConnectRecvQuit = PSIMCONNECT_RECV_QUIT;
PSIMCONNECT_RECV_EVENT = ^SIMCONNECT_RECV_EVENT;
SIMCONNECT_RECV_EVENT = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
uGroupID: DWORD;
uEventID: DWORD;
dwData: DWORD; // uEventID-dependent context
end;
TSimConnectRecvEvent = SIMCONNECT_RECV_EVENT;
PSimConnectRecvEvent = PSIMCONNECT_RECV_EVENT;
// when dwID == SIMCONNECT_RECV_ID_EVENT_FILENAME
PSIMCONNECT_RECV_EVENT_FILENAME = ^SIMCONNECT_RECV_EVENT_FILENAME;
SIMCONNECT_RECV_EVENT_FILENAME = packed record {SIMCONNECT_RECV_EVENT}
// "Inherits" SIMCONNECT_RECV_EVENT
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
uGroupID: DWORD;
uEventID: DWORD;
dwData: DWORD; // uEventID-dependent context
// End of Inherit
szFileName: array[0..256 - 1] of Char; // uEventID-dependent context
dwFlags: DWORD;
end;
TSimConnectRecvEventFileName = SIMCONNECT_RECV_EVENT_FILENAME;
PSimConnectRecvEventFileName = PSIMCONNECT_RECV_EVENT_FILENAME;
PSIMCONNECT_RECV_EVENT_OBJECT_ADDREMOVE =
^SIMCONNECT_RECV_EVENT_OBJECT_ADDREMOVE;
SIMCONNECT_RECV_EVENT_OBJECT_ADDREMOVE = packed record {SIMCONNECT_RECV_EVENT}
// "Inherits" SIMCONNECT_RECV_EVENT
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
uGroupID: DWORD;
uEventID: DWORD;
dwData: DWORD; // uEventID-dependent context
// End of Inherit
eObjType: TSimConnectSimObjectType;
end;
TSimConnectRecvEventObjectAddRemove = SIMCONNECT_RECV_EVENT_OBJECT_ADDREMOVE;
PSimConnectRecvEventObjectAddRemove = PSIMCONNECT_RECV_EVENT_OBJECT_ADDREMOVE;
// when dwID == SIMCONNECT_RECV_ID_EVENT_FRAME
PSIMCONNECT_RECV_EVENT_FRAME = ^SIMCONNECT_RECV_EVENT_FRAME;
SIMCONNECT_RECV_EVENT_FRAME = packed record {SIMCONNECT_RECV_EVENT}
// "Inherits" SIMCONNECT_RECV_EVENT
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
uGroupID: DWORD;
uEventID: DWORD;
dwData: DWORD; // uEventID-dependent context
// End of Inherit
FrameRate: single;
fSimSpeed: single;
end;
TSimConnectRecvEventFrame = SIMCONNECT_RECV_EVENT_FRAME;
PSimConnectRecvEventFrame = PSIMCONNECT_RECV_EVENT_FRAME;
PSIMCONNECT_RECV_SIMOBJECT_DATA = ^SIMCONNECT_RECV_SIMOBJECT_DATA;
SIMCONNECT_RECV_SIMOBJECT_DATA = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
dwRequestID: DWORD;
dwObjectID: DWORD;
dwDefineID: DWORD;
dwFlags: DWORD; // SIMCONNECT_DATA_REQUEST_FLAG
dwentrynumber: DWORD;
// if multiple objects returned, this is number <entrynumber> out of <outof>.
dwoutof: DWORD; // note: starts with 1, not 0.
dwDefineCount: DWORD; // data count (number of datums, *not* byte count)
dwData: DWORD; // data begins here, dwDefineCount data items
end;
TSimConnectRecvSimObjectData = SIMCONNECT_RECV_SIMOBJECT_DATA;
PSimConnectRecvSimObjectData = PSIMCONNECT_RECV_SIMOBJECT_DATA;
// when dwID == SIMCONNECT_RECV_ID_SIMOBJECT_DATA_BYType
PSIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE =
^SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE;
SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
dwRequestID: DWORD;
dwObjectID: DWORD;
dwDefineID: DWORD;
dwFlags: DWORD; // SIMCONNECT_DATA_REQUEST_FLAG
dwentrynumber: DWORD;
// if multiple objects returned, this is number <entrynumber> out of <outof>.
dwoutof: DWORD; // note: starts with 1, not 0.
dwDefineCount: DWORD; // data count (number of datums, *not* byte count)
dwData: DWORD; // data begins here, dwDefineCount data items
end;
TSimConnectRecvSimObjectDataByType = SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE;
PSimConnectRecvSimObjectDataByType = PSIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE;
// when dwID == SIMCONNECT_RECV_ID_CLIENT_DATA
PSIMCONNECT_RECV_CLIENT_DATA = ^SIMCONNECT_RECV_CLIENT_DATA;
SIMCONNECT_RECV_CLIENT_DATA = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
dwRequestID: DWORD;
dwObjectID: DWORD;
dwDefineID: DWORD;
dwFlags: DWORD; // SIMCONNECT_DATA_REQUEST_FLAG
dwentrynumber: DWORD;
// if multiple objects returned, this is number <entrynumber> out of <outof>.
dwoutof: DWORD; // note: starts with 1, not 0.
dwDefineCount: DWORD; // data count (number of datums, *not* byte count)
dwData: DWORD; // data begins here, dwDefineCount data items
end;
TSimConnectRecvClientData = SIMCONNECT_RECV_CLIENT_DATA;
PSimConnectRecvClientData = PSIMCONNECT_RECV_CLIENT_DATA;
// when dwID == SIMCONNECT_RECV_ID_WEATHER_OBSERVATION
PSIMCONNECT_RECV_WEATHER_OBSERVATION = ^SIMCONNECT_RECV_WEATHER_OBSERVATION;
SIMCONNECT_RECV_WEATHER_OBSERVATION = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
dwRequestID: DWORD;
szMetar: array[0..0] of Char;
// Variable length String whose maximum size is MAX_METAR_LENGTH
end;
TSimConnectRecvWeatherObservation = SIMCONNECT_RECV_WEATHER_OBSERVATION;
PSimConnectRecvWeatherObservation = PSIMCONNECT_RECV_WEATHER_OBSERVATION;
// when dwID == SIMCONNECT_RECV_ID_CLOUD_STATE
PSIMCONNECT_RECV_CLOUD_STATE = ^SIMCONNECT_RECV_CLOUD_STATE;
SIMCONNECT_RECV_CLOUD_STATE = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
dwRequestID: DWORD;
dwArraySize: DWORD;
rgbData: array[0..0] of byte;
end;
TSimConnectRecvCloudState = SIMCONNECT_RECV_CLOUD_STATE;
PSimConnectRecvCloudState = PSIMCONNECT_RECV_CLOUD_STATE;
// when dwID == SIMCONNECT_RECV_ID_ASSIGNED_OBJECT_ID
PSIMCONNECT_RECV_ASSIGNED_OBJECT_ID = ^SIMCONNECT_RECV_ASSIGNED_OBJECT_ID;
SIMCONNECT_RECV_ASSIGNED_OBJECT_ID = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
dwRequestID: DWORD;
dwObjectID: DWORD;
end;
TSimConnectRecvAssignedObjectId = SIMCONNECT_RECV_ASSIGNED_OBJECT_ID;
PSimConnectRecvAssignedObjectId = PSIMCONNECT_RECV_ASSIGNED_OBJECT_ID;
// when dwID == SIMCONNECT_RECV_ID_RESERVED_KEY
PSIMCONNECT_RECV_RESERVED_KEY = ^SIMCONNECT_RECV_RESERVED_KEY;
SIMCONNECT_RECV_RESERVED_KEY = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
szChoiceReserved: array[0..29] of Char;
szReservedKey: array[0..49] of Char;
end;
TSimConnectRecvReservedKey = SIMCONNECT_RECV_RESERVED_KEY;
PSimConnectRecvReservedKey = PSIMCONNECT_RECV_RESERVED_KEY;
// when dwID == SIMCONNECT_RECV_ID_SYSTEM_STATE
PSIMCONNECT_RECV_SYSTEM_STATE = ^SIMCONNECT_RECV_SYSTEM_STATE;
SIMCONNECT_RECV_SYSTEM_STATE = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
dwRequestID: DWORD;
dwInteger: DWORD;
fFloat: single;
szString: array[0..255] of Char;
end;
TSimConnectRecvSystemState = SIMCONNECT_RECV_SYSTEM_STATE;
PSimConnectRecvSystemState = PSIMCONNECT_RECV_SYSTEM_STATE;
PSIMCONNECT_RECV_CUSTOM_ACTION = ^SIMCONNECT_RECV_CUSTOM_ACTION;
SIMCONNECT_RECV_CUSTOM_ACTION = packed record {SIMCONNECT_RECV_EVENT}
// "Inherits" SIMCONNECT_RECV_EVENT
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
uGroupID: DWORD;
uEventID: DWORD;
dwData: DWORD; // uEventID-dependent context
// End of Inherit
guidInstanceId: TGUID; // Instance id of the action that executed
dwWaitForCompletion: DWORD; // Wait for completion flag on the action
szPayLoad: array[0..0] of Char;
// Variable length String payload associated with the mission action.
end;
TSimConnectRecvCustomAction = SIMCONNECT_RECV_CUSTOM_ACTION;
PSimConnectRecvCustomAction = PSIMCONNECT_RECV_CUSTOM_ACTION;
// SP1A additions
PSIMCONNECT_RECV_EVENT_WEATHER_MODE = ^SIMCONNECT_RECV_EVENT_WEATHER_MODE;
SIMCONNECT_RECV_EVENT_WEATHER_MODE = packed record {SIMCONNECT_RECV_EVENT}
// "Inherits" SIMCONNECT_RECV_EVENT
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
uGroupID: DWORD;
uEventID: DWORD;
dwData: DWORD; // uEventID-dependent context
// End of Inherit
// No event specific data - the new weather mode is in the base structure dwData member.
end;
TSimConnectRecvEventWeatherMode = SIMCONNECT_RECV_EVENT_WEATHER_MODE;
PSimConnectRecvEventWeatherMode = PSIMCONNECT_RECV_EVENT_WEATHER_MODE;
// SIMCONNECT_RECV_FACILITIES_LIST
PSIMCONNECT_RECV_FACILITIES_LIST = ^SIMCONNECT_RECV_FACILITIES_LIST;
SIMCONNECT_RECV_FACILITIES_LIST = packed record {SIMCONNECT_RECV}
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of Inherit
dwRequestID: DWORD;
dwArraySize: DWORD;
dwEntryNumber: DWORD; // when the array of items is too big for one send, which send this is (0..dwOutOf-1)
dwOutOf: DWORD; // total number of transmissions the list is chopped into
end;
TSimConnectRecvFaciltiesList = SIMCONNECT_RECV_FACILITIES_LIST;
PSimConnectRecvFaciltiesList = PSIMCONNECT_RECV_FACILITIES_LIST;
// SIMCONNECT_DATA_FACILITY_AIRPORT
PSIMCONNECT_DATA_FACILITY_AIRPORT = ^SIMCONNECT_DATA_FACILITY_AIRPORT;
SIMCONNECT_DATA_FACILITY_AIRPORT = packed record
Icao: array[0..8] of char; // ICAO of the object
Latitude: double; // degrees
Longitude: double; // degrees
Altitude: double; // meters
end;
TSimConnectDataFacilityAirport = SIMCONNECT_DATA_FACILITY_AIRPORT;
PSimConnectDataFacilityAirport = PSIMCONNECT_DATA_FACILITY_AIRPORT;
// SIMCONNECT_RECV_AIRPORT_LIST
PSIMCONNECT_RECV_AIRPORT_LIST = ^SIMCONNECT_RECV_AIRPORT_LIST;
SIMCONNECT_RECV_AIRPORT_LIST = packed record {SIMCONNECT_RECV_FACILITIES_LIST}
// "Inherits" SIMCONNECT_RECV_FACILITIES_LIST
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of nested Inherit
dwRequestID: DWORD;
dwArraySize: DWORD;
dwEntryNumber: DWORD; // when the array of items is too big for one send, which send this is (0..dwOutOf-1)
dwOutOf: DWORD; // total number of transmissions the list is chopped into
// End of Inherit
rgData: array[0..0] of SIMCONNECT_DATA_FACILITY_AIRPORT;
end;
TSimConnectRecvAirportsList = SIMCONNECT_RECV_AIRPORT_LIST;
PSimConnectRecvAirportsList = PSIMCONNECT_RECV_AIRPORT_LIST;
// SIMCONNECT_DATA_FACILITY_WAYPOINT
PSIMCONNECT_DATA_FACILITY_WAYPOINT = ^SIMCONNECT_DATA_FACILITY_WAYPOINT;
SIMCONNECT_DATA_FACILITY_WAYPOINT = packed record {SIMCONNECT_DATA_FACILITY_AIRPORT}
// "inherits" SIMCONNECT_DATA_FACILITY_AIRPORT
Icao: array[0..8] of char; // ICAO of the object
Latitude: double; // degrees
Longitude: double; // degrees
Altitude: double; // meters
// End of Inherit
fMagVar: single; // Magvar in degrees
end;
TSimConnectDataFacilityWaypoint = SIMCONNECT_DATA_FACILITY_WAYPOINT;
PSimConnectDataFacilityWaypoint = PSIMCONNECT_DATA_FACILITY_WAYPOINT;
// SIMCONNECT_RECV_WAYPOINT_LIST
PSIMCONNECT_RECV_WAYPOINT_LIST = ^SIMCONNECT_RECV_WAYPOINT_LIST;
SIMCONNECT_RECV_WAYPOINT_LIST = packed record {SIMCONNECT_RECV_FACILITIES_LIST}
// "Inherits" SIMCONNECT_RECV_FACILITIES_LIST
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of nested Inherit
dwRequestID: DWORD;
dwArraySize: DWORD;
dwEntryNumber: DWORD; // when the array of items is too big for one send, which send this is (0..dwOutOf-1)
dwOutOf: DWORD; // total number of transmissions the list is chopped into
// End of Inherit
rgData: array[0..0] of SIMCONNECT_DATA_FACILITY_WAYPOINT;
end;
TSimConnectRecvWaypointList = SIMCONNECT_RECV_WAYPOINT_LIST;
PSimConnectRecvWaypointList = PSIMCONNECT_RECV_WAYPOINT_LIST;
// SIMCONNECT_DATA_FACILITY_NDB
PSIMCONNECT_DATA_FACILITY_NDB = ^SIMCONNECT_DATA_FACILITY_NDB;
SIMCONNECT_DATA_FACILITY_NDB = packed record {SIMCONNECT_DATA_FACILITY_WAYPOINT}
// "Inherits" SIMCONNECT_DATA_FACILITY_WAYPOINT
// "Inherits" SIMCONNECT_DATA_FACILITY_AIRPORT
Icao: array[0..8] of char; // ICAO of the object
Latitude: double; // degrees
Longitude: double; // degrees
Altitude: double; // meters
// End of Nested Inherit
fMagVar: single; // Magvar in degrees
// End of Inherit
fFrequency: DWORD; // frequency in Hz
end;
TSimConnectDataFacilityNdb = SIMCONNECT_DATA_FACILITY_NDB;
PSimConnectDataFacilityNdb = PSIMCONNECT_DATA_FACILITY_NDB;
// SIMCONNECT_RECV_NDB_LIST
PSIMCONNECT_RECV_NDB_LIST = ^SIMCONNECT_RECV_NDB_LIST;
SIMCONNECT_RECV_NDB_LIST = packed record {SIMCONNECT_RECV_FACILITIES_LIST}
// "Inherits" SIMCONNECT_RECV_FACILITIES_LIST
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of nested Inherit
dwRequestID: DWORD;
dwArraySize: DWORD;
dwEntryNumber: DWORD; // when the array of items is too big for one send, which send this is (0..dwOutOf-1)
dwOutOf: DWORD; // total number of transmissions the list is chopped into
// End of Inherit
rgData: array[0..0] of SIMCONNECT_DATA_FACILITY_NDB;
end;
TSimConnectRecvNdbList = SIMCONNECT_RECV_NDB_LIST;
PSimConnectRecvNdbList = PSIMCONNECT_RECV_NDB_LIST;
// SIMCONNECT_DATA_FACILITY_VOR
PSIMCONNECT_DATA_FACILITY_VOR = ^SIMCONNECT_DATA_FACILITY_VOR;
SIMCONNECT_DATA_FACILITY_VOR = packed record {SIMCONNECT_DATA_FACILITY_NDB}
// "Inherits" SIMCONNECT_DATA_FACILITY_NDB
// "Inherits" SIMCONNECT_DATA_FACILITY_WAYPOINT
// "Inherits" SIMCONNECT_DATA_FACILITY_AIRPORT
Icao: array[0..8] of char; // ICAO of the object
Latitude: double; // degrees
Longitude: double; // degrees
Altitude: double; // meters
// End of Nested Inherit
fMagVar: single; // Magvar in degrees
// End of Nested Inherit
fFrequency: DWORD; // frequency in Hz
// End of Inherit
Flags: DWORD; // SIMCONNECT_VOR_FLAGS
fLocalizer: single; // Localizer in degrees
GlideLat: double; // Glide Slope Location (deg, deg, meters)
GlideLon: double;
GlideAlt: double;
fGlideSlopeAngle: single; // Glide Slope in degrees
end;
TSimConnectDataFacilityVor = SIMCONNECT_DATA_FACILITY_VOR;
PSimConnectDataFacilityVor = PSIMCONNECT_DATA_FACILITY_VOR;
// SIMCONNECT_RECV_VOR_LIST
PSIMCONNECT_RECV_VOR_LIST = ^SIMCONNECT_RECV_VOR_LIST;
SIMCONNECT_RECV_VOR_LIST = packed record {SIMCONNECT_RECV_FACILITIES_LIST}
// "Inherits" SIMCONNECT_RECV_FACILITIES_LIST
// "Inherits" SIMCONNECT_RECV
dwSize: DWORD;
dwVersion: DWORD;
dwID: DWORD;
// End of nested Inherit
dwRequestID: DWORD;
dwArraySize: DWORD;
dwEntryNumber: DWORD; // when the array of items is too big for one send, which send this is (0..dwOutOf-1)
dwOutOf: DWORD; // total number of transmissions the list is chopped into
// End of Inherit
rgData: array[0..0] of SIMCONNECT_DATA_FACILITY_VOR;
end;
TSimConnectRecvVorList = SIMCONNECT_RECV_VOR_LIST;
PSimConnectRecvVorList = PSIMCONNECT_RECV_VOR_LIST;
// End of SP1A additions
// SIMCONNECT_DATAType_INITPOSITION
PSIMCONNECT_DATA_INITPOSITION = ^SIMCONNECT_DATA_INITPOSITION;
SIMCONNECT_DATA_INITPOSITION = packed record
Latitude: double; // degrees
Longitude: double; // degrees
Altitude: double; // feet
Pitch: double; // degrees
Bank: double; // degrees
Heading: double; // degrees
OnGround: DWORD; // 1=force to be on the ground
Airspeed: DWORD; // knots
end;
TSimConnectDataInitPosition = SIMCONNECT_DATA_INITPOSITION;
PSimConnectDataInitPosition = PSIMCONNECT_DATA_INITPOSITION;
// SIMCONNECT_DATAType_MARKERSTATE
SIMCONNECT_DATA_MARKERSTATE = packed record
szMarkerName: array[0..63] of Char;
dwMarkerState: DWORD;
end;
TSimConnectDataMarkerState = SIMCONNECT_DATA_MARKERSTATE;
// SIMCONNECT_DATAType_WAYPOINT
SIMCONNECT_DATA_WAYPOINT = packed record
Latitude: double;
Longitude: double;
Altitude: double;
Flags: LongInt;
ktsSpeed: double;
percentThrottle: double;
end;
TSimConnectDataWaypoint = SIMCONNECT_DATA_WAYPOINT;
// SIMCONNECT_DATA_LATLONALT
SIMCONNECT_DATA_LATLONALT = packed record
Latitude: double;
Longitude: double;
Altitude: double;
end;
TSimConnectDataLatLonAlt = SIMCONNECT_DATA_LATLONALT;
// SIMCONNECT_DATA_XYZ
SIMCONNECT_DATA_XYZ = packed record
x: double;
y: double;
z: double;
end;
TSimConnectDataXYZ = SIMCONNECT_DATA_XYZ;
// A procedure to pass to CallDispatch (SDK standard method)
TDispatchProc = procedure(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer); stdcall;
// A method to pass to CallDispatch (allows direct link to method of form
// Note that overloading causes a compiler error, so this version is
// used in CallDispatchMethod (which calls the same DLL entry)
TDispatchMethod = procedure(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer) of object; stdcall;
//----------------------------------------------------------------------------
// Function Declarations
//----------------------------------------------------------------------------
function SimConnect_AddToDataDefinition(
hSimConnect: THandle;
DefineID: SIMCONNECT_DATA_DEFINITION_ID;
DatumName: string;
UnitsName: string;
DatumType: SIMCONNECT_DATAType = SIMCONNECT_DATAType_FLOAT64;
fEpsilon: Single = 0;
DatumID: DWORD = SIMCONNECT_UNUSED
): HRESULT; StdCall;
function SimConnect_Close(
hSimConnect: THandle
): HRESULT; StdCall;
function SimConnect_FlightLoad(
hSimConnect: THandle;
const szFileName: PChar
): HRESULT; StdCall;
function SimConnect_FlightSave(
hSimConnect: THandle;
const szFileName: PChar;
const szDescription: PChar;
Flags: DWORD
): HRESULT; StdCall;
function SimConnect_GetNextDispatch(
hSimConnect: THandle;
var ppData: PSimConnectRecv;
var pcbData: DWORD
): HRESULT; StdCall;
function SimConnect_Open(
var phSimConnect: THandle;
szName: PChar;
hWnd: HWnd;
UserEventWin32: DWORD;
hEventHandle: THandle;
ConfigIndex: DWORD
): HRESULT; StdCall;
function SimConnect_RequestDataOnSimObject(
hSimConnect: THandle;
RequestID: SIMCONNECT_DATA_REQUEST_ID;
DefineID: SIMCONNECT_DATA_DEFINITION_ID;
ObjectID: SIMCONNECT_OBJECT_ID;
Period: SIMCONNECT_PERIOD;
Flags: SIMCONNECT_DATA_REQUEST_FLAG = 0;
origin: DWORD = 0;
interval: DWORD = 0;
limit: DWORD = 0
): HRESULT; StdCall;
function SimConnect_CallDispatch(
hSimConnect: THandle;
pfcnDispatch: TDispatchProc;
pContext: Pointer
): HRESULT; StdCall;
function SimConnect_CallDispatchMethod(
hSimConnect: THandle;
pfcnDispatch: TDispatchMethod;
pContext: Pointer
): HRESULT; StdCall;
function SimConnect_RequestDataOnSimObjectType(
hSimConnect: THandle;
RequestID: SIMCONNECT_DATA_REQUEST_ID;
DefineID: SIMCONNECT_DATA_DEFINITION_ID;
dwRadiusMeters: DWORD;
ObjectType: SIMCONNECT_SIMOBJECT_Type
): HRESULT; StdCall;
function SimConnect_SetInputGroupState(
hSimConnect: THandle;
GroupID: SIMCONNECT_INPUT_GROUP_ID;
dwState: DWORD
): HRESULT; StdCall;
function SimConnect_SetDataOnSimObject(
hSimConnect: THandle;
DefineID: SIMCONNECT_DATA_DEFINITION_ID;
ObjectID: SIMCONNECT_OBJECT_ID;
Flags: SIMCONNECT_DATA_SET_FLAG;
ArrayCount: DWORD;
cbUnitSize: DWORD;
pDataSet: Pointer
): HRESULT; StdCall;
function SimConnect_MapClientEventToSimEvent(
hSimConnect: THandle;
EventID: SIMCONNECT_CLIENT_EVENT_ID;
EventName: string = ''
): HRESULT; StdCall;
function SimConnect_MapInputEventToClientEvent(
hSimConnect: THandle;
GroupID: SIMCONNECT_INPUT_GROUP_ID;
const szInputDefinition: PChar;
DownEventID: SIMCONNECT_CLIENT_EVENT_ID;
DownValue: DWORD = 0;
UpEventID: SIMCONNECT_CLIENT_EVENT_ID = Ord(SIMCONNECT_UNUSED);
UpValue: DWORD = 0;
bMaskable: BOOL = False
): HRESULT; StdCall;
function SimConnect_AddClientEventToNotificationGroup(
hSimConnect: THandle;
GroupID: SIMCONNECT_NOTIFICATION_GROUP_ID;
EventID: SIMCONNECT_CLIENT_EVENT_ID;
bMaskable: BOOL = False
): HRESULT; StdCall;
function SimConnect_SetNotificationGroupPriority(
hSimConnect: THandle;
GroupID: SIMCONNECT_NOTIFICATION_GROUP_ID;
uPriority: Cardinal
): HRESULT; StdCall;
function SimConnect_RetrieveString(
pData: PSimConnectRecv;
cbData: Cardinal;
pStringV: PChar;
var pszString: PChar;
var pcbString: Cardinal
): HRESULT; StdCall;
function SimConnect_CameraSetRelative6DOF(
hSimConnect: THandle;
fDeltaX: Single;
fDeltaY: Single;
fDeltaZ: Single;
fPitchDeg: Single;
fBankDeg: Single;
fHeadingDeg: Single
): HRESULT; StdCall;
function SimConnect_SetInputGroupPriority(
hSimConnect: THandle;
GroupID: SIMCONNECT_INPUT_GROUP_ID;
uPriority: Cardinal
): HRESULT; StdCall;
function SimConnect_RemoveClientEvent(
hSimConnect: THandle;
GroupID: SIMCONNECT_NOTIFICATION_GROUP_ID;
EventID: SIMCONNECT_CLIENT_EVENT_ID
): HRESULT; StdCall;
function SimConnect_MenuDeleteItem(
hSimConnect: THandle;
MenuEventID: SIMCONNECT_CLIENT_EVENT_ID
): HRESULT; StdCall;
function SimConnect_MenuAddItem(
hSimConnect: THandle;
const szMenuItem: PChar;
MenuEventID: SIMCONNECT_CLIENT_EVENT_ID;
dwData: Cardinal
): HRESULT; StdCall;
function SimConnect_RequestReservedKey(
hSimConnect: THandle;
EventID: SIMCONNECT_CLIENT_EVENT_ID;
szKeyChoice1: string;
szKeyChoice2: string;
szKeyChoice3: string
): HRESULT; StdCall;
function SimConnect_TransmitClientEvent(
hSimConnect: THandle;
ObjectID: SIMCONNECT_OBJECT_ID;
EventID: SIMCONNECT_CLIENT_EVENT_ID;
dwData: Cardinal;
GroupID: SIMCONNECT_NOTIFICATION_GROUP_ID;
Flags: SIMCONNECT_EVENT_FLAG
): HRESULT; StdCall;
function SimConnect_WeatherRequestObservationAtNearestStation(
hSimConnect: THandle;
RequestID: SIMCONNECT_DATA_REQUEST_ID;
lat: Single;
lon: Single
): HRESULT; StdCall;
function SimConnect_WeatherRequestObservationAtStation(
hSimConnect: THandle;
RequestID: SIMCONNECT_DATA_REQUEST_ID;
const szICAO: PChar
): HRESULT; StdCall;
function SimConnect_AICreateSimulatedObject(
hSimConnect: THandle;
const szContainerTitle: PChar;
InitPos: SIMCONNECT_DATA_INITPOSITION;
RequestID: SIMCONNECT_DATA_REQUEST_ID
): HRESULT; StdCall;
function SimConnect_AICreateNonATCAircraft(
hSimConnect: THandle;
const szContainerTitle: PChar;
const szTailNumber: PChar;
InitPos: SIMCONNECT_DATA_INITPOSITION;
RequestID: SIMCONNECT_DATA_REQUEST_ID
): HRESULT; StdCall;
function SimConnect_AISetAircraftFlightPlan(
hSimConnect: THandle;
ObjectID: SIMCONNECT_OBJECT_ID;
const szFlightPlanPath: PChar;
RequestID: SIMCONNECT_DATA_REQUEST_ID
): HRESULT; StdCall;
function SimConnect_AICreateParkedATCAircraft(
hSimConnect: THandle;
const szContainerTitle: PChar;
const szTailNumber: PChar;
const szAirportID: PChar;
RequestID: SIMCONNECT_DATA_REQUEST_ID
): HRESULT; StdCall;
function SimConnect_SubscribeToSystemEvent(
hSimConnect: THandle;
EventID: SIMCONNECT_CLIENT_EVENT_ID;
const SystemEventName: PChar
): HRESULT; StdCall;
function SimConnect_AICreateEnrouteATCAircraft(
hSimConnect: THandle;
const szContainerTitle: PChar;
const szTailNumber: PChar;
iFlightNumber: Integer;
const szFlightPlanPath: PChar;
dFlightPlanPosition: Double;
bTouchAndGo: Bool;
RequestID: SIMCONNECT_DATA_REQUEST_ID
): HRESULT; StdCall;
function SimConnect_RequestSystemState(
hSimConnect: THandle;
RequestID: SIMCONNECT_DATA_REQUEST_ID;
const szState: PChar
): HRESULT; StdCall;
function SimConnect_SetSystemState(
hSimConnect: THandle;
const szState: PChar;
dwInteger: Cardinal;
fFloat: Single;
const szString: PChar
): HRESULT; StdCall;
function SimConnect_GetLastSentPacketID(
hSimConnect: THandle;
var pdwSendID: Cardinal
): HRESULT; StdCall;
function SimConnect_MenuAddSubItem(
hSimConnect: THandle;
MenuEventID: SIMCONNECT_CLIENT_EVENT_ID;
const szMenuItem: PChar;
SubMenuEventID: SIMCONNECT_CLIENT_EVENT_ID;
dwData: Cardinal
): HRESULT; StdCall;
function SimConnect_MenuDeleteSubItem(
hSimConnect: THandle;
MenuEventID: SIMCONNECT_CLIENT_EVENT_ID;
const SubMenuEventID: SIMCONNECT_CLIENT_EVENT_ID
): HRESULT; StdCall;
function SimConnect_RequestResponseTimes(
hSimConnect: THandle;
nCount: Cardinal;
var fElapsedSeconds: Single
): HRESULT; StdCall;
function SimConnect_FlightPlanLoad(
hSimConnect: THandle;
const szFileName: PChar
): HRESULT; StdCall;
// BEWARE!!!!!
// Unlike the C version these must not pass the GUID as a "const"
// In Delphi that results in passing a pointer, not a value, and it will fail
function SimConnect_ExecuteMissionAction(
hSimConnect: THandle;
guidInstanceId: TGUID
): HRESULT; StdCall;
function SimConnect_CompleteCustomMissionAction(
hSimConnect: THandle;
guidInstanceId: TGUID
): HRESULT; StdCall;
//-------------------------
// Not checked
//-------------------------
function SimConnect_SetSystemEventState(
hSimConnect: THandle;
EventID: SIMCONNECT_CLIENT_EVENT_ID;
dwState: SIMCONNECT_STATE
): HRESULT; StdCall;
function SimConnect_ClearNotificationGroup(
hSimConnect: THandle;
GroupID: SIMCONNECT_NOTIFICATION_GROUP_ID
): HRESULT; StdCall;
function SimConnect_RequestNotificationGroup(
hSimConnect: THandle;
GroupID: SIMCONNECT_NOTIFICATION_GROUP_ID;
dwReserved: Cardinal;
Flags: Cardinal
): HRESULT; StdCall;
function SimConnect_ClearDataDefinition(
hSimConnect: THandle;
DefineID: SIMCONNECT_DATA_DEFINITION_ID
): HRESULT; StdCall;
function SimConnect_RemoveInputEvent(
hSimConnect: THandle;
GroupID: SIMCONNECT_INPUT_GROUP_ID;
const szInputDefinition: PChar
): HRESULT; StdCall;
function SimConnect_ClearInputGroup(
hSimConnect: THandle;
GroupID: SIMCONNECT_INPUT_GROUP_ID
): HRESULT; StdCall;
function SimConnect_UnsubscribeFromSystemEvent(
hSimConnect: THandle;
EventID: SIMCONNECT_CLIENT_EVENT_ID
): HRESULT; StdCall;
function SimConnect_WeatherRequestInterpolatedObservation(
hSimConnect: THandle;
RequestID: SIMCONNECT_DATA_REQUEST_ID;
lat: Single;
lon: Single;
alt: Single
): HRESULT; StdCall;
function SimConnect_WeatherCreateStation(
hSimConnect: THandle;
RequestID: SIMCONNECT_DATA_REQUEST_ID;
const szICAO: PChar;
const szName: PChar;
lat: Single;
lon: Single;
alt: Single
): HRESULT; StdCall;
function SimConnect_WeatherRemoveStation(
hSimConnect: THandle;
RequestID: SIMCONNECT_DATA_REQUEST_ID;
const szICAO: PChar
): HRESULT; StdCall;
function SimConnect_WeatherSetObservation(
hSimConnect: THandle;
Seconds: Cardinal;
const szMETAR: PChar
): HRESULT; StdCall;
function SimConnect_WeatherSetModeServer(
hSimConnect: THandle;
dwPort: Cardinal;
dwSeconds: Cardinal
): HRESULT; StdCall;
function SimConnect_WeatherSetModeTheme(
hSimConnect: THandle;
const szThemeName: PChar
): HRESULT; StdCall;
function SimConnect_WeatherSetModeGlobal(
hSimConnect: THandle
): HRESULT; StdCall;
function SimConnect_WeatherSetModeCustom(
hSimConnect: THandle
): HRESULT; StdCall;
function SimConnect_WeatherSetDynamicUpdateRate(
hSimConnect: THandle;
dwRate: Cardinal
): HRESULT; StdCall;
function SimConnect_WeatherRequestCloudState(
hSimConnect: THandle;
RequestID: SIMCONNECT_DATA_REQUEST_ID;
minLat: Single;
minLon: Single;
minAlt: Single;
maxLat: Single;
maxLon: Single;
maxAlt: Single;
dwFlags: LongInt
): HRESULT; StdCall;
function SimConnect_WeatherCreateThermal(
hSimConnect: THandle;
RequestID: SIMCONNECT_DATA_REQUEST_ID;
lat: Single;
lon: Single;
alt: Single;
radius: Single;
height: Single;
coreRate: Single;
coreTurbulence: Single;
sinkRate: Single;
sinkTurbulence: Single;
coreSize: Single;
coreTransitionSize: Single;
sinkLayerSize: Single;
sinkTransitionSize: Single
): HRESULT; StdCall;
function SimConnect_WeatherRemoveThermal(
hSimConnect: THandle;
ObjectID: SIMCONNECT_OBJECT_ID
): HRESULT; StdCall;
function SimConnect_AIReleaseControl(
hSimConnect: THandle;
ObjectID: SIMCONNECT_OBJECT_ID;
RequestID: SIMCONNECT_DATA_REQUEST_ID
): HRESULT; StdCall;
function SimConnect_AIRemoveObject(
hSimConnect: THandle;
ObjectID: SIMCONNECT_OBJECT_ID;
RequestID: SIMCONNECT_DATA_REQUEST_ID
): HRESULT; StdCall;
function SimConnect_InsertString(
pDest: PChar;
cbDest: Cardinal;
var ppEnd: Pointer;
var pcbStringV: Cardinal;
const pSource: PChar
): HRESULT; StdCall;
function SimConnect_MapClientDataNameToID(
hSimConnect: THandle;
const szClientDataName: PChar;
ClientDataID: SIMCONNECT_CLIENT_DATA_ID
): HRESULT; StdCall;
function SimConnect_CreateClientData(
hSimConnect: THandle;
ClientDataID: SIMCONNECT_CLIENT_DATA_ID;
dwSize: Cardinal;
Flags: SIMCONNECT_CREATE_CLIENT_DATA_FLAG
): HRESULT; StdCall;
// Modified for SP1A
function SimConnect_AddToClientDataDefinition(
hSimConnect: THandle;
DefineID: SIMCONNECT_CLIENT_DATA_DEFINITION_ID;
dwOffset: Cardinal;
dwSizeOrType: Cardinal;
fEpsilon : single = 0;
DatumID: DWORD = SIMCONNECT_UNUSED
): HRESULT; StdCall;
function SimConnect_ClearClientDataDefinition(
hSimConnect: THandle;
DefineID: SIMCONNECT_CLIENT_DATA_DEFINITION_ID
): HRESULT; StdCall;
function SimConnect_RequestClientData(
hSimConnect: THandle;
ClientDataID: SIMCONNECT_CLIENT_DATA_ID;
RequestID: SIMCONNECT_DATA_REQUEST_ID;
DefineID: SIMCONNECT_CLIENT_DATA_DEFINITION_ID;
Period : SIMCONNECT_CLIENT_DATA_PERIOD = SIMCONNECT_CLIENT_DATA_PERIOD_ONCE;
Flags : SIMCONNECT_CLIENT_DATA_REQUEST_FLAG = 0;
origin : DWORD= 0;
interval : DWORD= 0;
limit : DWORD= 0
): HRESULT; StdCall;
function SimConnect_SetClientData(
hSimConnect: THandle;
ClientDataID: SIMCONNECT_CLIENT_DATA_ID;
DefineID: SIMCONNECT_CLIENT_DATA_DEFINITION_ID;
dwReserved: Cardinal;
cbUnitSize: Cardinal;
pDataSet: Pointer
): HRESULT; StdCall;
// SP1A Additions
function SimConnect_Text(
hSimConnect: THandle;
TextType: TSimConnectTextType;
fTimeSeconds: single;
EventID: SIMCONNECT_CLIENT_EVENT_ID;
cbUnitSize: DWORD;
pDataSet: Pointer
): HRESULT; StdCall;
function SimConnect_SubscribeToFacilities(
hSimConnect: THandle;
ListType: SIMCONNECT_FACILITY_LIST_TYPE;
RequestID: SIMCONNECT_DATA_REQUEST_ID
): HRESULT; StdCall;
function SimConnect_UnsubscribeToFacilities(
hSimConnect: THandle;
ListType: SIMCONNECT_FACILITY_LIST_TYPE
): HRESULT; StdCall;
function SimConnect_RequestFacilitiesList(
hSimConnect: THandle;
ListType: SIMCONNECT_FACILITY_LIST_TYPE;
RequestID: SIMCONNECT_DATA_REQUEST_ID
): HRESULT; StdCall;
// End of SP1A Additions
implementation
function SimConnect_MapClientEventToSimEvent; external 'SIMCONNECT.DLL';
function SimConnect_TransmitClientEvent; external 'SIMCONNECT.DLL';
function SimConnect_SetSystemEventState; external 'SIMCONNECT.DLL';
function SimConnect_AddClientEventToNotificationGroup; external
'SIMCONNECT.DLL';
function SimConnect_RemoveClientEvent; external 'SIMCONNECT.DLL';
function SimConnect_SetNotificationGroupPriority; external 'SIMCONNECT.DLL';
function SimConnect_ClearNotificationGroup; external 'SIMCONNECT.DLL';
function SimConnect_RequestNotificationGroup; external 'SIMCONNECT.DLL';
function SimConnect_AddToDataDefinition; external 'SIMCONNECT.DLL';
function SimConnect_ClearDataDefinition; external 'SIMCONNECT.DLL';
function SimConnect_RequestDataOnSimObject; external 'SIMCONNECT.DLL';
function SimConnect_RequestDataOnSimObjectType; external 'SIMCONNECT.DLL';
function SimConnect_SetDataOnSimObject; external 'SIMCONNECT.DLL';
function SimConnect_MapInputEventToClientEvent; external 'SIMCONNECT.DLL';
function SimConnect_SetInputGroupPriority; external 'SIMCONNECT.DLL';
function SimConnect_RemoveInputEvent; external 'SIMCONNECT.DLL';
function SimConnect_ClearInputGroup; external 'SIMCONNECT.DLL';
function SimConnect_SetInputGroupState; external 'SIMCONNECT.DLL';
function SimConnect_RequestReservedKey; external 'SIMCONNECT.DLL';
function SimConnect_SubscribeToSystemEvent; external 'SIMCONNECT.DLL';
function SimConnect_UnsubscribeFromSystemEvent; external 'SIMCONNECT.DLL';
function SimConnect_WeatherRequestInterpolatedObservation; external
'SIMCONNECT.DLL';
function SimConnect_WeatherRequestObservationAtStation; external
'SIMCONNECT.DLL';
function SimConnect_WeatherRequestObservationAtNearestStation; external
'SIMCONNECT.DLL';
function SimConnect_WeatherCreateStation; external 'SIMCONNECT.DLL';
function SimConnect_WeatherRemoveStation; external 'SIMCONNECT.DLL';
function SimConnect_WeatherSetObservation; external 'SIMCONNECT.DLL';
function SimConnect_WeatherSetModeServer; external 'SIMCONNECT.DLL';
function SimConnect_WeatherSetModeTheme; external 'SIMCONNECT.DLL';
function SimConnect_WeatherSetModeGlobal; external 'SIMCONNECT.DLL';
function SimConnect_WeatherSetModeCustom; external 'SIMCONNECT.DLL';
function SimConnect_WeatherSetDynamicUpdateRate; external 'SIMCONNECT.DLL';
function SimConnect_WeatherRequestCloudState; external 'SIMCONNECT.DLL';
function SimConnect_WeatherCreateThermal; external 'SIMCONNECT.DLL';
function SimConnect_WeatherRemoveThermal; external 'SIMCONNECT.DLL';
function SimConnect_AICreateParkedATCAircraft; external 'SIMCONNECT.DLL';
function SimConnect_AICreateEnrouteATCAircraft; external 'SIMCONNECT.DLL';
function SimConnect_AICreateNonATCAircraft; external 'SIMCONNECT.DLL';
function SimConnect_AICreateSimulatedObject; external 'SIMCONNECT.DLL';
function SimConnect_AIReleaseControl; external 'SIMCONNECT.DLL';
function SimConnect_AIRemoveObject; external 'SIMCONNECT.DLL';
function SimConnect_AISetAircraftFlightPlan; external 'SIMCONNECT.DLL';
function SimConnect_ExecuteMissionAction; external 'SIMCONNECT.DLL';
function SimConnect_CompleteCustomMissionAction; external 'SIMCONNECT.DLL';
function SimConnect_Close; external 'SIMCONNECT.DLL';
function SimConnect_RetrieveString; external 'SIMCONNECT.DLL';
function SimConnect_GetLastSentPacketID; external 'SIMCONNECT.DLL';
function SimConnect_Open; external 'SIMCONNECT.DLL';
function SimConnect_CallDispatch; external 'SIMCONNECT.DLL';
// This effectively overloads CallDispatch to allow direct access to methods
function SimConnect_CallDispatchMethod; external 'SIMCONNECT.DLL' name
'SimConnect_CallDispatch';
function SimConnect_GetNextDispatch; external 'SIMCONNECT.DLL';
function SimConnect_RequestResponseTimes; external 'SIMCONNECT.DLL';
function SimConnect_InsertString; external 'SIMCONNECT.DLL';
function SimConnect_CameraSetRelative6DOF; external 'SIMCONNECT.DLL';
function SimConnect_MenuAddItem; external 'SIMCONNECT.DLL';
function SimConnect_MenuDeleteItem; external 'SIMCONNECT.DLL';
function SimConnect_MenuAddSubItem; external 'SIMCONNECT.DLL';
function SimConnect_MenuDeleteSubItem; external 'SIMCONNECT.DLL';
function SimConnect_RequestSystemState; external 'SIMCONNECT.DLL';
function SimConnect_SetSystemState; external 'SIMCONNECT.DLL';
function SimConnect_MapClientDataNameToID; external 'SIMCONNECT.DLL';
function SimConnect_CreateClientData; external 'SIMCONNECT.DLL';
function SimConnect_AddToClientDataDefinition; external 'SIMCONNECT.DLL';
function SimConnect_ClearClientDataDefinition; external 'SIMCONNECT.DLL';
function SimConnect_RequestClientData; external 'SIMCONNECT.DLL';
function SimConnect_SetClientData; external 'SIMCONNECT.DLL';
function SimConnect_FlightLoad; external 'SIMCONNECT.DLL';
function SimConnect_FlightSave; external 'SIMCONNECT.DLL';
function SimConnect_FlightPlanLoad; external 'SIMCONNECT.DLL';
// SP1A Additions
function SimConnect_Text; external 'SIMCONNECT.DLL';
function SimConnect_SubscribeToFacilities; external 'SIMCONNECT.DLL';
function SimConnect_UnsubscribeToFacilities; external 'SIMCONNECT.DLL';
function SimConnect_RequestFacilitiesList; external 'SIMCONNECT.DLL';
// End of SP1A Additions
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.FBDef;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Phys.IBWrapper;
type
// TFDPhysFBConnectionDefParams
// Generated for: FireDAC FB driver
TFDFBCharLenMode = (clmChars, clmBytes);
/// <summary> TFDPhysFBConnectionDefParams class implements FireDAC FB driver specific connection definition class. </summary>
TFDPhysFBConnectionDefParams = class(TFDConnectionDefParams)
private
function GetDriverID: String;
procedure SetDriverID(const AValue: String);
function GetOSAuthent: Boolean;
procedure SetOSAuthent(const AValue: Boolean);
function GetProtocol: TIBProtocol;
procedure SetProtocol(const AValue: TIBProtocol);
function GetServer: String;
procedure SetServer(const AValue: String);
function GetPort: Integer;
procedure SetPort(const AValue: Integer);
function GetSQLDialect: Integer;
procedure SetSQLDialect(const AValue: Integer);
function GetRoleName: String;
procedure SetRoleName(const AValue: String);
function GetCharacterSet: TIBCharacterSet;
procedure SetCharacterSet(const AValue: TIBCharacterSet);
function GetExtendedMetadata: Boolean;
procedure SetExtendedMetadata(const AValue: Boolean);
function GetOpenMode: TIBOpenMode;
procedure SetOpenMode(const AValue: TIBOpenMode);
function GetPageSize: TIBPageSize;
procedure SetPageSize(const AValue: TIBPageSize);
function GetDropDatabase: Boolean;
procedure SetDropDatabase(const AValue: Boolean);
function GetIBAdvanced: String;
procedure SetIBAdvanced(const AValue: String);
function GetCharLenMode: TFDFBCharLenMode;
procedure SetCharLenMode(const AValue: TFDFBCharLenMode);
published
property DriverID: String read GetDriverID write SetDriverID stored False;
property OSAuthent: Boolean read GetOSAuthent write SetOSAuthent stored False;
property Protocol: TIBProtocol read GetProtocol write SetProtocol stored False default ipLocal;
property Server: String read GetServer write SetServer stored False;
property Port: Integer read GetPort write SetPort stored False;
property SQLDialect: Integer read GetSQLDialect write SetSQLDialect stored False default 3;
property RoleName: String read GetRoleName write SetRoleName stored False;
property CharacterSet: TIBCharacterSet read GetCharacterSet write SetCharacterSet stored False default csNONE;
property ExtendedMetadata: Boolean read GetExtendedMetadata write SetExtendedMetadata stored False;
property OpenMode: TIBOpenMode read GetOpenMode write SetOpenMode stored False default omOpen;
property PageSize: TIBPageSize read GetPageSize write SetPageSize stored False default ps4096;
property DropDatabase: Boolean read GetDropDatabase write SetDropDatabase stored False;
property IBAdvanced: String read GetIBAdvanced write SetIBAdvanced stored False;
property CharLenMode: TFDFBCharLenMode read GetCharLenMode write SetCharLenMode stored False default clmChars;
end;
implementation
uses
FireDAC.Stan.Consts;
// TFDPhysFBConnectionDefParams
// Generated for: FireDAC FB driver
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetDriverID: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_DriverID];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetDriverID(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetOSAuthent: Boolean;
begin
Result := FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetOSAuthent(const AValue: Boolean);
begin
FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetProtocol: TIBProtocol;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_IB_Protocol];
if CompareText(s, 'Local') = 0 then
Result := ipLocal
else if CompareText(s, 'TCPIP') = 0 then
Result := ipTCPIP
else if CompareText(s, 'NetBEUI') = 0 then
Result := ipNetBEUI
else if CompareText(s, 'SPX') = 0 then
Result := ipSPX
else
Result := ipLocal;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetProtocol(const AValue: TIBProtocol);
const
C_Protocol: array[TIBProtocol] of String = ('Local', 'TCPIP', 'NetBEUI', 'SPX');
begin
FDef.AsString[S_FD_ConnParam_IB_Protocol] := C_Protocol[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetServer: String;
begin
Result := FDef.AsString[S_FD_ConnParam_Common_Server];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetServer(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_Common_Server] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetPort: Integer;
begin
Result := FDef.AsInteger[S_FD_ConnParam_Common_Port];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetPort(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_Common_Port] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetSQLDialect: Integer;
begin
if not FDef.HasValue(S_FD_ConnParam_IB_SQLDialect) then
Result := 3
else
Result := FDef.AsInteger[S_FD_ConnParam_IB_SQLDialect];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetSQLDialect(const AValue: Integer);
begin
FDef.AsInteger[S_FD_ConnParam_IB_SQLDialect] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetRoleName: String;
begin
Result := FDef.AsString[S_FD_ConnParam_IB_RoleName];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetRoleName(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_IB_RoleName] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetCharacterSet: TIBCharacterSet;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_Common_CharacterSet];
if CompareText(s, 'NONE') = 0 then
Result := csNONE
else if CompareText(s, 'ASCII') = 0 then
Result := csASCII
else if CompareText(s, 'BIG_5') = 0 then
Result := csBIG_5
else if CompareText(s, 'CYRL') = 0 then
Result := csCYRL
else if CompareText(s, 'DOS437') = 0 then
Result := csDOS437
else if CompareText(s, 'DOS850') = 0 then
Result := csDOS850
else if CompareText(s, 'DOS852') = 0 then
Result := csDOS852
else if CompareText(s, 'DOS857') = 0 then
Result := csDOS857
else if CompareText(s, 'DOS860') = 0 then
Result := csDOS860
else if CompareText(s, 'DOS861') = 0 then
Result := csDOS861
else if CompareText(s, 'DOS863') = 0 then
Result := csDOS863
else if CompareText(s, 'DOS865') = 0 then
Result := csDOS865
else if CompareText(s, 'EUCJ_0208') = 0 then
Result := csEUCJ_0208
else if CompareText(s, 'GB_2312') = 0 then
Result := csGB_2312
else if CompareText(s, 'ISO8859_1') = 0 then
Result := csISO8859_1
else if CompareText(s, 'ISO8859_2') = 0 then
Result := csISO8859_2
else if CompareText(s, 'KSC_5601') = 0 then
Result := csKSC_5601
else if CompareText(s, 'NEXT') = 0 then
Result := csNEXT
else if CompareText(s, 'OCTETS') = 0 then
Result := csOCTETS
else if CompareText(s, 'SJIS_0208') = 0 then
Result := csSJIS_0208
else if CompareText(s, 'UNICODE_FSS') = 0 then
Result := csUNICODE_FSS
else if CompareText(s, 'WIN1250') = 0 then
Result := csWIN1250
else if CompareText(s, 'WIN1251') = 0 then
Result := csWIN1251
else if CompareText(s, 'WIN1252') = 0 then
Result := csWIN1252
else if CompareText(s, 'WIN1253') = 0 then
Result := csWIN1253
else if CompareText(s, 'WIN1254') = 0 then
Result := csWIN1254
else if CompareText(s, 'DOS737') = 0 then
Result := csDOS737
else if CompareText(s, 'DOS775') = 0 then
Result := csDOS775
else if CompareText(s, 'DOS858') = 0 then
Result := csDOS858
else if CompareText(s, 'DOS862') = 0 then
Result := csDOS862
else if CompareText(s, 'DOS864') = 0 then
Result := csDOS864
else if CompareText(s, 'DOS866') = 0 then
Result := csDOS866
else if CompareText(s, 'DOS869') = 0 then
Result := csDOS869
else if CompareText(s, 'WIN1255') = 0 then
Result := csWIN1255
else if CompareText(s, 'WIN1256') = 0 then
Result := csWIN1256
else if CompareText(s, 'WIN1257') = 0 then
Result := csWIN1257
else if CompareText(s, 'ISO8859_3') = 0 then
Result := csISO8859_3
else if CompareText(s, 'ISO8859_4') = 0 then
Result := csISO8859_4
else if CompareText(s, 'ISO8859_5') = 0 then
Result := csISO8859_5
else if CompareText(s, 'ISO8859_6') = 0 then
Result := csISO8859_6
else if CompareText(s, 'ISO8859_7') = 0 then
Result := csISO8859_7
else if CompareText(s, 'ISO8859_8') = 0 then
Result := csISO8859_8
else if CompareText(s, 'ISO8859_9') = 0 then
Result := csISO8859_9
else if CompareText(s, 'ISO8859_13') = 0 then
Result := csISO8859_13
else if CompareText(s, 'ISO8859_15') = 0 then
Result := csISO8859_15
else if CompareText(s, 'KOI8R') = 0 then
Result := csKOI8R
else if CompareText(s, 'KOI8U') = 0 then
Result := csKOI8U
else if CompareText(s, 'UTF8') = 0 then
Result := csUTF8
else if CompareText(s, 'UNICODE_LE') = 0 then
Result := csUNICODE_LE
else if CompareText(s, 'UNICODE_BE') = 0 then
Result := csUNICODE_BE
else
Result := csNONE;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetCharacterSet(const AValue: TIBCharacterSet);
const
C_CharacterSet: array[TIBCharacterSet] of String = ('NONE', 'ASCII', 'BIG_5', 'CYRL', 'DOS437', 'DOS850', 'DOS852', 'DOS857', 'DOS860', 'DOS861', 'DOS863', 'DOS865', 'EUCJ_0208', 'GB_2312', 'ISO8859_1', 'ISO8859_2', 'KSC_5601', 'NEXT', 'OCTETS', 'SJIS_0208', 'UNICODE_FSS', 'WIN1250', 'WIN1251', 'WIN1252', 'WIN1253', 'WIN1254', 'DOS737', 'DOS775', 'DOS858', 'DOS862', 'DOS864', 'DOS866', 'DOS869', 'WIN1255', 'WIN1256', 'WIN1257', 'ISO8859_3', 'ISO8859_4', 'ISO8859_5', 'ISO8859_6', 'ISO8859_7', 'ISO8859_8', 'ISO8859_9', 'ISO8859_13', 'ISO8859_15', 'KOI8R', 'KOI8U', 'UTF8', 'UNICODE_LE', 'UNICODE_BE');
begin
FDef.AsString[S_FD_ConnParam_Common_CharacterSet] := C_CharacterSet[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetExtendedMetadata: Boolean;
begin
Result := FDef.AsBoolean[S_FD_ConnParam_Common_ExtendedMetadata];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetExtendedMetadata(const AValue: Boolean);
begin
FDef.AsBoolean[S_FD_ConnParam_Common_ExtendedMetadata] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetOpenMode: TIBOpenMode;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_IB_OpenMode];
if CompareText(s, 'Open') = 0 then
Result := omOpen
else if CompareText(s, 'Create') = 0 then
Result := omCreate
else if CompareText(s, 'OpenOrCreate') = 0 then
Result := omOpenOrCreate
else
Result := omOpen;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetOpenMode(const AValue: TIBOpenMode);
const
C_OpenMode: array[TIBOpenMode] of String = ('Open', 'Create', 'OpenOrCreate');
begin
FDef.AsString[S_FD_ConnParam_IB_OpenMode] := C_OpenMode[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetPageSize: TIBPageSize;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_IB_PageSize];
if CompareText(s, '1024') = 0 then
Result := ps1024
else if CompareText(s, '2048') = 0 then
Result := ps2048
else if CompareText(s, '4096') = 0 then
Result := ps4096
else if CompareText(s, '8192') = 0 then
Result := ps8192
else if CompareText(s, '16384') = 0 then
Result := ps16384
else
Result := ps4096;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetPageSize(const AValue: TIBPageSize);
const
C_PageSize: array[TIBPageSize] of String = ('1024', '2048', '4096', '8192', '16384');
begin
FDef.AsString[S_FD_ConnParam_IB_PageSize] := C_PageSize[AValue];
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetDropDatabase: Boolean;
begin
Result := FDef.AsYesNo[S_FD_ConnParam_IB_DropDatabase];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetDropDatabase(const AValue: Boolean);
begin
FDef.AsYesNo[S_FD_ConnParam_IB_DropDatabase] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetIBAdvanced: String;
begin
Result := FDef.AsString[S_FD_ConnParam_IB_IBAdvanced];
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetIBAdvanced(const AValue: String);
begin
FDef.AsString[S_FD_ConnParam_IB_IBAdvanced] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDPhysFBConnectionDefParams.GetCharLenMode: TFDFBCharLenMode;
var
s: String;
begin
s := FDef.AsString[S_FD_ConnParam_FB_CharLenMode];
if CompareText(s, 'Chars') = 0 then
Result := clmChars
else if CompareText(s, 'Bytes') = 0 then
Result := clmBytes
else
Result := clmChars;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysFBConnectionDefParams.SetCharLenMode(const AValue: TFDFBCharLenMode);
const
C_CharLenMode: array[TFDFBCharLenMode] of String = ('Chars', 'Bytes');
begin
FDef.AsString[S_FD_ConnParam_FB_CharLenMode] := C_CharLenMode[AValue];
end;
end.
|
{A benchmark demonstrating how the RTL Delphi MM fragments the virtual address
space}
unit FragmentationTestUnit;
interface
uses BenchmarkClassUnit, Math;
type
TFragmentationTest = class(TFastcodeMMBenchmark)
protected
FStrings: array of string;
public
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetSpeedWeight: Double; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
{ TFragmentationTest }
class function TFragmentationTest.GetBenchmarkDescription: string;
begin
Result := 'A benchmark that intersperses large block allocations with the '
+ 'allocation of smaller blocks to test how resistant the memory manager '
+ 'is to address space fragmentation that may eventually lead to '
+ '"out of memory" errors. '
+ 'Benchmark submitted by Pierre le Riche.';
end;
class function TFragmentationTest.GetBenchmarkName: string;
begin
Result := 'Fragmentation Test';
end;
class function TFragmentationTest.GetCategory: TBenchmarkCategory;
begin
Result := bmSingleThreadRealloc;
end;
class function TFragmentationTest.GetSpeedWeight: Double;
begin
{This benchmark is just to show how the RTL MM fragments. No real-world
significance apart from that, so we ignore the speed.}
Result := 0.2;
end;
procedure TFragmentationTest.RunBenchmark;
var
i, n: integer;
begin
inherited;
for n := 1 to 3 do // loop added to have more than 1000 MTicks for this benchmark
begin
SetLength(FStrings, 0);
for i := 1 to 90 do
begin
//add 100000 elements
SetLength(FStrings, length(FStrings) + 100000);
//allocate a 1 length string
SetLength(FStrings[high(FStrings)], 1);
end;
{Update the peak address space usage}
UpdateUsageStatistics;
end;
end;
end.
|
unit MissileSpeeds;
// this unit creates two objectlists with missile speed data Vanilla/CMOD4
// querying these ingame is not working for some reason...
interface
uses Contnrs, Classes;
type TMissile = class(TObject)
private
Name : string;
Speed : integer;
constructor Create(MissileName:string; MissileSpeed:integer);
end;
var
VanillaMissiles : TObjectlist;
CMOD4Missiles : TObjectlist;
implementation
var SaveExit : pointer;
procedure FreeLists; far;
begin
ExitProc := SaveExit;
VanillaMissiles.Free;
CMOD4Missiles.Free;
end {NewExit};
procedure PopulateLists();
begin
SaveExit := ExitProc;
ExitProc := @FreeLists;
VanillaMissiles:=TObjectList.Create(True);
CMOD4Missiles:=TObjectList.Create(True);
with VanillaMissiles do
begin
Add(TMissile.create('Banshee',153));
Add(TMissile.Create('Tomahawk',196));
Add(TMissile.Create('Hornet',186));
Add(TMissile.Create('Thorn',158));
Add(TMissile.Create('Typhoon',195));
Add(TMissile.Create('Firestorm',165));
Add(TMissile.Create('Hammer',253));
Add(TMissile.Create('Flail',486));
Add(TMissile.Create('Boarding',480));
Add(TMissile.Create('Poltergeist',250));
Add(TMissile.Create('Wraith',170));
Add(TMissile.Create('Spectre',190));
Add(TMissile.Create('Shadow',245));
Add(TMissile.Create('Ghoul',450));
Add(TMissile.Create('Phantom',212));
Add(TMissile.Create('Sting',257));
Add(TMissile.Create('Needle',500));
Add(TMissile.Create('Windstalker',179));
Add(TMissile.Create('Wildfire',246));
Add(TMissile.Create('Disruptor',514));
Add(TMissile.Create('Hammerhead',172));
Add(TMissile.Create('Beluga',211));
Add(TMissile.Create('Remote',142));
Add(TMissile.Create('Firefly',576));
Add(TMissile.Create('Thunderbolt',195));
Add(TMissile.Create('Aurora',589));
Add(TMissile.Create('Tornado',312));
Add(TMissile.Create('Cyclone',148));
Add(TMissile.Create('Tempest',195));
Add(TMissile.Create('Hurricane',471));
Add(TMissile.Create('Silkworm',190));
Add(TMissile.Create('Mosquito',590));
Add(TMissile.Create('Firelance',500));
Add(TMissile.Create('Wasp',560));
Add(TMissile.Create('Rapier',657));
Add(TMissile.Create('Dragonfly',250));
end;
with CMOD4Missiles do
begin
Add(TMissile.create('Banshee',230));
Add(TMissile.Create('Tomahawk',196));
Add(TMissile.Create('Hornet',349));
Add(TMissile.Create('Thorn',244));
Add(TMissile.Create('Typhoon',230));
Add(TMissile.Create('Firestorm',250));
Add(TMissile.Create('Hammer',400));
Add(TMissile.Create('Flail',486));
Add(TMissile.Create('Boarding',480));
Add(TMissile.Create('Poltergeist',250));
Add(TMissile.Create('Wraith',275));
Add(TMissile.Create('Spectre',250));
Add(TMissile.Create('Shadow',245));
Add(TMissile.Create('Ghoul',450));
Add(TMissile.Create('Phantom',212));
Add(TMissile.Create('Sting',290));
Add(TMissile.Create('Needle',235));
Add(TMissile.Create('Windstalker',553));
Add(TMissile.Create('Wildfire',246));
Add(TMissile.Create('Disruptor',514));
Add(TMissile.Create('Hammerhead',300));
Add(TMissile.Create('Beluga',211));
Add(TMissile.Create('Remote',170));
Add(TMissile.Create('Firefly',900));
Add(TMissile.Create('Thunderbolt',240));
Add(TMissile.Create('Aurora',1450));
Add(TMissile.Create('Tornado',360));
Add(TMissile.Create('Cyclone',260));
Add(TMissile.Create('Tempest',250));
Add(TMissile.Create('Hurricane',471));
Add(TMissile.Create('Silkworm',220));
Add(TMissile.Create('Mosquito',590));
Add(TMissile.Create('Firelance',110));
Add(TMissile.Create('Wasp',560));
Add(TMissile.Create('Rapier',657));
Add(TMissile.Create('Dragonfly',310));
end;
end;
{ TMissile }
constructor TMissile.Create(MissileName: string; MissileSpeed: integer);
begin
inherited Create();
Name:=MissileName;
Speed:=MissileSpeed;
end;
begin
PopulateLists();
end.
|
unit StrToInt_1;
interface
implementation
uses System;
function StrToInt(const Str: string): Int32;
var
i, SPos, Sign: Int32;
Ch: Char;
begin
Result := 0;
if Str[0] = '-' then
begin
sign := -1;
SPos := 1;
end else begin
Sign := 1;
SPos := 0;
end;
for i := SPos to Length(Str) - 1 do
begin
Ch := Str[i];
if (Ch > '9') or (Ch < '0') then
Assert(False, 'Invalid chars');
Result := Result * 10;
Result := Result + ord(Ch) - ord('0');
end;
Result := Result * sign;
end;
var
I: Int32;
procedure Test;
begin
I := StrToInt('-1');
Assert(I = -1);
I := StrToInt('00000');
Assert(I = 0);
I := StrToInt('45');
Assert(I = 45);
I := StrToInt('4512314123');
Assert(I = 4512314123);
I := StrToInt('-2147483648');
Assert(I = MinInt32);
I := StrToInt('2147483647');
Assert(I = MaxInt32);
end;
initialization
Test();
finalization
end. |
unit Input;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types,
FMX.Objects, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math,
System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects;
type
TIconPosition = (Left, Right);
TInput = class(TControl)
private
{ Private declarations }
protected
{ Protected declarations }
FPointerOnEnter: TNotifyEvent;
FPointerOnExit: TNotifyEvent;
FPointerOnIconClick: TNotifyEvent;
FPointerOnKeyUp: TKeyEvent;
FBackground: TRectangle;
FEdit: TEdit;
FIcon: TPath;
FLayoutIcon: TLayout;
FLayoutIconClick: TLayout;
FDark: Boolean;
FTabNext: TControl;
FDarkTheme: TAlphaColor;
FLightTheme: TAlphaColor;
procedure Paint; override;
procedure Resize; override;
procedure Painting; override;
procedure OnKeyUpTabNext(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
{ Repaint }
procedure DoChanged(Sender: TObject);
{ Events settings }
function GetFTag: NativeInt;
procedure SetFTag(const Value: NativeInt);
procedure SetFTabNext(const Value: TControl);
procedure OnEditEnter(Sender: TObject); virtual;
procedure OnEditExit(Sender: TObject); virtual;
function Validate(): Boolean; virtual;
procedure OnFBackgroundClick(Sender: TObject);
procedure OnFIconClick(Sender: TObject);
procedure SetFOnTyping(const Value: TNotifyEvent);
function GetFText: String;
procedure SetFText(const Value: String);
function GetFOnTyping: TNotifyEvent;
function GetFTextPrompt: String;
procedure SetFTextPrompt(const Value: String);
function GetFPassword: Boolean;
procedure SetFPassword(const Value: Boolean);
function GetFOnClick: TNotifyEvent;
procedure SetFOnClick(const Value: TNotifyEvent);
function GetFOnDblClick: TNotifyEvent;
procedure SetFOnDblClick(const Value: TNotifyEvent);
function GetTextSettings: TTextSettings;
procedure SetTextSettings(const Value: TTextSettings);
function GetFBackgroudColor: TBrush;
procedure SetFBackgroudColor(const Value: TBrush);
function GetFDark: Boolean;
procedure SetFDark(const Value: Boolean);
procedure SetFIconPosition(const Value: TIconPosition);
function GetFHitTest: Boolean;
procedure SetFHitTest(const Value: Boolean);
function GetFCursor: TCursor;
procedure SetFCursor(const Value: TCursor);
function GetFOnKeyDown: TKeyEvent;
procedure SetFOnKeyDown(const Value: TKeyEvent);
function GetFOnKeyUp: TKeyEvent;
procedure SetFOnKeyUp(const Value: TKeyEvent);
function GetFOnMouseDown: TMouseEvent;
procedure SetFOnMouseDown(const Value: TMouseEvent);
function GetFOnMouseUp: TMouseEvent;
procedure SetFOnMouseUp(const Value: TMouseEvent);
function GetFOnMouseWheel: TMouseWheelEvent;
procedure SetFOnMouseWheel(const Value: TMouseWheelEvent);
function GetFOnMouseMove: TMouseMoveEvent;
procedure SetFOnMouseMove(const Value: TMouseMoveEvent);
function GetFOnMouseEnter: TNotifyEvent;
procedure SetFOnMouseEnter(const Value: TNotifyEvent);
function GetFOnMouseLeave: TNotifyEvent;
procedure SetFOnMouseLeave(const Value: TNotifyEvent);
function GetFMaxLength: Integer;
procedure SetFMaxLength(const Value: Integer);
function GetFFilterChar: String;
procedure SetFFilterChar(const Value: String);
function GetFOnEnter: TNotifyEvent;
function GetFOnExit: TNotifyEvent;
procedure SetFOnEnter(const Value: TNotifyEvent);
procedure SetFOnExit(const Value: TNotifyEvent);
function GetFReadOnly: Boolean;
procedure SetFReadOnly(const Value: Boolean);
function GetFOnIconClick: TNotifyEvent;
procedure SetFOnIconClick(const Value: TNotifyEvent);
function GetFCanFocus: Boolean;
procedure SetFCanFocus(const Value: Boolean);
function GetFCaret: TCaret;
procedure SetFCaret(const Value: TCaret);
function GetFIconPosition: TIconPosition;
function GetFIconData: TPathData;
procedure SetFIconData(const Value: TPathData);
function GetFIconSize: Single;
procedure SetFIconSize(const Value: Single);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetFocus; reintroduce;
procedure Clear;
published
{ Published declarations }
property Align;
property Anchors;
property Enabled;
property Height;
property Opacity;
property Visible;
property Width;
property Size;
property Scale;
property Margins;
property Position;
property RotationAngle;
property RotationCenter;
{ Additional properties }
property Caret: TCaret read GetFCaret write SetFCaret;
property CanFocus: Boolean read GetFCanFocus write SetFCanFocus default True;
property Cursor: TCursor read GetFCursor write SetFCursor;
property HitTest: Boolean read GetFHitTest write SetFHitTest default True;
property ReadOnly: Boolean read GetFReadOnly write SetFReadOnly;
property Dark: Boolean read GetFDark write SetFDark;
property BackgroudColor: TBrush read GetFBackgroudColor write SetFBackgroudColor;
property Text: String read GetFText write SetFText;
property TextPrompt: String read GetFTextPrompt write SetFTextPrompt;
property TextSettings: TTextSettings read GetTextSettings write SetTextSettings;
property MaxLength: Integer read GetFMaxLength write SetFMaxLength;
property FilterChar: String read GetFFilterChar write SetFFilterChar;
property Password: Boolean read GetFPassword write SetFPassword;
property IconData: TPathData read GetFIconData write SetFIconData;
property IconSize: Single read GetFIconSize write SetFIconSize;
property IconPosition: TIconPosition read GetFIconPosition write SetFIconPosition;
property TabNext: TControl read FTabNext write SetFTabNext;
property Tag: NativeInt read GetFTag write SetFTag;
{ Optional properties - Rarely used }
// property CanFocus default True;
// property DragMode;
// property EnableDragHighlight;
// property Locked;
// property Padding;
// property PopupMenu;
// property TouchTargetExpansion;
// property TabOrder default -1;
// property TabStop default True;
{ Events }
property OnPainting;
property OnPaint;
property OnResize;
{ Mouse events }
property OnIconClick: TNotifyEvent read GetFOnIconClick write SetFOnIconClick;
property OnClick: TNotifyEvent read GetFOnClick write SetFOnClick;
property OnDblClick: TNotifyEvent read GetFOnDblClick write SetFOnDblClick;
property OnKeyDown: TKeyEvent read GetFOnKeyDown write SetFOnKeyDown;
property OnKeyUp: TKeyEvent read GetFOnKeyUp write SetFOnKeyUp;
property OnMouseDown: TMouseEvent read GetFOnMouseDown write SetFOnMouseDown;
property OnMouseUp: TMouseEvent read GetFOnMouseUp write SetFOnMouseUp;
property OnMouseWheel: TMouseWheelEvent read GetFOnMouseWheel write SetFOnMouseWheel;
property OnMouseMove: TMouseMoveEvent read GetFOnMouseMove write SetFOnMouseMove;
property OnMouseEnter: TNotifyEvent read GetFOnMouseEnter write SetFOnMouseEnter;
property OnMouseLeave: TNotifyEvent read GetFOnMouseLeave write SetFOnMouseLeave;
property OnTyping: TNotifyEvent read GetFOnTyping write SetFOnTyping;
property OnEnter: TNotifyEvent read GetFOnEnter write SetFOnEnter;
property OnExit: TNotifyEvent read GetFOnExit write SetFOnExit;
{ Optional events - Rarely used }
// property OnDragEnter;
// property OnDragLeave;
// property OnDragOver;
// property OnDragDrop;
// property OnDragEnd;
end;
implementation
uses
LongInput;
procedure TInput.OnEditEnter(Sender: TObject);
begin
if Assigned(FPointerOnEnter) then
FPointerOnEnter(Sender);
end;
procedure TInput.OnEditExit(Sender: TObject);
begin
if Assigned(FPointerOnExit) then
FPointerOnExit(Sender);
end;
procedure TInput.OnFBackgroundClick(Sender: TObject);
begin
FEdit.SetFocus;
end;
procedure TInput.OnFIconClick(Sender: TObject);
begin
OnFBackgroundClick(Sender);
if Assigned(FPointerOnIconClick) then
FPointerOnIconClick(Sender);
end;
procedure TInput.OnKeyUpTabNext(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if (Key = vkTab) and (Assigned(FTabNext)) then
begin
if (FTabNext is TInput) then
TInput(FTabNext).SetFocus
else if (FTabNext is TLongInput) then
TLongInput(FTabNext).SetFocus
else
FTabNext.SetFocus;
end;
if Assigned(FPointerOnKeyUp) then
FPointerOnKeyUp(Sender, Key, KeyChar, Shift);
end;
procedure TInput.SetFOnClick(const Value: TNotifyEvent);
begin
FEdit.OnClick := Value;
end;
procedure TInput.SetFBackgroudColor(const Value: TBrush);
begin
FBackground.Fill := Value;
end;
function TInput.GetFBackgroudColor: TBrush;
begin
Result := FBackground.Fill;
end;
procedure TInput.SetFCursor(const Value: TCursor);
begin
FBackground.Cursor := Value;
FEdit.Cursor := Value;
end;
function TInput.GetFCanFocus: Boolean;
begin
Result := FEdit.CanFocus;
end;
procedure TInput.SetFCanFocus(const Value: Boolean);
begin
FEdit.CanFocus := Value;
end;
function TInput.GetFCaret: TCaret;
begin
Result := FEdit.Caret;
end;
procedure TInput.SetFCaret(const Value: TCaret);
begin
FEdit.Caret := Value;
end;
function TInput.GetFCursor: TCursor;
begin
Result := FBackground.Cursor;
end;
procedure TInput.SetFDark(const Value: Boolean);
begin
FDark := Value;
FBackground.Fill.Kind := TBrushKind.Solid;
if Value then
begin
FBackground.Fill.Color := FDarkTheme;
FEdit.TextSettings.FontColor := TAlphaColor($FFFFFFFF);
FIcon.Fill.Color := TAlphaColor($FFFFFFFF);
end
else
begin
FBackground.Fill.Color := FLightTheme;
FEdit.TextSettings.FontColor := TAlphaColor($FF323232);
FIcon.Fill.Color := TAlphaColor($FF515151);
end;
end;
procedure TInput.SetFIconData(const Value: TPathData);
begin
FIcon.Data := Value;
end;
procedure TInput.SetFIconPosition(const Value: TIconPosition);
begin
if Value = TIconPosition.Right then
begin
FLayoutIcon.Align := TAlignLayout.Right;
FIcon.Align := TAlignLayout.Left;
end
else
begin
FLayoutIcon.Align := TAlignLayout.Left;
FIcon.Align := TAlignLayout.Right;
end;
end;
procedure TInput.SetFIconSize(const Value: Single);
begin
FIcon.Width := Value;
FIcon.Height := Value;
end;
function TInput.GetFIconData: TPathData;
begin
Result := FIcon.Data;
end;
function TInput.GetFIconPosition: TIconPosition;
begin
Result := TIconPosition.Right;
if FLayoutIcon.Align = TAlignLayout.Right then
Result := TIconPosition.Right
else if FLayoutIcon.Align = TAlignLayout.Left then
Result := TIconPosition.Left;
end;
function TInput.GetFIconSize: Single;
begin
Result := FIcon.Width;
end;
procedure TInput.SetFocus;
begin
FEdit.SetFocus;
end;
procedure TInput.Clear;
begin
FEdit.Text := '';
end;
function TInput.Validate: Boolean;
begin
Result := not(FEdit.Text.Length = 0);
end;
function TInput.GetFDark: Boolean;
begin
Result := FDark;
end;
procedure TInput.SetFFilterChar(const Value: String);
begin
FEdit.FilterChar := Value;
end;
function TInput.GetFFilterChar: String;
begin
Result := FEdit.FilterChar;
end;
procedure TInput.SetFHitTest(const Value: Boolean);
begin
FBackground.HitTest := Value;
FEdit.HitTest := Value;
end;
function TInput.GetFHitTest: Boolean;
begin
Result := FBackground.HitTest;
end;
procedure TInput.SetFMaxLength(const Value: Integer);
begin
FEdit.MaxLength := Value;
end;
function TInput.GetFMaxLength: Integer;
begin
Result := FEdit.MaxLength;
end;
function TInput.GetFOnClick: TNotifyEvent;
begin
Result := FEdit.OnClick;
end;
procedure TInput.SetFOnDblClick(const Value: TNotifyEvent);
begin
FEdit.OnDblClick := Value;
end;
function TInput.GetFOnDblClick: TNotifyEvent;
begin
Result := FEdit.OnDblClick;
end;
procedure TInput.SetFOnEnter(const Value: TNotifyEvent);
begin
FPointerOnEnter := Value;
end;
function TInput.GetFOnEnter: TNotifyEvent;
begin
Result := FPointerOnEnter;
end;
procedure TInput.SetFOnExit(const Value: TNotifyEvent);
begin
FPointerOnExit := Value;
end;
function TInput.GetFOnExit: TNotifyEvent;
begin
Result := FPointerOnExit;
end;
procedure TInput.SetFOnIconClick(const Value: TNotifyEvent);
begin
FPointerOnIconClick := Value;
if Assigned(Value) then
FLayoutIconClick.HitTest := True
else
FLayoutIconClick.HitTest := False;
end;
function TInput.GetFOnIconClick: TNotifyEvent;
begin
Result := FPointerOnIconClick;
end;
procedure TInput.SetFOnKeyDown(const Value: TKeyEvent);
begin
FEdit.OnKeyDown := Value;
end;
function TInput.GetFOnKeyDown: TKeyEvent;
begin
Result := FEdit.OnKeyDown;
end;
procedure TInput.SetFOnKeyUp(const Value: TKeyEvent);
begin
FPointerOnKeyUp := Value;
end;
function TInput.GetFOnKeyUp: TKeyEvent;
begin
Result := FPointerOnKeyUp;
end;
procedure TInput.SetFOnMouseDown(const Value: TMouseEvent);
begin
FEdit.OnMouseDown := Value;
end;
function TInput.GetFOnMouseDown: TMouseEvent;
begin
Result := FEdit.OnMouseDown;
end;
procedure TInput.SetFOnMouseEnter(const Value: TNotifyEvent);
begin
FEdit.OnMouseEnter := Value;
end;
function TInput.GetFOnMouseEnter: TNotifyEvent;
begin
Result := FEdit.OnMouseEnter;
end;
procedure TInput.SetFOnMouseLeave(const Value: TNotifyEvent);
begin
FEdit.OnMouseLeave := Value;
end;
function TInput.GetFOnMouseLeave: TNotifyEvent;
begin
Result := FEdit.OnMouseLeave;
end;
procedure TInput.SetFOnMouseMove(const Value: TMouseMoveEvent);
begin
FEdit.OnMouseMove := Value;
end;
function TInput.GetFOnMouseMove: TMouseMoveEvent;
begin
Result := FEdit.OnMouseMove;
end;
procedure TInput.SetFOnMouseUp(const Value: TMouseEvent);
begin
FEdit.OnMouseUp := Value;
end;
function TInput.GetFOnMouseUp: TMouseEvent;
begin
Result := FEdit.OnMouseUp;
end;
procedure TInput.SetFOnMouseWheel(const Value: TMouseWheelEvent);
begin
FEdit.OnMouseWheel := Value;
end;
function TInput.GetFOnMouseWheel: TMouseWheelEvent;
begin
Result := FEdit.OnMouseWheel;
end;
procedure TInput.SetFOnTyping(const Value: TNotifyEvent);
begin
FEdit.OnTyping := Value;
end;
function TInput.GetFOnTyping: TNotifyEvent;
begin
Result := FEdit.OnTyping;
end;
procedure TInput.SetFTabNext(const Value: TControl);
begin
FTabNext := Value;
end;
procedure TInput.SetFTag(const Value: NativeInt);
begin
FBackground.Tag := Value;
FEdit.Tag := Value;
FLayoutIconClick.Tag := Value;
TControl(Self).Tag := Value;
end;
procedure TInput.SetFText(const Value: String);
begin
FEdit.Text := Value;
end;
function TInput.GetFTag: NativeInt;
begin
Result := TControl(Self).Tag;
end;
function TInput.GetFText: String;
begin
Result := FEdit.Text;
end;
procedure TInput.SetFTextPrompt(const Value: String);
begin
FEdit.TextPrompt := Value;
end;
function TInput.GetFTextPrompt: String;
begin
Result := FEdit.TextPrompt;
end;
procedure TInput.SetTextSettings(const Value: TTextSettings);
begin
FEdit.TextSettings := Value;
end;
function TInput.GetTextSettings: TTextSettings;
begin
Result := FEdit.TextSettings;
end;
procedure TInput.SetFPassword(const Value: Boolean);
begin
FEdit.Password := Value;
end;
function TInput.GetFPassword: Boolean;
begin
Result := FEdit.Password;
end;
procedure TInput.SetFReadOnly(const Value: Boolean);
begin
FEdit.ReadOnly := Value;
end;
function TInput.GetFReadOnly: Boolean;
begin
Result := FEdit.ReadOnly;
end;
{ Protected declarations }
procedure TInput.Paint;
begin
inherited;
if FIcon.Data.Data.Equals('') then
begin
FLayoutIcon.Visible := False;
FIcon.Visible := False;
end
else
begin
FLayoutIcon.Visible := True;
FIcon.Visible := True;
FLayoutIcon.Width := 13 + FIcon.Width;
end;
end;
procedure TInput.Resize;
begin
inherited;
if Assigned(FBackground) then
begin
with FBackground do
begin
Height := Self.Width * 0.85;
Width := Self.Width * 0.85;
Position.X := Self.Width / 2 - Width / 2;
Position.Y := Self.Height / 2 - Height / 2;
end;
end;
end;
procedure TInput.Painting;
begin
inherited;
end;
{ Repaint }
procedure TInput.DoChanged(Sender: TObject);
begin
Repaint;
end;
{ Public declarations }
constructor TInput.Create(AOwner: TComponent);
begin
inherited;
Self.Width := 250;
Self.Height := 40;
FDarkTheme := TAlphaColor($C82F2F2F);
FLightTheme := TAlphaColor($C8FFFFFF);
{ Backgroud }
FBackground := TRectangle.Create(Self);
Self.AddObject(FBackground);
FBackground.Align := TAlignLayout.Contents;
FBackground.Stroke.Kind := TBrushKind.None;
FBackground.Fill.Color := FLightTheme;
FBackground.XRadius := 4;
FBackground.YRadius := 4;
FBackground.SetSubComponent(True);
FBackground.Stored := False;
FBackground.OnClick := OnFBackgroundClick;
{ Edit }
FEdit := TEdit.Create(Self);
FEdit.Parent := FBackground;
FEdit.Align := TAlignLayout.Client;
FEdit.Margins.Top := 5;
FEdit.Margins.Bottom := 5;
FEdit.Margins.Left := 8;
FEdit.Margins.Right := 8;
FEdit.StyleLookup := 'transparentedit';
FEdit.StyledSettings := [];
FEdit.TextSettings.Font.Size := 14;
FEdit.TextSettings.Font.Family := 'SF Pro Display';
FEdit.TextSettings.FontColor := TAlphaColor($FF323232);
FEdit.SetSubComponent(True);
FEdit.Stored := False;
FEdit.OnKeyUp := OnKeyUpTabNext;
FEdit.TabStop := False;
FEdit.OnEnter := OnEditEnter;
FEdit.OnExit := OnEditExit;
{ Icon }
FLayoutIcon := TLayout.Create(Self);
FBackground.AddObject(FLayoutIcon);
FLayoutIcon.Align := TAlignLayout.Left;
FLayoutIcon.Width := 25;
FLayoutIcon.HitTest := False;
FLayoutIcon.SetSubComponent(True);
FLayoutIcon.Stored := False;
FIcon := TPath.Create(Self);
FLayoutIcon.AddObject(FIcon);
FIcon.Align := TAlignLayout.Right;
FIcon.WrapMode := TPathWrapMode.Fit;
FIcon.Fill.Color := TAlphaColor($FF515151);
FIcon.Stroke.Kind := TBrushKind.None;
FIcon.Width := 12;
FIcon.HitTest := False;
FIcon.SetSubComponent(True);
FIcon.Stored := False;
{ Layout Click }
FLayoutIconClick := TLayout.Create(Self);
FIcon.AddObject(FLayoutIconClick);
FLayoutIconClick.Align := TAlignLayout.Client;
FLayoutIconClick.Margins.Left := -10;
FLayoutIconClick.Margins.Right := -10;
FLayoutIconClick.Cursor := crHandPoint;
FLayoutIconClick.HitTest := False;
FLayoutIconClick.OnClick := OnFIconClick;
{ Initial settings }
SetFCursor(crIBeam);
end;
destructor TInput.Destroy;
begin
if Assigned(FIcon) then
FIcon.Free;
if Assigned(FLayoutIcon) then
FLayoutIcon.Free;
if Assigned(FEdit) then
FEdit.Free;
if Assigned(FBackground) then
FBackground.Free;
inherited;
end;
end.
|
{ Invokable interface ISetExamState }
unit SetExamStateIntf;
interface
uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns;
const
IS_OPTN = $0001;
IS_UNBD = $0002;
IS_NLBL = $0004;
IS_REF = $0080;
type
SetExamStateRequest = class(TRemotable)
private
Fusn: string;
Fusn_Specified: boolean;
Fpwd: string;
Fpwd_Specified: boolean;
Fappointment_id: string;
Fexam_id: integer;
Fexam_type_id: integer;
Fexam_status: integer;
Fexam_datetime: TXSDateTime;
procedure Setusn(Index: Integer; const Astring: string);
function usn_Specified(Index: Integer): boolean;
procedure Setpwd(Index: Integer; const Astring: string);
function pwd_Specified(Index: Integer): boolean;
public
destructor Destroy; override;
published
property usn: string Index (IS_OPTN) read Fusn write Setusn stored usn_Specified;
property pwd: string Index (IS_OPTN) read Fpwd write Setpwd stored pwd_Specified;
property appointment_id: string read Fappointment_id write Fappointment_id;
property exam_id: integer read Fexam_id write Fexam_id;
property exam_type_id: integer read Fexam_type_id write Fexam_type_id;
property exam_status: integer read Fexam_status write Fexam_status;
property exam_datetime: TXSDateTime read Fexam_datetime write Fexam_datetime;
end;
SetExamStateResponse = class(TRemotable)
private
Fres_code: Integer;
Fres_msg: string;
Fres_msg_Specified: boolean;
procedure Setres_msg(Index: Integer; const Astring: string);
function res_msg_Specified(Index: Integer): boolean;
published
property res_code: Integer read Fres_code write Fres_code;
property res_msg: string Index (IS_OPTN) read Fres_msg write Setres_msg stored res_msg_Specified;
end;
{ Invokable interfaces must derive from IInvokable }
ISetExamState = interface(IInvokable)
['{21E5BBC4-75F8-4456-B15A-78AF7AF4A14B}']
function SetExamState(const pSetExamStateRequest: SetExamStateRequest): SetExamStateResponse; stdcall;
end;
implementation
uses System.SysUtils;
destructor SetExamStateRequest.Destroy;
begin
System.SysUtils.FreeAndNil(Fexam_datetime);
inherited Destroy;
end;
procedure SetExamStateRequest.Setusn(Index: Integer; const Astring: string);
begin
Fusn := Astring;
Fusn_Specified := True;
end;
function SetExamStateRequest.usn_Specified(Index: Integer): boolean;
begin
Result := Fusn_Specified;
end;
procedure SetExamStateRequest.Setpwd(Index: Integer; const Astring: string);
begin
Fpwd := Astring;
Fpwd_Specified := True;
end;
function SetExamStateRequest.pwd_Specified(Index: Integer): boolean;
begin
Result := Fpwd_Specified;
end;
procedure SetExamStateResponse.Setres_msg(Index: Integer; const Astring: string);
begin
Fres_msg := Astring;
Fres_msg_Specified := True;
end;
function SetExamStateResponse.res_msg_Specified(Index: Integer): boolean;
begin
Result := Fres_msg_Specified;
end;
initialization
{ Invokable interfaces must be registered }
// InvRegistry.RegisterInterface(TypeInfo(ChorafarmaSOAPServer));
InvRegistry.RegisterInterface(TypeInfo(ISetExamState), 'urn:SetExamStateIntf-ISetExamState', '');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(ISetExamState), 'urn:SetExamStateIntf-ISetExamState#SetExamState');
RemClassRegistry.RegisterXSClass(SetExamStateResponse, 'urn:SetExamStateIntf', 'SetExamStateResponse');
RemClassRegistry.RegisterXSClass(SetExamStateRequest, 'urn:SetExamStateIntf', 'SetExamStateRequest');
(*
InvRegistry.RegisterInterface(TypeInfo(ChorafarmaSOAPServer), 'urn:SetExamStateIntf-ChorafarmaSOAPServer', '');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(ChorafarmaSOAPServer), 'urn:SetExamStateIntf-ChorafarmaSOAPServer#SetExamState');
RemClassRegistry.RegisterXSClass(SetExamStateResponse, 'urn:SetExamStateIntf', 'SetExamStateResponse');
RemClassRegistry.RegisterXSClass(SetExamStateRequest, 'urn:SetExamStateIntf', 'SetExamStateRequest');
*)
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Datasnap.DSService;
interface
uses
System.Classes,
Data.DBXCommon,
Data.DbxDatasnap,
Data.DBXJSON,
Data.DBXMessageHandlerCommon,
{$IFDEF CLR}
DBXSocketChannelManaged,
{$ELSE}
Data.DbxSocketChannelNative,
{$ENDIF}
Data.DBXTransport,
Datasnap.DSAuth,
Datasnap.DSCommonServer,
Datasnap.DSTransport,
System.Generics.Collections,
System.SyncObjs,
System.SysUtils;
const
REQUEST_DELIMITER = '/';
REQUEST_PARAM_DELIMITER = '?';
REST_CONTEXT = 'rest';
JSON_CONTEXT = 'json';
CACHE_CONTEXT = 'cache';
type
/// <summary>Filter parameter range type</summary>
/// <remarks>It is expected that server methods have up to 64 parameters (and an eventual return).
/// Each parameter can subject to a filter operation.
/// </remarks>
TParamRange = set of 0..64;
/// <summary> Converts any type to JSON based on filter parameters </summary>
/// <remarks> Any request filter needs to register with the RequestFilter factory
/// in order to be used within requests. The filter is configurable in the request
/// based on parameter values
/// </remarks>
TDSRequestFilter<T> = class
strict private
FName: String;
FRange: TParamRange;
FOnResult: boolean;
FTypeName: String;
protected
constructor Create(const TypeName: String); virtual;
public
destructor Destroy; override;
/// <summary>Changes the parameter value</summary>
/// <param name="ParamName">Filter parameter</param>
/// <param name="ParamValue">Parameter value, as string</param>
/// <return>true if the parameter exists and the value is valid</return>
function SetParameterValue(ParamName: String; ParamValue: String): boolean; virtual;
/// <summary>Returns true if the filter accepts the given parameter</summary>
/// <param name="ParamName">parameter name</param>
/// <return>true if the parameter exists</return>
function HasParameter(const ParamName: String): boolean; virtual;
/// <summary>Returns true if the value can be converted to JSON</summary>
/// <param name="Value">value to be converted</param>
/// <return>true if the value can be converted</return>
function CanConvert(Value: T): boolean; virtual; abstract;
/// <summary>Returns the JSON value</summary>
/// <param name="Value">value to be converted</param>
/// <param name="IsLocal">true for an in-process value (controls the life-cycle)</param>
/// <return>JSON value</return>
function ToJSON(Value: T; IsLocal: boolean): TJSONValue; virtual; abstract;
public
property Name: string read FName write FName;
property TypeName: string read FTypeName;
property Range: TParamRange read FRange write FRange;
property OnResult: boolean read FOnResult write FOnResult;
end;
/// <summary>Specilized filter for DBX values</summary>
TDBXRequestFilter = class(TDSRequestFilter<TDBXValue>)
public
/// <summary>Clone current instance</summary>
/// <return>TDBXRequestFilter</return>
function Clone: TDBXRequestFilter; virtual; abstract;
end;
/// <summary>Returns parts of the DBX values, based on offset and count</summary>
TDBXCropRequestFilter = class(TDBXRequestFilter)
strict private
FOff, FCount: Integer;
protected
constructor Create(const TypeName: String; Off, Count: Integer); reintroduce; overload;
property Off: Integer read FOff;
property Count: Integer read FCount;
public
constructor Create(const TypeName: String); overload; override;
destructor Destroy; override;
function SetParameterValue(ParamName: String; ParamValue: String): boolean; override;
function HasParameter(const ParamName: String): boolean; override;
end;
/// <summary>Specialized request filter for String and Stream types</summary>
TDBXSubStringRequestFilter = class(TDBXCropRequestFilter)
public
function CanConvert(Value: TDBXValue): boolean; override;
function ToJSON(Value: TDBXValue; IsLocal: boolean = false): TJSONValue; override;
function Clone: TDBXRequestFilter; override;
end;
/// <summary>Specialized crop filter to DBX Reader</summary>
TDBXReaderRequestFilter = class(TDBXCropRequestFilter)
public
function CanConvert(Value: TDBXValue): boolean; override;
function ToJSON(Value: TDBXValue; IsLocal: boolean = false): TJSONValue; override;
function Clone: TDBXRequestFilter; override;
end;
/// <summary>Handles the available DBX request filters</summary>
TDBXRequestFilterFactory = class
strict private
class var FInstance: TDBXRequestFilterFactory;
private
FRepo: TObjectDictionary<String, TDBXRequestFilter>;
class procedure SetUp;
class procedure CleanUp;
public
constructor Create;
destructor Destroy; override;
procedure RegisterRequestFilter(Converter: TDBXRequestFilter);
function RequestFilter(Name: String): TDBXRequestFilter;
procedure GetAllWithField(FieldName: String; List: TObjectList<TDBXRequestFilter>);
class property Instance: TDBXRequestFilterFactory read FInstance;
end;
/// <summary> DSService exceptions </summary>
TDSServiceException = class(Exception)
end;
TDBXRequestFilterDictionary = TObjectDictionary<String, TDBXRequestFilter>;
/// <summary> Class for managing Request Filteres
/// </summary>
TDSRequestFilterManager = class
protected
FRequestFilterStore: TDBXRequestFilterDictionary;
FStreamAsJSON: Boolean;
/// <summary> Processes request parameters name from: DCType1-10.Field or DCType.Field or DCType1,3.Field
/// </summary>
class procedure ParseParamName(const PName: string; out DCName: string; out DCType: string; out FieldName: string;
out Range: TParamRange; out OnResult: boolean);
public
constructor Create; virtual;
destructor Destroy; override;
/// <summary> Builds the appropriate data converters out of query parameters</summary>
function ProcessQueryParameter(const ParamName: string; const ParamValue: String): boolean;
procedure FiltersForCriteria(const TypeName: string; const Range: TParamRange;
const OnResult: boolean; out List: TObjectList<TDBXRequestFilter>); overload;
procedure FiltersForCriteria(const Range: TParamRange; const OnResult: boolean;
out List: TObjectList<TDBXRequestFilter>); overload;
/// <summary> Checks if two converters overlap ranges in FDataConverterStore </summary>
function CheckConvertersForConsistency: boolean;
end;
/// <summary> API class for all DS specific stateless services. A request
/// comes in usually as a HTTP request and the response consists of an JSON object.
/// Various protocols such as REST implements the methods of this class.
/// </summary>
TDSService = class(TDSRequestFilterManager)
private
FDBXProperties: TDBXDatasnapProperties;
FLocalConnection: boolean;
function GetInputParameterInstance(JsonParam: TJSONValue; Parameter: TDBXParameter;
var InstanceOwner: Boolean): TJSONValue;
protected
/// <summary> Dispatches the JSON request to appropriate processing method. It
/// accepts an array of JSON objects that will be dispatched to the processing
/// mrthod. The response is a JSON array with the execution results.
/// </summary>
/// <remarks>
/// Example of JSON request: [{"execute":{"MethodClass.MethodName":[inputParameter,...]}},...]
///
/// Where output or return parameters are defined, they are picked up into a JSON response:
/// [{"result":[parameterValue,parameterValue...]},...]
///
/// If the server throws an exception, then the JSON response is:
/// [{"error":"error message"},...]
/// </remarks>
/// <param name="Request">JSON request in the protocol format, never nil</param>
/// <param name="ResponseHandler"> Handler responsible for managing the result
/// </param>
procedure ProcessRequest(const Request:TJSONArray; ResponseHandler: TRequestCommandHandler); virtual;
/// <summary> Executes the JSON request and generates the JSON response
/// </summary>
/// <remarks> Input parameters are consumed from left to right (position based).
/// The values are bound to the IN or IN/OUT method actual parameters orderly
/// from left to right, skipping the OUT or RETURN parameters.
/// If not enough input parameters are supplied, the outstanding actual parameters
/// are bound to nil.
/// </remarks>
/// <param name="Request">JSON request in the protocol format, never nil</param>
/// <param name="ResponseHandler">Handles the result of command execution</param>
procedure Execute(const Request: TJSONObject; ResponseHandler: TRequestCommandHandler);
public
constructor Create(DSServerName, DSHostname: String; DSPort: Integer;
AuthUser: String = ''; AuthPassword: String = ''); reintroduce; overload; Virtual;
constructor Create(DSServerName, DSHostname: String; DSPort: Integer;
AuthUser: String = ''; AuthPassword: String = ''; AIPImplementationID: string = ''); reintroduce; overload; Virtual;
destructor Destroy; override;
/// <summary> processes GET request
/// </summary>
/// <remarks> The response contains either success or an error message in an JSON object.
/// </remarks>
/// <param name="Request">contains the original request, never nil or empty</param>
/// <param name="Params">request parameters</param>
/// <param name="Content">contains the request content, usually the serialized JSON object to be updated.</param>
/// <param name="ResponseHandler">Handles the command populated with the result</param>
procedure ProcessGETRequest(const Request: String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler); virtual; abstract;
/// <summary> processes PUT request
/// </summary>
/// <remarks> The response contains either success or an error message in an JSON object.
/// </remarks>
/// <param name="Request">contains the original request, never nil or empty</param>
/// <param name="Params">request parameters</param>
/// <param name="Content">contains the request content, usually the serialized JSON object to be updated.</param>
/// <param name="ResponseHandler">Handles the command populated with the result</param>
procedure ProcessPUTRequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler); virtual; abstract;
/// <summary> processes POST request
/// </summary>
/// <remarks> The response contains either success or an error message in an JSON object.
/// </remarks>
/// <param name="Request">contains the original request, never nil or empty</param>
/// <param name="Params">request parameters</param>
/// <param name="Content">contains the request content, usually the serialized JSON object to be updated.</param>
/// <param name="ResponseHandler">Handles the command populated with the result</param>
procedure ProcessPOSTRequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler); virtual; abstract;
/// <summary> processes DELETE request
/// </summary>
/// <remarks> The response contains either success or an error message in an JSON object.
/// </remarks>
/// <param name="Request">contains the original request, never nil or empty</param>
/// <param name="Params">request parameters</param>
/// <param name="Content">contains the request content, usually the serialized JSON object to be updated.</param>
/// <param name="ResponseHandler">Handles the command populated with the result</param>
procedure ProcessDELETERequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler); virtual; abstract;
property LocalConnection: boolean read FLocalConnection;
/// <summary> Set with query parameter 'json' allowing the user to returna stream as a
/// JSON array of bytes instead of a content stream.
/// </summary>
property StreamAsJSON: Boolean read FStreamAsJSON write FStreamAsJSON;
end;
/// <summary> REST service implementation. Request methods are mapped to
/// CRUD as described below.
/// </summary>
/// <remarks>
/// REST protocol:
/// GET: /MethodClass/MethodName/inputParameter[/inputParameter]*
/// JSON request: {"execute":{"MethodClass.MethodName":[inputParameter[,inputParameter]*]}}
/// PUT: /MethodClass/MethodName/inputParameter[/inputparameter]* and [content]
/// JSON request: {"execute":{"MethodClass.acceptMethodName":[inputParameter[,inputParameter]*[,JSONValue]}}
/// POST: /MethodClass/MethodName/inputParameter[/inputparameter]* and [content]
/// JSON request: {"execute":{"MethodClass.updateMethodName":[inputParameter[,inputParameter]*[,JSONValue]}}
/// DELETE: /MethodClass/MethodName/inputParameter[/inputParameter]*
/// JSON request: {"execute":{"MethodClass.cancelMethodName":[inputParameter[,inputParameter]*]}}
///
/// Example: Manage a database connection
/// PUT message http://mySite.com/datasnap/rest/Test/Connection/MSSQL1 results in the JSON request
/// {"execute":{"Test.acceptConnection":["MSSQL1"]}}
/// POST message http://mySite.com/datasnap/rest/Test/Connection/MSSQL2 results in the JSON request
/// {"execute":{"Test.updateConnection":["MSSQL2"]}}
/// GET message http://mySite.com/datasnap/rest/Test/Connection results in the JSON request
/// {"execute":{"Test.Connection":[]}}
/// DELETE message http://mySite.com/datasnap/rest/Test/Connection results in the JSON request
/// {"execute":{"Test.cancelConnection":[]}}
///
/// In the acceptConnection the user can implement the code required to open a connection denoted
/// MSSQL1, in updateConnection to close the existing connection (if any) and open a new one,
/// in Connection the code returns the name of the current open connection and in cancelConnection
/// the code closes the existing connection if any.
///
/// Where output or return parameters are defined, they are picked up into a JSON response:
/// {"result":[parameterValue[,parameterValue]*]}
///
/// If the server throws an exception, then the JSON response is:
/// {"error":"error message"}
///
/// </remarks>
TDSRESTService = class(TDSService)
private
/// <summary> Utility mnethod that parses a generic request /class/method[/param]* and returns the values in the output parameters
/// </summary>
/// <param name="Request">Request string in the format above, never null of empty</param>
/// <param name="ClassName">Output parameter with the class name</param>
/// <param name="MethodName">Output parameter with the method name</param>
/// <param name="ParamValues">parameter list with parameter values</param>
procedure ParseRequest(const Request: String; var ClassName: String; var MethodName:
String; var ParamValues: TStringList);
/// <summary> Utility mnethod that creates a JSON array out a parameter list
/// </summary>
/// <param name="Params">parameter list, never nil but may be empty</param>
/// <param name="ParamArray">JSON array, containing values from the parameter list</param>
procedure BuildParamArray(const Params: TStringList; var ParamArray: TJSONArray);
/// <summary> processes REST request
/// </summary>
/// <remarks> The response contains either success or an error message
/// </remarks>
/// <param name="RequestType">The request type, one of GET, POST, PUT and DELETE</param>
/// <param name="RestRequest">contains the REST request, never nil or empty</param>
/// <param name="Content">contains the HTTP content, usually the object to be updated</param>
/// <param name="ResponseHandler"> Handler responsible for managing the result </param>
procedure ProcessREST(const RequestType: String; const RestRequest: String;
const Content: TBytes; ResponseHandler: TRequestCommandHandler);
procedure SetMethodNameWithPrefix(const RequestType, ClassName, MethodName: String; out DSMethodName: String);
public
constructor Create( dsServerName, dsHostname: String; dsPort: Integer; AuthUser: String = '';
AuthPassword: String = '' ); override;
constructor CreateImpl( dsServerName, dsHostname: String; dsPort: Integer; AuthUser: String = '';
AuthPassword: String = ''; AIPImplementationID: string = '');
destructor Destroy; override;
procedure ProcessGETRequest(const Request:String; Params: TStrings;
Content: TBytes;
ResponseHandler: TRequestCommandHandler); override;
procedure ProcessPUTRequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler); override;
procedure ProcessPOSTRequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler); override;
procedure ProcessDELETERequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler); override;
end;
/// <summary> Service for JSON HTTP request. They are post requests with
/// JSON content {["execute":{"MethodClass.MethodName":[inputParameter[,inputParameter]*]}]+}.
/// If the JSON content cannot be parsed from the content an exception is thrown.
///
/// For each method a pair "result":[parameterValue[,parameterValue]*] is generated,
/// where the parameter values are the method output and return parameters.
/// If the method throws an exception, then corresponding JSON pair is {"error":"error message"}
///
/// The JSON response is:
/// {"result":[parameterValue[,parameterValue]*][,"result":[...]]*}
///
/// </summary>
TDSJSONService = class(TDSService)
protected
procedure ProcessJSONCommand(Content: TBytes; ResponseHandler: TRequestCommandHandler);
public
constructor Create( dsServerName, dsHostname: String; dsPort: Integer; AuthUser: String = '';
AuthPassword: String = '' ); override;
constructor CreateImpl( dsServerName, dsHostname: String; dsPort: Integer; AuthUser: String = '';
AuthPassword: String = ''; AIPImplementationID: string = '');
destructor Destroy; override;
procedure ProcessGETRequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler); override;
procedure ProcessPUTRequest(const Request:String; Params: TStrings;
Content: TBytes;
ResponseHandler: TRequestCommandHandler); override;
procedure ProcessPOSTRequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler); override;
procedure ProcessDELETERequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler); override;
end;
TDSSessionCacheKeys = TList<Integer>;
/// <summary> Cache for holding commands with complex parameter types (Table, Stream, Object)
/// which are being stored for later reuse.
/// </summary>
TDSSessionCache = class
private
FItems : TDictionary<Integer, TResultCommandHandler>;
public
constructor Create;
destructor Destroy(); Override;
/// <summary> Trys to add the given item to the list of items managed by the cache. If successful
/// this will return the unique ID for the item in the cache. If not successful, -1 will be returned.
/// </summary>
function AddItem(Item: TResultCommandHandler): Integer;
/// <summary> Removes the given item from the list of managed items if found.
/// </summary>
/// <remarks> Does not claim ownership of the item. </remarks>
procedure RemoveItem(Item: TResultCommandHandler); Overload;
/// <summary> Removes the item with the given ID from the list of managed items if found.
/// </summary>
/// <remarks> If InstanceOwner is set to false, the item will be returned if found, or nil if not found.
/// If InstanceOwner is true, nil will always be returned.
/// </remarks>
function RemoveItem(ID: Integer; InstanceOwner: Boolean = True): TResultCommandHandler; Overload;
/// <summary> Returns the item with the given ID, or nil if not found.
/// </summary>
function GetItem(ID: Integer): TResultCommandHandler;
/// <summary> Returns the ID for the item, or -1 if not found
/// </summary>
function GetItemID(Item: TResultCommandHandler): Integer;
/// <summary> Returns a list of IDs currently helf by the cache </summary>
function GetItemIDs: TDSSessionCacheKeys;
/// <summary> Clears all of the items stred in this cache,
/// freeing them if InstanceOwner is True. (defaults to true)
/// </summary>
procedure ClearAllItems(InstanceOwner: Boolean = True);
end;
/// <summary> Session status
/// </summary>
TDSSessionStatus = (Active, Closed, Idle, Terminated, Connected, Expired);
TDSSession = class
private
FStartDateTime: TDateTime; /// creation timestamp
FDuration: Integer; /// in miliseconds, 0 for infinite (default)
FStatus: TDSSessionStatus; /// default idle
FLastActivity: Cardinal; /// timestamp of the last activity on this session
FUserName: String; /// user name that was authenticated with this session
FSessionName: String; /// session name, may be internally generated, exposed to 3rd party
FMetaData: TDictionary<String,String>; /// map of metadata stored in the session
FMetaObjects: TDictionary<String,TObject>; /// map of objects stored in the session
FUserRoles: TStrings; /// user roles defined through authentication
FCache: TDSSessionCache;
FLastResultStream: TObject; /// Allow any object which owns a stream, or the stream itself, to be stored here
FCreator: TObject; /// Creator of the session object reference
private
procedure SetSessionName(const sessionId: String);
procedure SetUserName(const userName: String);
protected
/// <return> session internal id </return>
function GetId: NativeInt;
/// <summary> terminates the current session, normally triggered by a scheduler </summary>
procedure TerminateSession; virtual;
/// <summary> Terminates the session only if LifeDuration is less than than the
/// difference between the last active time and now.</summary>
procedure TerminateInactiveSession; virtual;
/// <summary>returns true if session did not have any activity for number of seconds specified</summary>
function IsIdle(Seconds: Cardinal): Boolean;
function IsIdleMS(Milliseconds: Cardinal): Boolean;
/// <summary> Returns the session status </summary>
/// <remarks> Sets the session to expired if it was not already terminated, and it has been idle for Duration.
/// </remarks>
function GetSessionStatus: TDSSessionStatus; virtual;
procedure GetAuthRoleInternal(ServerMethod: TDSServerMethod; AuthManager : TDSCustomAuthenticationManager;
out AuthorizedRoles, DeniedRoles: TStrings);
public
/// <summary>Creates an anonymous session</summary>
constructor Create; overload; virtual;
constructor Create(const SessionName: string); overload; virtual;
constructor Create(const SessionName: string; const AUser: String); overload; virtual;
destructor Destroy; override;
/// <summary> Marks session be active </summary>
procedure MarkActivity;
/// <summary> Schedules an event in elapsed time
/// </summary>
/// <param name="event">Event to be run after the time elapses</param>
/// <param name="elapsedTime">Elapsed time in miliseconds</param>
procedure ScheduleUserEvent(Event: TDBXScheduleEvent; ElapsedTime: Integer);
/// <summary> Schedule a session termination event at FCreateDateTime + FDuration
/// </summary>
procedure ScheduleTerminationEvent;
/// <summary> Similar to ScheduleTerminationEvent, but will be called continually each time the event
/// is executed until the session has been idle for longer than LifeDuration.
/// </summary>
procedure ScheduleInactiveTerminationEvent;
/// <summary> Cancel the last shceduled event </summary>
procedure CancelScheduledEvent;
/// <summary> Authenticate a connection from the given properties and any data stored in the Session. </summary>
/// <remarks> Subclasses of TDSSession should override this, to be useful, but also call into this base
/// implementation (ignoring the return value of this base implementation.)
/// </remarks>
function Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): boolean; overload; virtual;
/// <summary> Checks that the user of the current session has authorization for the given method. </summary>
function Authorize(EventObject: TDSAuthorizeEventObject): boolean; overload; virtual;
/// <summary> Returns true if the given method requires authorization, false otherwise. </summary>
/// <remarks> For example 'DSMetadata.GetDatabase' is called when a SQLConnection to the server
/// is established, so checking for authorization would be redundant (and possibly falsly fail)
/// as the connection is already authenticated.
/// </remarks>
function RequiresAuthorization(MethodInfo: TDSMethodInfo): Boolean; virtual;
/// <summary> Get authorized and denied roles associated with server method </summary>
procedure GetAuthRoles(ServerMethod: TDSServerMethod; out AuthorizedRoles,
DeniedRoles: TStrings); virtual;
/// <summary> Convenience function which returns true if status is Active, Connected or Idle
/// </summary>
function IsValid: boolean; virtual;
/// <summary>
/// Generates a unique session id
/// </summary>
/// <remarks>
/// No assumptions should be made about the id structure or content other
/// than unicity on the current process
/// </remarks>
/// <return>session id as a string</return>
class function GenerateSessionId: string; static;
/// <summary>
/// To be called when session ends. The communication channel is closed.
/// </summary>
procedure Close; virtual;
/// <summary> Terminates the session </summary>
/// <remarks> It is exceptionally used when a session needs to be terminated
/// due to the overall process state. All memory is released as session ends
/// normally. Calling terminate may induce abnormal termination of
/// dependent mid-tier apps</remarks>
procedure Terminate; virtual;
/// <summary> Returns true if the session holds data for the given key. </summary>
function HasData(Key: String): Boolean;
/// <summary> Retrieve a value string stored in this session for the given key </summary>
function GetData(Key: String): String;
/// <summary> Store a value string in this session with the given key </summary>
procedure PutData(Key, Value: String);
/// <summary> Remove a value string from this session matching the given key </summary>
procedure RemoveData(Key: String);
/// <summary> Returns true if the session holds an Object for the given key. </summary>
function HasObject(Key: String): Boolean;
/// <summary> Retrieve a value Object stored in this session for the given key </summary>
function GetObject(Key: String): TObject;
/// <summary> Store an Object in this session with the given key </summary>
/// <remarks> Returns false is the object couldn't be inserted. (Invalid/in-use key) </remarks>
function PutObject(Key: String; Value: TObject): Boolean;
/// <summary> Remove an Object from this session matching the given key </summary>
function RemoveObject(Key: String; InstanceOwner: Boolean = True): TObject;
/// <summary> Returns the miliseconds since last activity </summary>
function ElapsedSinceLastActvity: Cardinal;
/// <summary> Returns the miliseconds remaining before the session expires </summary>
function ExpiresIn: Cardinal;
/// <summary> session duration in miliseconds </summary>
property LifeDuration: Integer read FDuration write FDuration;
/// <summary> session id </summary>
property Id: NativeInt read GetId;
/// <summary> Session status </summary>
property Status: TDSSessionStatus read GetSessionStatus;
/// <summary> For scheduled managed sessions, has the scheduled time</summary>
property StartDateTime: TDateTime read FStartDateTime;
/// <summary>Session's user name, empty for anonymous</summary>
property UserName: string read FUserName;
/// <summary>Session name, immutable</summary>
property SessionName: string read FSessionName;
/// <summary>User roles set through authentication</summary>
property UserRoles: TStrings read FUserRoles;
/// <summary>Cache for storing and retrieving previously executed commands and their results.</summary>
/// <remarks>Optionally used in conjunction with REST when a command execution results
/// in multiple complex typed result objects. (Streams, Tables, Objects.)
/// </remarks>
property ParameterCache: TDSSessionCache read FCache;
/// <summary> Holds a reference to the last result stream sent to a client. </summary>
/// <remarks> Used for REST, when sending a result stream back to the client, as there is no
/// easy way to tie in with the response sent to the client to know whent he stream is no longer needed.
/// The object stored here is a TObject instead of a stream to handle the case where there is an object
/// wrapping the stream which needs to be freed with the stream.
/// </remarks>
property LastResultStream: TObject read FLastResultStream write FLastResultStream;
/// <summary>Exposes the creator object. It can be the server transport, http service, etc</summary>
/// <remarks>It is used usually to distinguish between sessions in a Close event, or to extract more
/// metadata about the session context
/// </remarks>
property ObjectCreator: TObject read FCreator write FCreator;
end;
TDSAuthSession = class(TDSSession)
private
protected
FAuthManager : TDSCustomAuthenticationManager;
public
procedure GetAuthRoles(ServerMethod: TDSServerMethod; out AuthorizedRoles,
DeniedRoles: TStrings); override;
function Authorize(EventObject: TDSAuthorizeEventObject): boolean; override;
/// <summary> The Authentication manager held by this session. Used for
/// user (role) Authorization.
/// </summary>
property AuthManager: TDSCustomAuthenticationManager read FAuthManager;
end;
/// <summary> Session class for REST communication protocol.
/// It holds an instance of an authentication manager.
/// </summary>
TDSRESTSession = class(TDSAuthSession)
public
/// <summary> Creates an instance of a REST Session, passing in the
/// authentication manager to hold a reference to.
/// </summary>
constructor Create(AAuthManager: TDSCustomAuthenticationManager); virtual;
/// <summary> Extension of Authenticate to wrap the TCP authentication manager call
/// </summary>
function Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): boolean; override;
end;
/// <summary> Session class for HTTP communication protocol. It acts like a
/// proxy for the socket channel with the DS. It offers Open and Close
/// methods to handle the session life-cycle
/// </summary>
TDSTunnelSession = class(TDSAuthSession)
private
/// <summary>
/// User pointer
/// </summary>
FUserPointer: Pointer;
/// <summary>
/// User flag
/// </summary>
FUserFlag: Integer;
protected
procedure TerminateSession; override;
public
constructor Create; reintroduce;
destructor Destroy; override;
/// <summary>
/// To be called when the session starts. The communication channel is
/// being setup at thie moment.
/// </summary>
procedure Open; virtual; abstract;
/// <summary>
/// Reopens the socket channel toward a different location. All required parameters
/// are expected to be present in the argument
/// </summary>
/// <param name="DBXDatasnapProperties">connection properties</param>
procedure Reopen(DBXDatasnapProperties: TDBXDatasnapProperties); virtual;
/// <summary> Reads bytes from communication layer. </summary>
/// <remarks>If none are avaiable yet the call may be blocking. </remarks>
/// <param name="Buffer">Byte array buffer with capacity to store data</param>
/// <param name="Offset">Byte array index from where the read bytes are stored</param>
/// <param name="Count">Expected number of bytes to be read. It is assumed there
/// is enough capacity in the buffer area for them</param>
/// <return>Actual number of bytes being read, -1 on error</return>
function Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; virtual; abstract;
/// <summary> Sends bytes into the communication layer. </summary>
/// <remarks> The operation may be blocking until data is consumed by the mid-tier. </remarks>
/// <param name="Buffer">Byte array buffer with data to be written</param>
/// <param name="Offset">Index from the bytes are written</param>
/// <param name="Count">Number of bytes to be written. It is expected that
/// the buffer has enough capacity to match the parameter</param>
/// <return>Actual number of bytes being written</return>
function Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; virtual; abstract;
property UserPointer: Pointer read FUserPointer write FUserPointer;
property UserFlag: Integer read FUserFlag write FUserFlag;
end;
/// <summary> Manages the http session for a remote DS instance </summary>
TDSRemoteSession = class(TDSTunnelSession)
private
/// <summary>
/// Communication channel with the actual resources
/// </summary>
FSocketChannel: TDBXSocketChannel;
public
constructor Create(DBXDatasnapProperties: TDBXDatasnapProperties);
destructor Destroy; override;
procedure Open; override;
procedure Reopen(DBXDatasnapProperties: TDBXDatasnapProperties); override;
procedure Close; override;
procedure Terminate; override;
function Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
function Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
/// <summary> Extension of Authenticate to wrap the TCP authentication manager call
/// </summary>
function Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): boolean; override;
property SocketChannel: TDBXSocketChannel read FSocketChannel write FSocketChannel;
end;
/// <summary> User event for notification of session events, such as create and terminate.
/// </summary>
TDSSessionEventType = (SessionCreate, SessionClose);
/// <summary> User event for notification of session events, such as create and terminate.
/// </summary>
/// <remarks> Event type is used to specify what action has been done to the session,
/// The session itself, if type is SessionClose for example, could be in a partially invalid state.
/// </remarks>
TDSSessionEvent = reference to procedure(Sender: TObject;
const EventType: TDSSessionEventType;
const Session: TDSSession);
TDSSessionVisitor = reference to procedure(const Session: TDSSession);
/// <summary>Singleton that will manage the session objects</summary>
TDSSessionManager = class
type
TFactoryMethod = reference to function: TDSSession;
strict private
FSessionContainer: TDictionary<String, TDSSession>;
FListeners: TList<TDSSessionEvent>;
private
class var FInstance: TDSSessionManager;
/// <summary> Returns the session object based on its id
/// </summary>
/// <param name="SessionId">session identifier</param>
/// <return>a session object, nil if not found</return>
function GetSession(SessionId: string): TDSSession;
/// <summary> Returns the tunnel session object based on its id
/// </summary>
/// <param name="SessionId">session identifier</param>
/// <return>tunnel session object, nil if not found or is not a tunnel session</return>
function GetTunnelSession(SessionId: string): TDSTunnelSession;
function GetUniqueSessionId: string;
procedure TerminateSession(session: TDSSession); overload;
procedure CloseSession(session: TDSSession); overload;
/// <summary> Internal function for notifying the registered events
/// </summary>
procedure NotifyEvents(session: TDSSession; EventType: TDSSessionEventType);
procedure TerminateAllSessions(const ACreator: TObject;
AAllSessions: Boolean); overload;
public
constructor Create;
destructor Destroy; override;
function CreateSession<T: TDSSession>(factory: TFactoryMethod; userName: String): T; overload;
function CreateSession<T: TDSSession>(factory: TFactoryMethod; DoNotify: Boolean = True): T; overload;
/// <summary> Add the given session event to the list of events which gets
/// executed when a change occurrs with a session through this manager.
/// </summary>
procedure AddSessionEvent(Event: TDSSessionEvent);
/// <summary> Remove the given session event to the list of events which gets
/// executed when a change occurrs with a session through this manager.
/// </summary>
/// <returns> true if successfully removed, false otherwise. </returns>
function RemoveSessionEvent(Event: TDSSessionEvent): boolean;
/// <summary>Closes the session identified by argument
/// </summary>
/// <remarks> The session object is freed, no further access to it is expected
/// </remarks>
/// <param name="SessionId">session identifier</param>
procedure CloseSession(SessionId: string); overload;
/// <summary> Terminates all registered sessions for a given owner. Usually when the owner is taken
/// offline or being closed.
/// </summary>
procedure TerminateAllSessions(const ACreator: TObject); overload;
/// <summary> Terminates all registered sessions. Usually when the the server is stopped.
/// </summary>
procedure TerminateAllSessions; overload;
/// <summary> Iterates over all sessions and invokes the TDSSessionVisitor for each.
/// </summary>
procedure ForEachSession(AVisitor: TDSSessionVisitor);
/// <summary> Removes the session from session container and invokes session's Teminate method
/// </summary>
/// <remarks> Further session access will not be possible
/// </remarks>
/// <param name="SessionId">session unique name</param>
procedure TerminateSession(const sessionId: String); overload;
/// <summary> Returns number of open sessions
/// </summary>
/// <returns>number of open session</returns>
function GetSessionCount: Integer;
/// <summary>Removes the session from session container
/// </summary>
/// <param name="SessionId">session identifier</param>
function RemoveSession(SessionId: string): TDSSession;
/// <summary> Adds all open session keys to parameter container
/// </summary>
/// <param name="Container">string list</param>
procedure GetOpenSessionKeys(Container: TStrings); overload;
procedure GetOpenSessionKeys(Container: TStrings; ACreator: TObject); overload;
/// <summary> Returns the Session for the current thread.
/// </summary>
class function GetThreadSession: TDSSession;
/// <summary> Sets the given session as the session for the thread calling this function.
/// </summary>
class procedure SetAsThreadSession(Session: TDSSession);
/// <summary> Removes any session set to be the session for the current thread
/// </summary>
class procedure ClearThreadSession;
property Session[id: String]: TDSSession read GetSession;
property TunnelSession[id: String]: TDSTunnelSession read GetTunnelSession;
class property Instance: TDSSessionManager read FInstance;
end;
/// <summary> Synchronizes the local channel </summary>
TDSSynchronizedLocalChannel = class(TDBXLocalChannel)
private
FReadSemaphore: TSemaphore;
FLocalReadSemaphore: TSemaphore;
FWriteSemaphore: TSemaphore;
FLocalWriteSemaphore: TSemaphore;
FTerminated: boolean;
public
constructor Create(const ServerName: String);
destructor Destroy; override;
function Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
function WriteLocalData(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
function Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
function ReadLocalData(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
procedure Terminate;
end;
/// <summary> Consumes remote byte stream produced by a remote source. The
/// remote is proxied by a local session instance passed in the contructor.
/// </summary>
TDSLocalServer = class(TThread)
private
FErrorMsg: String;
FLocalChannel: TDBXLocalChannel;
FDBXProtocolHandler: TDBXProtocolHandler;
FSession: TDSSession;
protected
procedure Execute; override;
/// <summary> Processes the byte stream as it comes along
/// </summary>
/// <remarks> The tunnel session is synchronizing the read/write semaphores
/// </remarks>
procedure ConsumeByteStream;
public
constructor Create(ALocalChannel: TDBXLocalChannel; AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory;
AFilters: TTransportFilterCollection; Session: TDSSession);
destructor Destroy; override;
/// <summary> Returns true if the local server protocol failed at some point</summary>
/// <remarks>Error management is passive due to multi-threaded environment. It
/// is the responsability of the user thread to use this flag appropriately.
/// The error message can be acquired using ErrorMsg property.
/// </remarks>
/// <returns>true if the communication protocol exprienced an error</returns>
function HasError: Boolean;
/// <summary>Error message when HasError function returns true</summary>
property ErrorMsg: String read FErrorMsg;
end;
/// <summary> Manages the http session for a local DS instance </summary>
TDSLocalSession = class(TDSTunnelSession)
private
FFilters: TTransportFilterCollection;
FProtocolHandlerFactory: TDSJSONProtocolHandlerFactory;
FLocalChannel: TDSSynchronizedLocalChannel;
FDSLocalServer: TDSLocalServer;
public
constructor Create(AFilters: TTransportFilterCollection; AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory);
destructor Destroy; override;
procedure Open; override;
procedure Close; override;
procedure Terminate; override;
/// <summary> Extension of Authenticate to wrap the TCP authentication manager call
/// </summary>
function Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): boolean; override;
function Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
function Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
end;
TTunnelSessionEvent = procedure(Sender: TObject; Session: TDSTunnelSession; Content: TBytes;
var Count: Integer) of object;
/// <summary> Implements the HTTP tunneling logic. The tunnel accepts POST and
/// GET requests from HTTP channels and un-wraps or wraps the byte content from/for them.
/// POST is assimilated with a write operation, GET is assimilated with a READ.
/// The actual byte flow is handled by session's channel toward and from the
/// intranet resource.
/// </summary>
/// <remarks>
/// Class handles the session id generation, session management, session life cycle
/// </remarks>
TDSTunnelService = class
strict private
FFilters: TTransportFilterCollection;
FProtocolHandlerFactory: TDSJSONProtocolHandlerFactory;
FDSHostname: String;
FDSPort: Integer;
FHasLocalServer: Boolean;
private
FDBXProperties: TDBXDatasnapProperties;
FOnOpenSession: TTunnelSessionEvent;
FOnErrorOpenSession: TTunnelSessionEvent;
FOnCloseSession: TTunnelSessionEvent;
FOnWriteSession: TTunnelSessionEvent;
FOnReadSession: TTunnelSessionEvent;
FOnErrorWriteSession: TTunnelSessionEvent;
FOnErrorReadSession: TTunnelSessionEvent;
FDSAuthenticationManager: TDSCustomAuthenticationManager;
protected
/// <summary> True if the current session id signals the session closure
/// </summary>
/// <return>true if current session should be closed</return>
class function CanCloseSession(var id: string): boolean;
/// <summary> Creates a tunnel session based on the tunnel creation parameters
/// </summary>
/// <param name="Session">output tunnel session object</param>
/// <param name="RemoteIP">The connecting client's IP address</param>
procedure CreateSession(out Session: TDSTunnelSession; RemoteIP: String = ''); overload;
/// <summary> Creates a tunnel session based on the tunnel creation parameters
/// </summary>
/// <param name="Session">output tunnel session object</param>
/// <param name="ClientInfo">Info about the connecting client</param>
procedure CreateSession(out Session: TDSTunnelSession; ClientInfo: TDBXClientInfo); overload;
function GetSession(const SessionId: String): TDSTunnelSession;
/// <summary>Default implementation of the OpenSession event</summary>
/// <remarks>Event is triggered each time a session is opened successfully.
/// Default implementation delegates to OnOpenSession property if set</remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultOpenSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TBytes; var Count: Integer);
/// <summary>Default implementation of the ErrorOpenSession event</summary>
/// <remarks>Event is triggered when a session cannot be opened. Default implementation
/// delegates to OnOpenSessionError property if set, otherwise re-throws the
/// exception.</remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultErrorOpenSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TBytes; var Count: Integer);
/// <summary>Default implementation of the CloseSession event</summary>
/// <remarks>Event is triggered each time a session is closed successfully.
/// Default implementation delegates to OnCloseSession property if set</remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultCloseSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TBytes; var Count: Integer);
/// <summary>Default implementation of the WriteSession event</summary>
/// <remarks>Event is triggered each time a session performs a write operation successfully.
/// Default implementation delegates to OnWriteSession property if set</remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultWriteSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TBytes; var Count: Integer);
/// <summary>Default implementation of the ReadSession event</summary>
/// <remarks>Event is triggered each time a session performs a read operation successfully.
/// Default implementation delegates to OnReadSession property if set</remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultReadSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TBytes; var Count: Integer);
/// <summary>Default implementation of the ErrorWriteSession event</summary>
/// <remarks>Event is triggered each time a session fails to write data.
/// Default implementation delegates to OnErrorWriteSession property if set, otherwise it
/// rethrows the exception.
/// </remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultErrorWriteSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TBytes; var Count: Integer);
/// <summary>Default implementation of the ErrorReadSession event</summary>
/// <remarks>Event is triggered each time a session fails to write data.
/// Default implementation delegates to OnErrorReadSession property if set, otherwise it
/// rethrows the exception.
/// </remarks>
/// <param name="Sender">Event sender</param>
/// <param name="Session">Tunnel session instance that manages current comunication</param>
/// <param name="Content">Bytes content</param>
/// <param name="Count">Byte content size (in bytes)</param>
procedure DefaultErrorReadSessionEvent(Sender: TObject; Session: TDSTunnelSession;
Content: TBytes; var Count: Integer);
procedure SetDSHostname(AHostname: String);
procedure SetDSPort(APort: Integer);
public
/// <summary> Constructor with hostname and port to write and read the byte stream
/// </summary>
/// <param name="DSHostname">datasnap server machine</param>
/// <param name="DSPort">datasnap server port it listens to</param>
/// <param name="AFilters">the filters collection</param>
/// <param name="AProtocolHandlerFactory">the protocol handler factory</param>
constructor Create(DSHostname: String; DSPort: Integer; AFilters: TTransportFilterCollection;
AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory); virtual;
destructor Destroy; override;
/// <summary>Pass through of user credentials</summary>
/// <param name="userName">user name</param>
/// <param name="userPass">user password</param>
procedure AddUserCredentials(const userName: String; const userPass: String);
/// <summary> Terminates all registered sessions. Usually when the server is taken
/// offline or being closed.
/// </summary>
procedure TerminateAllSessions;
/// <summary> Terminates session with session id among the input parameters
/// </summary>
/// <remarks> Further session access will not be possible
/// </remarks>
/// <param name="Params">Parameter collection</param>
class procedure TerminateSession(const Params: TStrings); overload;
/// <summary> Returns number of open sessions
/// </summary>
/// <returns>number of open session</returns>
function GetSessionCount: Integer;
/// <summary>Closes the session identified by argument
/// </summary>
/// <remarks> The session object is freed, no further access to it is expected
/// </remarks>
/// <param name="SessionId">session identifier</param>
procedure CloseSession(SessionId: string); overload;
/// <summary> Adds all open session keys to parameter container
/// </summary>
/// <param name="Container">string list</param>
procedure GetOpenSessionKeys(Container: TStrings);
/// <summary>
/// Initializes the session pointed to by the specified parameter value for 'dss'
/// If the value of the 'dss' parameter is 0, then a new session will be created and the
/// value for dss in the given params will be replaced.
/// </summary>
function InitializeSession(Params: TStrings; RemoteIP: String = ''): TDSTunnelSession; overload;
function InitializeSession(Params: TStrings; ClientInfo: TDBXClientInfo): TDSTunnelSession; overload;
/// <summary>
/// Handles the POST requests. They are assimilated to write operations.
/// The response consists in the session id and the actual amount of bytes
/// successfully delivered to the destination.
/// </summary>
/// <param name="Params">HTTP parameters (name=value) that provide the session id
/// (dss) and eventually the content size (c). The content is expected to be available
/// in the byte stream. A session id zero (0) is equivalent to a new session.
/// The code will generate a new session id that will be returned as content
/// in the JSON object.
/// </param>
/// <param name="Content">Byte content to be forwarded to the session's communication channel</param>
/// <param name="JsonResponse">Output parameters with the session id and actual data write size.
/// <param name="CloseConnection">true if server has to signal client to close the connection</param>
/// Upon success the response is: {"response":[[sessionId],[count]]
/// </param>
procedure ProcessPOST(Params: TStrings; Content: TBytes; out JsonResponse: TJSONValue; out CloseConnection: boolean);
/// <summary>
/// Handles the GET requests. They are assimilated to the read operations. The
/// response is returned as a byte stream.
/// </summary>
/// <param name="Params">Request parameters with session id (dss) and expected byte
/// count to be read (c).
/// </param>
/// <param name="Len">Actual number of bytes read</param>
/// <param name="CloseConnection">true if server has to signal client to close the connection</param>
/// <return>byte stream</return>
function ProcessGET(Params: TStrings; var Len: Integer; out CloseConnection: boolean): TStream;
/// <summary> Returns true if the request parameters provide user name and paasword
/// </summary>
/// <returns>true if the request needs authentication</returns>
function NeedsAuthentication(Params: TStrings): Boolean;
/// <summary>Remote host name where the DataSnap Server will process the requests
/// </summary>
property DSHostname: String read FDSHostname write SetDSHostname;
/// <summary>Remote DataSnap port that processes the requests</summary>
property DSPort: Integer read FDSPort write SetDSPort;
/// <summary>True if the DataSnap process is in process.</summary>
/// <remarks>In process servers have precedence over the remote ones. Hence, if
/// property is true DSHostname and DSPort will be ignored.
/// </remarks>
property HasLocalServer: Boolean read FHasLocalServer write FHasLocalServer;
/// <summary>Communication filters such as compression or encryption</summary>
property Filters: TTransportFilterCollection read FFilters write FFilters;
/// <summary>Factory that will provide the protocol handler</summary>
property ProtocolHandlerFactory: TDSJSONProtocolHandlerFactory read FProtocolHandlerFactory
write FProtocolHandlerFactory;
/// <summary>
/// Event invoked after the tunnel session was open
/// </summary>
property OnOpenSession: TTunnelSessionEvent read FOnOpenSession write FOnOpenSession;
/// <summary>
/// Event invoked if a session cannot open
/// </summary>
property OnErrorOpenSession: TTunnelSessionEvent read FOnErrorOpenSession write FOnErrorOpenSession;
/// <summary> Event invoked before the session is closed
/// </summary>
property OnCloseSession: TTunnelSessionEvent read FOnCloseSession write FOnCloseSession;
/// <summary> Event invoked after the data has been written into the tunnel channel
/// </summary>
property OnWriteSession: TTunnelSessionEvent read FOnWriteSession write FOnWriteSession;
/// <summary> Event invoked after the data has been read from the tunnel channel
/// </summary>
property OnReadSession: TTunnelSessionEvent read FOnReadSession write FOnReadSession;
/// <summary> Event invoked if channel write failed because of connection error
/// </summary>
property OnErrorWriteSession: TTunnelSessionEvent read FOnErrorWriteSession write FOnErrorWriteSession;
/// <summary> Event invoked if channel read failed because of connection error or timeout
/// </summary>
property OnErrorReadSession: TTunnelSessionEvent read FOnErrorReadSession write FOnErrorReadSession;
/// <summary> Returns number of open sessions
/// </summary>
property SessionCount: Integer read GetSessionCount;
/// <summary> The Authentication manager for use with this tunnel service
/// </summary>
property DSAuthenticationManager: TDSCustomAuthenticationManager read FDSAuthenticationManager
write FDSAuthenticationManager;
end;
/// <summary> Session class for TCP communication protocol.
/// It holds an instance of an authentication manager.
/// </summary>
TDSTCPSession = class(TDSAuthSession)
public
/// <summary> Creates an instance of a TCP Session, passing in the
/// authentication manager to hold a reference to.
/// </summary>
constructor Create(AAuthManager: TDSCustomAuthenticationManager); overload; virtual;
constructor Create(AAuthManager: TObject); overload; virtual;
/// <summary> Extension of Authenticate to wrap the TCP authentication manager call
/// </summary>
function Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): boolean; override;
end;
implementation
uses
{$IFNDEF POSIX}
Winapi.ActiveX,
System.Win.ComObj,
Winapi.Windows,
{$ELSE}
Macapi.CoreServices,
{$ENDIF}
Data.DBXClientResStrs,
Data.DBXJSONCommon,
Data.DBXPlatform,
Data.DBXTransportFilter,
IPPeerAPI,
System.StrUtils;
const
CMD_EXECUTE = 'execute';
CMD_ERROR = 'error';
QP_DSS = 'dss';
QP_COUNT = 'c';
DRIVER_NAME = 'Datasnap';
NULL = 'null';
PARAMETERS_PAIR = '_parameters';
ThreadVar
VDSSession: TDSSession; {Session for the current thread}
type
TAnonymousBlock = reference to procedure;
procedure Synchronized(monitor: TObject; proc: TAnonymousBlock);
begin
TMonitor.Enter(monitor);
try
proc;
finally
TMonitor.Exit(monitor);
end;
end;
{TDSTunnelSession}
constructor TDSTunnelSession.Create;
begin
inherited;
FUserFlag := 0;
FUserPointer := nil;
end;
destructor TDSTunnelSession.Destroy;
begin
inherited;
end;
procedure TDSTunnelSession.Reopen(DBXDatasnapProperties: TDBXDatasnapProperties);
begin
// do nothing
end;
procedure TDSTunnelSession.TerminateSession;
begin
inherited;
end;
{TDSRemoteSession}
constructor TDSRemoteSession.Create(DBXDatasnapProperties: TDBXDatasnapProperties);
begin
inherited Create;
FSocketChannel := TDBXSocketChannel.Create;
FSocketChannel.DBXProperties := DBXDatasnapProperties;
end;
destructor TDSRemoteSession.Destroy;
begin
FreeAndNil(FSocketChannel);
inherited;
end;
procedure TDSRemoteSession.Open;
begin
FSocketChannel.Open;
FStatus := Connected;
end;
procedure TDSRemoteSession.Reopen(DBXDatasnapProperties: TDBXDatasnapProperties);
begin
try
Close;
finally
FreeAndNil(FSocketChannel);
end;
FSocketChannel := TDBXSocketChannel.Create;
FSocketChannel.DBXProperties := DBXDatasnapProperties;
Open;
end;
function TDSRemoteSession.Authenticate(
const AuthenticateEventObject: TDSAuthenticateEventObject;
connectionProps: TDBXProperties): boolean;
begin
Inherited;
{Authentication will be done elsewhere for HTTP}
exit(True);
end;
procedure TDSRemoteSession.Close;
begin
Inherited;
FSocketChannel.Close;
end;
procedure TDSRemoteSession.Terminate;
begin
Inherited;
FSocketChannel.Terminate;
end;
function TDSRemoteSession.Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer;
begin
Result := FSocketChannel.Read(Buffer, Offset, Count);
end;
function TDSRemoteSession.Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer;
begin
Result := FSocketChannel.Write(Buffer, Offset, Count);
end;
{TDSSynchronizedLocalChannel}
constructor TDSSynchronizedLocalChannel.Create(const ServerName: string);
begin
inherited Create(ServerName);
FReadSemaphore := TSemaphore.Create(nil, 0, MaxInt, '');
FLocalReadSemaphore := TSemaphore.Create(nil, 1, MaxInt, '');
FWriteSemaphore := TSemaphore.Create(nil, 0, MaxInt, '');
FLocalWriteSemaphore := TSemaphore.Create(nil, 1, MaxInt, '');
FTerminated := false;
end;
destructor TDSSynchronizedLocalChannel.Destroy;
begin
FreeAndNil(FReadSemaphore);
FreeAndNil(FWriteSemaphore);
FreeAndNil(FLocalReadSemaphore);
FreeAndNil(FLocalWriteSemaphore);
inherited;
end;
procedure TDSSynchronizedLocalChannel.Terminate;
begin
FTerminated := true;
FLocalWriteSemaphore.Release;
FLocalReadSemaphore.Release;
FWriteSemaphore.Release;
FReadSemaphore.Release;
end;
function TDSSynchronizedLocalChannel.Read(const Buffer: TBytes; const Offset: Integer;
const Count: Integer): Integer;
var
status: TWaitResult;
begin
status := FReadSemaphore.WaitFor(INFINITE);
if status = wrError then
Raise TDBXError.Create(0, Format(SWaitFailure, ['Read']));
if status = wrTimeout then
Raise TDBXError.Create(0, Format(SWaitTimeout, ['Read']));
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
Result := inherited Read(Buffer, Offset, Count);
// if all written data was consumed allow subsequent write local data
if not HasWriteData then
FLocalWriteSemaphore.Release
else
FReadSemaphore.Release;
end;
function TDSSynchronizedLocalChannel.WriteLocalData(const Buffer: TBytes; const Offset: Integer;
const Count: Integer): Integer;
var
status: TWaitResult;
begin
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
status := FLocalWriteSemaphore.WaitFor(INFINITE);
if status = wrError then
Raise TDBXError.Create(0, Format(SWaitFailure, ['WriteLocalData']));
if status = wrTimeout then
Raise TDBXError.Create(0, Format(SWaitTimeout, ['WriteLocalData']));
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
Result := inherited WriteLocalData(Buffer, Offset, Count);
FReadSemaphore.Release;
end;
function TDSSynchronizedLocalChannel.Write(const Buffer: TBytes; const Offset: Integer;
const Count: Integer): Integer;
var
status: TWaitResult;
begin
status := FLocalReadSemaphore.WaitFor(INFINITE);
if status = wrError then
Raise TDBXError.Create(0, Format(SWaitFailure, ['Write']));
if status = wrTimeout then
Raise TDBXError.Create(0, Format(SWaitTimeout, ['Write']));
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
Result := inherited Write(Buffer, Offset, Count);
FWriteSemaphore.Release;
end;
function TDSSynchronizedLocalChannel.ReadLocalData(const Buffer: TBytes; const Offset: Integer;
const Count: Integer): Integer;
var
status: TWaitResult;
begin
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
status := FWriteSemaphore.WaitFor(INFINITE);
if status = wrError then
Raise TDBXError.Create(0, Format(SWaitFailure, ['ReadLocalData']));
if status = wrTimeout then
Raise TDBXError.Create(0, Format(SWaitTimeout, ['ReadLocalData']));
if FTerminated then
Raise TDBXError.Create(0, SWaitTerminated);
Result := inherited ReadLocalData(Buffer, Offset, Count);
if not HasReadData then
FLocalReadSemaphore.Release
else
FWriteSemaphore.Release;
end;
{TDSLocalSession}
constructor TDSLocalSession.Create(AFilters: TTransportFilterCollection; AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory);
begin
inherited Create;
FFilters := AFilters;
FProtocolHandlerFactory := AProtocolHandlerFactory;
end;
destructor TDSLocalSession.Destroy;
begin
FFilters := nil; // no ownership
FProtocolHandlerFactory := nil; // no ownership
if not FDSLocalServer.Terminated then
FDSLocalServer.Terminate;
FreeAndNil(FDSLocalServer);
inherited
end;
procedure TDSLocalSession.Open;
var
RemoteIP: String;
ClientInfo: TDBXClientInfo;
begin
RemoteIP := GetData('RemoteIP');
if RemoteIP = EmptyStr then
RemoteIP := 'local';
FLocalChannel := TDSSynchronizedLocalChannel.Create(RemoteIP);
with ClientInfo do
begin
IpAddress := RemoteIP;
Protocol := GetData('CommunicationProtocol');
AppName := GetData('RemoteAppName');
end;
FLocalChannel.ChannelInfo.ClientInfo := ClientInfo;
// start DS local
FDSLocalServer := TDSLocalServer.Create(FLocalChannel, FProtocolHandlerFactory, FFilters, Self);
FStatus := Connected;
end;
function TDSLocalSession.Authenticate(
const AuthenticateEventObject: TDSAuthenticateEventObject;
connectionProps: TDBXProperties): boolean;
begin
Inherited;
if FAuthManager <> nil then
exit(FAuthManager.Authenticate(AuthenticateEventObject, connectionProps));
exit(True);
end;
procedure TDSLocalSession.Close;
begin
// stop the DS local
FStatus := Closed;
FLocalChannel.Terminate;
FDSLocalServer.Terminate;
if not FDSLocalServer.Finished then
FDSLocalServer.WaitFor;
end;
procedure TDSLocalSession.Terminate;
begin
Close;
end;
function TDSLocalSession.Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer;
begin
Result := FLocalChannel.ReadLocalData(Buffer, Offset, Count);
if (FStatus = Connected) and FDSLocalServer.HasError then
Raise TDBXError.Create(0, FDSLocalServer.ErrorMsg);
end;
function TDSLocalSession.Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer;
begin
Result := FLocalChannel.WriteLocalData(Buffer, Offset, Count);
if (FStatus = Connected) and FDSLocalServer.HasError then
Raise TDBXError.Create(0, FDSLocalServer.ErrorMsg);
end;
{TDSLocalServer}
constructor TDSLocalServer.Create(ALocalChannel: TDBXLocalChannel; AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory;
AFilters: TTransportFilterCollection; Session: TDSSession);
var
FilterChannel: TDBXFilterSocketChannel;
begin
inherited Create(false);
FSession := Session;
FLocalChannel := ALocalChannel;
FilterChannel := TDBXFilterSocketChannel.Create(AFilters);
FilterChannel.Channel := FLocalChannel;
FDBXProtocolHandler := AProtocolHandlerFactory.CreateProtocolHandler(FilterChannel);
end;
destructor TDSLocalServer.Destroy;
begin
FreeAndNil( FDBXProtocolHandler );
FLocalChannel := nil; // soft reference
end;
procedure TDSLocalServer.ConsumeByteStream;
begin
try
FDBXProtocolHandler.HandleProtocol;
except
on ex: Exception do
if not Terminated then
begin
FErrorMsg := ex.Message;
Terminate;
end;
end;
end;
procedure TDSLocalServer.Execute;
begin
{$IFNDEF POSIX}
if CoInitFlags = -1 then
CoInitializeEx(nil, COINIT_MULTITHREADED)
else
CoInitializeEx(nil, CoInitFlags);
{$ENDIF}
try
if FSession <> nil then
TDSSessionManager.SetAsThreadSession(FSession);
ConsumeByteStream;
finally
{$IFNDEF POSIX}
CoUninitialize;
{$ENDIF}
end
end;
function TDSLocalServer.HasError: Boolean;
begin
Result := FErrorMsg <> EmptyStr;
end;
{TDSTunnelService}
constructor TDSTunnelService.Create(DSHostname: String; DSPort: Integer; AFilters: TTransportFilterCollection;
AProtocolHandlerFactory: TDSJSONProtocolHandlerFactory );
begin
FDSHostname := DSHostname;
FDSPort := DSPort;
FFilters := AFilters;
FProtocolHandlerFactory := AProtocolHandlerFactory;
FDBXProperties := TDBXDatasnapProperties.Create(nil);
FDBXProperties.Values[ TDBXPropertyNames.DriverName ] := DRIVER_NAME;
FDBXProperties.Values[ TDBXPropertyNames.HostName ] := FDSHostname;
FDBXProperties.Values[ TDBXPropertyNames.Port ] := IntToStr( FDSPort );
end;
destructor TDSTunnelService.Destroy;
begin
FreeAndNil(FDBXProperties);
FFilters := nil; // no ownership
FProtocolHandlerFactory := nil; // no ownership
inherited;
end;
procedure TDSTunnelService.AddUserCredentials(const userName, userPass: String);
begin
FDBXProperties.DSAuthUser := userName;
FDBXProperties.DSAuthPassword := userPass;
end;
class function TDSTunnelService.CanCloseSession(var id: string): boolean;
begin
Result := StringStartsWith(id, '-');
if Result then
Delete(id, 1, 1);
end;
procedure TDSTunnelService.CreateSession(out Session: TDSTunnelSession; RemoteIP: String);
var
ClientInfo: TDBXClientInfo;
begin
ClientInfo.IpAddress := RemoteIP;
CreateSession(Session, ClientInfo);
end;
procedure TDSTunnelService.CreateSession(out Session: TDSTunnelSession; ClientInfo: TDBXClientInfo);
var
Len: Integer;
begin
Session := TDSSessionManager.Instance.CreateSession<TDSTunnelSession>(function: TDSSession begin
if HasLocalServer then
Result := TDSLocalSession.Create(FFilters, FProtocolHandlerFactory)
else
begin
Result := TDSRemoteSession.Create(FDBXProperties);
end;
Result.ObjectCreator := self;
if ClientInfo.IpAddress <> EmptyStr then
Result.PutData('RemoteIP', ClientInfo.IpAddress);
if ClientInfo.Protocol <> EmptyStr then
Result.PutData('CommunicationProtocol', ClientInfo.Protocol);
if ClientInfo.AppName <> EmptyStr then
Result.PutData('RemoteAppName', ClientInfo.AppName);
Result.PutData('ProtocolSubType', 'tunnel');
end, FDBXProperties.UserName);
try
Session.FAuthManager := FDSAuthenticationManager;
Session.Open;
except
on ex: Exception do
try
DefaultErrorOpenSessionEvent(ex, Session, nil, Len);
except
TDSSessionManager.Instance.RemoveSession(Session.SessionName);
FreeAndNil(Session);
raise;
end;
end;
DefaultOpenSessionEvent(self, Session, nil, Len);
end;
procedure TDSTunnelService.CloseSession(SessionId: string);
var
Session: TDSSession;
Len: Integer;
begin
Session := TDSSessionManager.Instance.Session[SessionId];
if (Session <> nil) and (Session is TDSTunnelSession) then
begin
try
DefaultCloseSessionEvent(self, TDSTunnelSession(Session), nil, Len);
finally
TDSSessionManager.Instance.CloseSession(SessionId);
end
end
end;
procedure TDSTunnelService.TerminateAllSessions;
var
I: Integer;
openSessions: TStringList;
begin
openSessions := TStringList.Create;
try
TDSSessionManager.Instance.GetOpenSessionKeys(openSessions, self);
for I := 0 to openSessions.Count - 1 do
TDSSessionManager.Instance.TerminateSession(openSessions[I]);
finally
openSessions.Free;
end;
end;
class procedure TDSTunnelService.TerminateSession(const Params: TStrings);
var
SessionId: string;
begin
SessionId := Params.Values[QP_DSS];
if (SessionId <> '') and (SessionId <> '0') then
TDSSessionManager.Instance.TerminateSession(SessionId);
end;
function TDSTunnelService.GetSession(const SessionId: String): TDSTunnelSession;
begin
Result := TDSSessionManager.Instance.TunnelSession[SessionId];
end;
function TDSTunnelService.GetSessionCount: Integer;
var
openSessions: TStringList;
begin
openSessions := TStringList.Create;
try
TDSSessionManager.Instance.GetOpenSessionKeys(openSessions, self);
Result := openSessions.Count;
finally
openSessions.Free;
end;
end;
function TDSTunnelService.InitializeSession(Params: TStrings; RemoteIP: String): TDSTunnelSession;
var
ClientInfo: TDBXClientInfo;
begin
ClientInfo.IpAddress := RemoteIp;
Result := InitializeSession(Params, ClientInfo);
end;
function TDSTunnelService.InitializeSession(Params: TStrings; ClientInfo: TDBXClientInfo): TDSTunnelSession;
var
Session: TDSTunnelSession;
PSessionId: String;
begin
Session := nil;
PSessionId := Params.Values[QP_DSS];
if PSessionId = '0' then
begin
// first time - implicit session creation
CreateSession(Session, ClientInfo);
PSessionId := Session.SessionName;
// save the session id for error processing
Params.Values[QP_DSS] := PSessionId;
end
else
// get the session object
Session := GetSession(PSessionId);
if Session <> nil then
//associate session and thread
TDSSessionManager.SetAsThreadSession(Session);
Result := Session;
end;
function TDSTunnelService.NeedsAuthentication(Params: TStrings): Boolean;
var
PSessionId: String;
begin
PSessionId := Params.Values[QP_DSS];
Result := PSessionId = '0';
end;
procedure TDSTunnelService.GetOpenSessionKeys(Container: TStrings);
begin
TDSSessionManager.Instance.GetOpenSessionKeys(Container, self);
end;
procedure TDSTunnelService.ProcessPOST(Params: TStrings; Content: TBytes; out JsonResponse: TJSONValue;
out CloseConnection: boolean);
var
Session: TDSTunnelSession;
PSessionId: String;
PLen: String;
Len: Integer;
JsonParams: TJSONArray;
begin
// get the session id
PSessionId := Params.Values[QP_DSS];
if PSessionId <> '' then
begin
// close session request?
if CanCloseSession(PSessionId) then
begin
CloseConnection := true;
CloseSession(PSessionId);
end
else
begin
CloseConnection := false;
//creates or looks-up session for given session ID.
//content of Params will be replaced for 'dss' if session is created
Session := InitializeSession(Params);
if Session <> nil then
begin
//associate session and thread
TDSSessionManager.SetAsThreadSession(Session);
// number of bytes to be written
PLen := Params.Values[QP_COUNT];
if PLen = '' then
Len := Length(Content)
else
Len := StrToInt(PLen);
try
// write Len bytes
Len := Session.Write(Content, 0, Len);
except
on ex: Exception do
DefaultErrorWriteSessionEvent(ex, Session, Content, Len);
end;
JsonResponse := TJSONObject.Create;
JsonParams := TJSONArray.Create;
TJSONObject(JsonResponse).AddPair(
TJSONPair.Create(TJSONString.Create('response'),
JsonParams));
JsonParams.AddElement(TJSONString.Create(PSessionId));
JsonParams.AddElement(TJSONNumber.Create(Len));
//dis-associate the session from the thread
TDSSessionManager.ClearThreadSession;
DefaultWriteSessionEvent(self, Session, Content, Len);
end
else
raise TDSServiceException.Create(SNoSessionFound);
end;
end
else
raise TDSServiceException.Create(Format(SNoSessionInRequest, [QP_DSS]));
end;
function TDSTunnelService.ProcessGET(Params: TStrings; var Len: Integer; out CloseConnection: boolean): TStream;
var
Session: TDSTunnelSession;
PSessionId: String;
PLen: String;
Buff: TBytes;
Count: Integer;
begin
Result := nil;
// get the session id
PSessionId := Params.Values[QP_DSS];
if PSessionId <> '' then
begin
// close session request?
if CanCloseSession(PSessionId) then
begin
CloseSession(PSessionId);
CloseConnection := true;
end
else
begin
CloseConnection := false;
//creates or looks-up session for given session ID.
//content of Params will be replaced for 'dss' if session is created
Session := InitializeSession(Params);
if Session <> nil then
begin
//associate session and thread
TDSSessionManager.SetAsThreadSession(Session);
// number of bytes to be read
PLen := Params.Values[QP_COUNT];
if PLen = '' then
raise TDSServiceException.Create(Format(SNoCountParam, [QP_COUNT]))
else
Count := StrToInt(PLen);
SetLength(Buff, Count);
Len := Count;
try
// read Len bytes
Len := Session.Read(Buff, 0, Count);
except
on ex: Exception do
DefaultErrorReadSessionEvent(ex, Session, Buff, Len);
end;
//dis-associate the session from the thread
TDSSessionManager.ClearThreadSession;
DefaultReadSessionEvent(self, Session, Buff, Len);
if Len < Count then
SetLength(Buff, Len);
// write then into the stream
Result := TBytesStream.Create(Buff);
end
else
raise TDSServiceException.Create(SNoSessionFound);
end;
end
else
raise TDSServiceException.Create(Format(SNoSessionInRequest, [QP_DSS]));
end;
procedure TDSTunnelService.DefaultOpenSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TBytes; var Count: Integer);
begin
if Assigned(FOnOpenSession) then
FOnOpenSession(Sender, Session, Content, Count);
end;
procedure TDSTunnelService.DefaultErrorOpenSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TBytes; var Count: Integer);
begin
if Assigned(FOnErrorOpenSession) then
FOnErrorOpenSession(Sender, Session, Content, Count)
else if Sender is Exception then
raise TDSServiceException.Create(Exception(Sender).Message)
else
raise TDSServiceException.Create(SCommunicationErr);
end;
procedure TDSTunnelService.DefaultCloseSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TBytes; var Count: Integer);
begin
if Assigned(FOnCloseSession) then
FOnCloseSession(Sender, Session, Content, Count)
end;
procedure TDSTunnelService.DefaultWriteSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TBytes; var Count: Integer);
begin
if Assigned(FOnWriteSession) then
FOnWriteSession(Sender, Session, Content, Count)
end;
procedure TDSTunnelService.DefaultReadSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TBytes; var Count: Integer);
begin
if Assigned(FOnReadSession) then
FOnReadSession(Sender, Session, Content, Count)
end;
procedure TDSTunnelService.DefaultErrorWriteSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TBytes; var Count: Integer);
begin
if Assigned(FOnErrorWriteSession) then
FOnErrorWriteSession(Sender, Session, Content, Count)
else if Sender is Exception then
raise TDSServiceException.Create(Exception(Sender).Message)
else
raise TDSServiceException.Create(SCommunicationErr);
end;
procedure TDSTunnelService.DefaultErrorReadSessionEvent(Sender: TObject; Session: TDSTunnelSession; Content: TBytes; var Count: Integer);
begin
if Assigned(FOnErrorReadSession) then
FOnErrorReadSession(Sender, Session, Content, Count)
else if Sender is Exception then
raise TDSServiceException.Create(Exception(Sender).Message)
else
raise TDSServiceException.Create(SCommunicationErr);
end;
procedure TDSTunnelService.SetDSHostname(AHostname: string);
begin
FDSHostname := AHostname;
FDBXProperties.Values[ TDBXPropertyNames.HostName ] := FDSHostname;
end;
procedure TDSTunnelService.SetDSPort(APort: Integer);
begin
FDSPort := APort;
FDBXProperties.Values[ TDBXPropertyNames.Port ] := IntToStr( FDSPort );
end;
{TDSService}
constructor TDSService.Create(dsServerName, dsHostname: String; dsPort: Integer; AuthUser, AuthPassword: String);
begin
Create(dsServerName, dsHostname, dsPort, AuthUser, AuthPassword, '');
end;
constructor TDSService.Create(dsServerName, dsHostname: String; dsPort: Integer; AuthUser, AuthPassword, AIPImplementationID: String);
begin
inherited Create;
FDBXProperties := TDBXDatasnapProperties.Create(nil);
if DSServerName = EmptyStr then
begin
FDBXProperties.Values[ TDBXPropertyNames.DriverName ] := DRIVER_NAME;
FDBXProperties.Values[ TDBXPropertyNames.HostName ] := dsHostname;
FDBXProperties.Values[ TDBXPropertyNames.Port ] := IntToStr( dsPort );
FLocalConnection := false;
end
else
begin
FDBXProperties.Values[ TDBXPropertyNames.DriverName ] := DSServerName;
FLocalConnection := true;
end;
FDBXProperties.DSAuthUser := AuthUser;
FDBXProperties.DSAuthPassword := AuthPassword;
FDBXProperties.Values[ TDBXPropertyNames.IPImplementationID ] := AIPImplementationID;
StreamAsJSON := False;
end;
destructor TDSService.Destroy;
begin
FDBXProperties.Free;
inherited;
end;
procedure TDSService.ProcessRequest(const Request: TJSONArray; ResponseHandler: TRequestCommandHandler);
var
JsonCmd: TJSONString;
I: Integer;
begin
for I := 0 to Request.Size - 1 do
begin
JsonCmd := TJSONObject(Request.Get(I)).Get(0).JsonString;
if JsonCmd.Value = CMD_EXECUTE then
begin
try
Execute(TJSONObject(TJSONObject(request.Get(I)).Get(0).JsonValue), ResponseHandler);
except
on ex: Exception do
ResponseHandler.AddCommandError(ex.Message);
end;
end
else
begin
ResponseHandler.AddCommandError(Format(SInvalidInternalCmd, [JsonCmd.Value]));
end;
end;
end;
function TDSService.GetInputParameterInstance(JsonParam: TJSONValue; Parameter: TDBXParameter;
var InstanceOwner: Boolean): TJSONValue;
var
ParameterType: Integer;
ParamDirection: TDBXParameterDirection;
begin
//unless cloned, result will be the same as the value passed in
Result := JsonParam;
InstanceOwner := False;
ParameterType := Parameter.DataType;
ParamDirection := Parameter.ParameterDirection;
//potentially clone the JsonParam, depending on if its value will be
//returned in the response (var param) and if it is a complex type that
//isn't cloned by JSONToDBX
if (ParamDirection = TDBXParameterDirections.InOutParameter) then
begin
if JsonParam is TJSONObject then
begin
if (ParameterType = TDBXDataTypes.JsonValueType) then
begin
if Parameter.Value.ValueType.SubType <> TDBXDataTypes.UserSubType then
InstanceOwner := True;
end
else if (ParameterType = TDBXDataTypes.TableType) then
InstanceOwner := True;
end
else if JsonParam is TJSONArray then
InstanceOwner := True;
if InstanceOwner then
Result := TJSONValue(JsonParam.Clone);
end;
end;
procedure TDSService.Execute(const Request: TJSONObject; ResponseHandler: TRequestCommandHandler);
var
DBXConnection: TDBXConnection;
DBXCommand: TDBXCommand;
JsonParams: TJSONArray;
JsonParam: TJSONValue;
I, J: Integer;
Command: String;
ParamDirection: TDBXParameterDirection;
OwnParams: boolean;
DidClone: boolean;
begin
DBXCommand := nil;
OwnParams := false;
JsonParams := nil;
DBXConnection := TDBXConnectionFactory.GetConnectionFactory.GetConnection(FDBXProperties);
try
DBXCommand := DBXConnection.CreateCommand;
DBXCommand.CommandType := TDBXCommandTypes.DSServerMethod;
Command := Request.Get(0).JsonString.Value;
DBXCommand.Text := Command;
DBXCommand.Prepare;
JsonParams := TJSONArray(Request.Get(0).JsonValue);
if JsonParams.Size > DBXCommand.Parameters.Count then
begin
// too many parameters
Raise TDSServiceException.Create(Format(STooManyParameters, [Command, DBXCommand.Parameters.Count,
JsonParams.Size]));
end;
// populate input parameters - skip the output ones
J := 0;
for I := 0 to DBXCommand.Parameters.Count - 1 do
begin
DidClone := False;
ParamDirection := DBXCommand.Parameters[I].ParameterDirection;
if (ParamDirection = TDBXParameterDirections.InOutParameter) or
(ParamDirection = TDBXParameterDirections.InParameter) then
begin
// if less input arguments are provided the rest are assumed to be nil
if J >= jsonParams.Size then
JsonParam := nil
else
begin
JsonParam := JsonParams.Get(J);
//in some cases, we will want to use a cloned instance of JsonParam, this helper
//class assists with that... returning either the same instance or a cloned instance.
JsonParam := GetInputParameterInstance(JsonParam, DBXCommand.Parameters[I], DidClone);
Inc(J);
end;
try
//Only set instanceOnwer to true if the instance has just been cloned
TDBXJSONTools.JSONToDBX( JsonParam, DBXCommand.Parameters[I].Value, DBXCommand.Parameters[I].DataType, LocalConnection, DidClone );
except
//if an exception happened while trying to set the value,
//we assume the value wasn't set. So, if the parameter passed in was cloned,
//we need to free it here to prevent a memory leak
if DidClone then
FreeAndNil(JsonParam);
Raise;
end;
end;
end;
if J < jsonParams.Size then
begin
// reject execution if not all input parameters were used
Raise TDSServiceException.Create(Format(STooManyInputParams, [Command, J, jsonParams.Size]));
end;
DBXCommand.ExecuteUpdate;
ResponseHandler.AddCommand(DBXCommand, DBXConnection);
DBXCommand := nil;
DBXConnection := nil;
finally
if OwnParams then
JsonParams.Free;
if DBXCommand <> nil then
DBXCommand.Close;
if DBXConnection <> nil then
DBXConnection.Close;
DBXCommand.Free;
if LocalConnection and (DBXConnection <> nil) then
TDSServerConnection(DBXConnection).ServerConnectionHandler.Free
else
DBXConnection.Free;
end;
end;
{TDSRESTService}
constructor TDSRESTService.Create(DSServerName, DSHostname: String; DSPort: Integer; AuthUser, AuthPassword: String );
begin
CreateImpl(DSServerName, DSHostname, DSPort, AuthUser, AuthPassword, '');
end;
constructor TDSRESTService.CreateImpl(DSServerName, DSHostname: String; DSPort: Integer; AuthUser, AuthPassword, AIPImplementationID: String );
begin
inherited Create(DSServerName, DSHostname, DSPort, AuthUser, AuthPassword, AIPImplementationID);
end;
destructor TDSRESTService.Destroy;
begin
inherited;
end;
procedure TDSRESTService.BuildParamArray(const Params: TStringList; var ParamArray: TJSONArray);
var
I: Integer;
S: String;
LValue: Double;
begin
ParamArray := TJSONArray.Create;
for I := 0 to Params.Count - 1 do
begin
S := Params[I];
if (AnsiIndexText(S,TrueBoolStrs) > -1) then
ParamArray.AddElement(TJSONTrue.Create)
else if AnsiIndexText(S,FalseBoolStrs) > -1 then
ParamArray.AddElement(TJSONFalse.Create)
else if AnsiCompareStr(S,NULL) = 0 then
ParamArray.AddElement(TJSONNull.Create)
else
if TDBXPlatform.TryJsonToFloat(S, LValue) then
ParamArray.AddElement(TJSONNumber.Create(S))
else
ParamArray.AddElement(TJSONString.Create(S));
end;
end;
procedure TDSRESTService.ParseRequest(const Request: string; var ClassName: string;
var MethodName: string; var ParamValues: TStringList);
var
SlashLeft, SlashRight: Integer;
ParamValue: String;
LIPImplementationID: string;
begin
// extract the class name
SlashLeft := Pos(REQUEST_DELIMITER, Request);
if SlashLeft = 0 then
begin
// no delimiter for class name
Raise TDSServiceException.Create(SInvalidRequestFormat);
end;
if SlashLeft > 1 then
begin
// first / is missing
SlashRight := SlashLeft;
SlashLeft := 1;
end
else
begin
SlashRight := PosEx(REQUEST_DELIMITER, Request, SlashLeft+1);
if SlashRight < 1 then
begin
// no delimiter after class name
Raise TDSServiceException.Create(SInvalidRequestFormat);
end;
end;
if SlashRight = SlashLeft + 1 then
begin
// empty class name
Raise TDSServiceException.Create(SInvalidRequestFormat);
end;
LIPImplementationID := FDBXProperties.Values[TDBXPropertyNames.IPImplementationID];
ClassName := IPProcs(LIPImplementationID).URLDecode(Copy(Request, Slashleft+1, SlashRight-SlashLeft-1));
// search for method name
SlashLeft := SlashRight;
SlashRight := PosEx(REQUEST_DELIMITER, Request, SlashLeft+1);
if SlashRight < 1 then
begin
SlashRight := Length(Request)+1;
end;
MethodName := IPProcs(LIPImplementationID).URLDecode(Copy( Request, Slashleft+1, SlashRight-slashLeft-1));
SlashLeft := SlashRight;
ParamValues := TStringList.Create;
while slashLeft < Length(Request) do
begin
SlashRight := PosEx(REQUEST_DELIMITER, Request, SlashLeft + 1);
if SlashRight < 1 then
begin
SlashRight := Length(Request)+1;
end;
if (SlashRight = SlashLeft + 1) and (SlashRight <= Length(Request)) then
ParamValues.Add(EmptyStr)
else
begin
ParamValue := IPProcs(LIPImplementationID).URLDecode(Copy(Request, Slashleft+1, SlashRight-SlashLeft-1));
ParamValues.Add(ParamValue);
end;
SlashLeft := SlashRight;
end;
end;
procedure TDSRESTService.ProcessREST(const RequestType: String;
const RestRequest: string;
const Content: TBytes;
ResponseHandler: TRequestCommandHandler);
var
ClassName, MethodName, DSMethodName: String;
Params: TStringList;
ExecuteCmd: TJSONArray;
MethodObj: TJSONObject;
ParamArray: TJSONArray;
Body: TJSONValue;
BodyArray: TJSONArray;
I: Integer;
begin
ExecuteCmd := nil;
try
try
// get class, method name, parameters
ParseRequest(RestRequest, ClassName, MethodName, Params );
// get the JSON parameter array
BuildParamArray(Params, ParamArray);
// get the content
if (Content <> nil) and (Length(Content) > 0) then
begin
Body := TJSONObject.ParseJSONValue(Content, 0);
if Body = nil then
begin
ParamArray.Free;
Raise TDSServiceException.Create(SNoJSONValue);
end;
if (Body is TJSONObject) and (TJSONObject(Body).Size = 1) and
(TJSONObject(Body).Get(0).JSonString.Value = PARAMETERS_PAIR) and
(TJSONObject(Body).Get(0).JsonValue is TJSONArray) then
begin
BodyArray := TJSONArray(TJSONObject(Body).Get(0).JsonValue);
for I := 0 to BodyArray.Size - 1 do
ParamArray.AddElement(TJSONValue(BodyArray.Get(I).Clone));
Body.Free;
end
else
ParamArray.AddElement( Body );
end;
// build the execute command
MethodObj := TJSONObject.Create;
SetMethodNameWithPrefix(RequestType, ClassName, MethodName, DSMethodName);
MethodObj.AddPair(
TJSONPair.Create(
TJSONString.Create( DSMethodName ),
ParamArray ) );
ExecuteCmd := TJSONArray.Create(TJSONObject.Create(
TJSONPair.Create(
TJSONString.Create(CMD_EXECUTE),
MethodObj)));
// execute JSON request
ProcessRequest( ExecuteCmd, ResponseHandler );
except
on ex: Exception do
begin
ResponseHandler.AddCommandError(ex.Message);
end;
end;
finally
Params.Free;
ExecuteCmd.Free;
end;
end;
procedure TDSRESTService.SetMethodNameWithPrefix(const RequestType, ClassName, MethodName: String;
out DSMethodName: String);
var
Prefix: String;
begin
//prefix method name if it isn't quoted
if (MethodName[1] <> '"') and (MethodName[1] <> '''') and
//and if the class isn't one which specifically doesn't support method name prefixing
(ClassName <> 'DSAdmin') and (ClassName <> 'DSMetadata') then
begin
if RequestType = 'PUT' then
Prefix := 'accept'
else if RequestType = 'POST' then
Prefix := 'update'
else if RequestType = 'DELETE' then
Prefix := 'cancel';
end;
DSMethodName := Format('%s.%s%s', [ClassName, Prefix, MethodName]);
end;
procedure TDSRESTService.ProcessGETRequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler);
begin
ProcessREST('GET', Request, nil, ResponseHandler);
end;
procedure TDSRESTService.ProcessPOSTRequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler);
begin
if (Content <> nil) and (Length(Content) > 1) and
not (Content[0] in [91,123]) and (Params <> nil) and (Params.Count = 1) and (Params.names[0] <> EmptyStr) then
ProcessREST('POST', Request, BytesOf(Params.Values[Params.names[0]]), ResponseHandler)
else
ProcessREST('POST', Request, Content, ResponseHandler);
end;
procedure TDSRESTService.ProcessPUTRequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler);
begin
ProcessREST('PUT', Request, Content, ResponseHandler);
end;
procedure TDSRESTService.ProcessDELETERequest(const Request:String; Params: TStrings; Content: TBytes;
ResponseHandler: TRequestCommandHandler);
begin
ProcessREST('DELETE', Request, nil, ResponseHandler);
end;
{TDSJSONService}
constructor TDSJSONService.Create(dsServerName, dsHostname: string; dsPort: Integer; AuthUser, AuthPassword: String);
begin
CreateImpl(dsServerName, dsHostname, dsPort, AuthUser, AuthPassword, '');
end;
constructor TDSJSONService.CreateImpl(dsServerName, dsHostname: string; dsPort: Integer; AuthUser, AuthPassword, AIPImplementationID: String);
begin
inherited Create(dsServerName, dsHostname, dsPort, AuthUser, AuthPassword, AIPImplementationID);
end;
destructor TDSJSONService.Destroy;
begin
inherited;
end;
procedure TDSJSONService.ProcessJSONCommand(Content: TBytes; ResponseHandler: TRequestCommandHandler);
var
Cmd: TJSONValue;
begin
Cmd := TJSONObject.ParseJSONValue(Content, 0);
if Cmd = nil then
Raise TDSServiceException.Create(SNoJSONValue);
try
if Cmd is TJSONArray then
ProcessRequest(TJSONArray(Cmd), ResponseHandler)
else
raise TDSServiceException.Create(Format(SJSONArrayExpected, [Cmd.ClassName]));
finally
Cmd.Free;
end;
end;
procedure TDSJSONService.ProcessPOSTRequest(const Request: string; Params: TStrings; Content: TBytes; ResponseHandler: TRequestCommandHandler);
begin
if (Content <> nil) and (Length(Content) > 0) then
ProcessJSONCommand(Content, ResponseHandler)
else
raise TDSServiceException.Create(Format(SNoJSONCmdContent, ['POST']));
end;
procedure TDSJSONService.ProcessGETRequest(const Request: string; Params: TStrings; Content: TBytes; ResponseHandler: TRequestCommandHandler);
begin
raise TDSServiceException.Create(Format(SPOSTExpected, ['GET']));
end;
procedure TDSJSONService.ProcessPUTRequest(const Request: string; Params: TStrings; Content: TBytes; ResponseHandler: TRequestCommandHandler);
begin
raise TDSServiceException.Create(Format(SPOSTExpected, ['PUT']));
end;
procedure TDSJSONService.ProcessDELETERequest(const Request: string; Params: TStrings; Content: TBytes; ResponseHandler: TRequestCommandHandler);
begin
raise TDSServiceException.Create(Format(SPOSTExpected, ['DELETE']));
end;
{ TDSSession }
function TDSSession.Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): boolean;
begin
{If FUserName has not yet been assigned then try to populate it from the connection properties.
Note that the usefulness of this attempt will depend on the extended implementation of this session.}
if FUserName = '' then
FUserName := connectionProps.Values[TDBXPropertyNames.DSAuthenticationUser];
Result := True;
end;
function TDSSession.Authorize(EventObject: TDSAuthorizeEventObject): boolean;
begin
Result := True;
end;
procedure TDSSession.CancelScheduledEvent;
begin
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.CancelEvent(Id);
end;
constructor TDSSession.Create(const SessionName: string);
begin
FSessionName := SessionName;
Create;
end;
constructor TDSSession.Create(const SessionName: string; const AUser: String);
begin
FUserName := AUser;
Create(SessionName);
end;
constructor TDSSession.Create;
begin
FDuration := 0;
FStatus := Idle;
FStartDateTime := Now;
FMetaData := TDictionary<String,String>.Create;
FMetaObjects := TDictionary<String,TObject>.Create;
FUserRoles := TStringList.Create;
FCache := TDSSessionCache.Create;
MarkActivity;
end;
destructor TDSSession.Destroy;
var
ObjEnumerator: TDictionary<String, TObject>.TValueEnumerator;
begin
if TDSSessionManager.GetThreadSession = Self then
TDSSessionManager.ClearThreadSession;
ObjEnumerator := FMetaObjects.Values.GetEnumerator;
try
while ObjEnumerator.MoveNext do
try
ObjEnumerator.Current.Free;
except
end;
finally
ObjEnumerator.Free
end;
FreeAndNil(FMetaObjects);
FreeAndNil(FMetaData);
FreeAndNil(FUserRoles);
FreeAndNil(FCache);
if LastResultStream <> nil then
try
FreeAndNil(FLastResultStream);
except
end;
inherited;
end;
function TDSSession.ElapsedSinceLastActvity: Cardinal;
begin
{$IFNDEF POSIX}
exit( GetTickCount - FLastActivity );
{$ELSE}
exit( AbsoluteToNanoseconds(UpTime) div 1000000 - FLastActivity );
{$ENDIF}
end;
function TDSSession.ExpiresIn: Cardinal;
var
Elapsed: Integer;
begin
Elapsed := Integer(ElapsedSinceLastActvity);
if (Elapsed >= LifeDuration) then
Exit(0);
Result := LifeDuration - Elapsed;
end;
class function TDSSession.GenerateSessionId: string;
var
P1, P2, P3: Integer;
begin
P1 := Random(1000000);
P2 := Random(1000000);
P3 := Random(1000000);
Result := Format('%d.%d.%d', [P1, P2, P3]);
end;
function TDSSession.HasData(Key: String): Boolean;
begin
Result := FMetaData.ContainsKey(AnsiLowerCase(Key));
end;
function TDSSession.HasObject(Key: String): Boolean;
begin
Result := FMetaObjects.ContainsKey(AnsiLowerCase(Key));
end;
function TDSSession.GetObject(Key: String): TObject;
begin
if (FMetaObjects.TryGetValue(AnsiLowerCase(Key), Result)) then
Exit;
Result := nil;
end;
function TDSSession.PutObject(Key: String; Value: TObject): Boolean;
begin
Result := True;
if not HasObject(Key) then
FMetaObjects.Add(AnsiLowerCase(Key), Value)
else
Exit(False);
end;
function TDSSession.RemoveObject(Key: String; InstanceOwner: Boolean): TObject;
var
Val: TObject;
begin
Result := nil;
if HasObject(Key) then
begin
Val := GetObject(Key);
FMetaObjects.Remove(AnsiLowerCase(Key));
if InstanceOwner then
FreeAndNil(Val)
else
Result := Val;
end;
end;
procedure TDSSession.GetAuthRoleInternal(ServerMethod: TDSServerMethod;
AuthManager: TDSCustomAuthenticationManager; out AuthorizedRoles, DeniedRoles: TStrings);
var
RoleAuth: TRoleAuth;
MethodInfo: TDSMethodInfo;
FreeAuthRole: Boolean;
begin
AuthorizedRoles := nil;
DeniedRoles := nil;
FreeAuthRole := true;
RoleAuth := nil;
if (ServerMethod <> nil) and (ServerMethod.MethodInfo <> nil) then
begin
MethodInfo := ServerMethod.MethodInfo;
//Try to find a design time auth role
if (AuthManager <> nil) and (MethodInfo.DSClassInfo <> nil) then
begin
//only compute the design time Role Auth once
if (MethodInfo.AuthRole = nil) or
(not TRoleAuth(MethodInfo.AuthRole).IsDesignTime) then
begin
RoleAuth := TRoleAuth(AuthManager.GetAuthRole(MethodInfo.DSClassInfo.DSClassName, MethodInfo.DSMethodName));
if (RoleAuth = nil) and (MethodInfo.AuthRole = nil) then
// Create an empty roleauth if there isn't one from RTTI or authentication manager
RoleAuth := TRoleAuth.Create(nil, nil, True);
end;
end;
//if no design-time role found, use the one populated through RTI, if one exists
if RoleAuth = nil then
begin
RoleAuth := TRoleAuth(MethodInfo.AuthRole);
FreeAuthRole := false;
end;
end;
//copy the string lists being sent back, so users can't modify them,
//and so the TRoleAuth itself can be freed, unless it was a code attribute.
if RoleAuth <> nil then
begin
if RoleAuth.AuthorizedRoles <> nil then
begin
AuthorizedRoles := TStringList.Create;
AuthorizedRoles.AddStrings(RoleAuth.AuthorizedRoles);
end;
if RoleAuth.DeniedRoles <> nil then
begin
DeniedRoles := TStringList.Create;
DeniedRoles.AddStrings(RoleAuth.DeniedRoles);
end;
end;
if FreeAuthRole then
FreeAndNil(Roleauth);
end;
procedure TDSSession.GetAuthRoles(ServerMethod: TDSServerMethod;
out AuthorizedRoles, DeniedRoles: TStrings);
begin
AuthorizedRoles := nil;
DeniedRoles := nil;
end;
function TDSSession.GetData(Key: String): String;
var
Value: String;
begin
if (FMetaData.TryGetValue(AnsiLowerCase(Key), Value)) then
exit(Value);
Result := '';
end;
function TDSSession.GetId: NativeInt;
begin
exit(IntPtr(Pointer(Self)));
end;
function TDSSession.GetSessionStatus: TDSSessionStatus;
begin
if ((FStatus = TDSSessionStatus.Active) or
(FStatus = TDSSessionStatus.Idle) or
(FStatus = TDSSessionStatus.Connected))
and (FDuration > 0) and IsIdleMS(FDuration) then
begin
FStatus := TDSSessionStatus.Expired;
end;
Result := FStatus;
end;
procedure TDSSession.Close;
begin
FStatus := Closed;
end;
procedure TDSSession.Terminate;
begin
FStatus := Closed;
end;
function TDSSession.IsValid: boolean;
begin
Result := (Status = TDSSessionStatus.Active) or
(Status = TDSSessionStatus.Idle) or
(Status = TDSSessionStatus.Connected);
end;
function TDSSession.IsIdle(Seconds: Cardinal): Boolean;
begin
Result := IsIdleMS(Seconds * 1000);
end;
function TDSSession.IsIdleMS(Milliseconds: Cardinal): Boolean;
begin
Result := ElapsedSinceLastActvity > Milliseconds;
end;
procedure TDSSession.MarkActivity;
begin
FStatus := Active;
{$IFNDEF POSIX}
FLastActivity := GetTickCount;
{$ELSE}
FLastActivity := AbsoluteToNanoseconds(UpTime) div 1000000;
{$ENDIF}
end;
procedure TDSSession.PutData(Key, Value: String);
var
LowerKey: String;
begin
LowerKey := AnsiLowerCase(Key);
FMetaData.Remove(LowerKey);
FMetaData.Add(LowerKey, Value);
end;
procedure TDSSession.RemoveData(Key: String);
begin
FMetaData.Remove(AnsiLowerCase(Key));
end;
function TDSSession.RequiresAuthorization(MethodInfo: TDSMethodInfo): Boolean;
begin
Result := (MethodInfo <> nil) and
(MethodInfo.MethodAlias <> 'DSMetadata.GetDatabase') and
//GetPlatformName is often used to validate a connection, we will allow this call by anyone
(MethodInfo.MethodAlias <> 'DSAdmin.GetPlatformName');
end;
procedure TDSSession.TerminateInactiveSession;
begin
if (FDuration > 0) and (IsIdleMS(FDuration)) then
begin
try
TerminateSession;
TDSSessionManager.Instance.TerminateSession(SessionName);
except
end;
end
else
ScheduleInactiveTerminationEvent;
end;
procedure TDSSession.ScheduleInactiveTerminationEvent;
begin
if FDuration > 0 then
ScheduleUserEvent(TerminateInactiveSession, FDuration);
end;
procedure TDSSession.ScheduleTerminationEvent;
begin
if FDuration > 0 then
ScheduleUserEvent(TerminateSession, FDuration);
end;
procedure TDSSession.ScheduleUserEvent(Event: TDBXScheduleEvent; ElapsedTime: Integer);
begin
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.AddEvent(Id, Event, ElapsedTime);
end;
procedure TDSSession.SetSessionName(const sessionId: String);
begin
FSessionName := sessionId;
end;
procedure TDSSession.SetUserName(const userName: String);
begin
FUserName := userName;
end;
procedure TDSSession.TerminateSession;
begin
FStatus := Terminated;
end;
{ TDSRequestFilter<T> }
constructor TDSRequestFilter<T>.Create(const TypeName: String);
begin
FTypeName := TypeName;
end;
destructor TDSRequestFilter<T>.Destroy;
begin
inherited;
end;
function TDSRequestFilter<T>.HasParameter(const ParamName: String): boolean;
begin
exit(false);
end;
function TDSRequestFilter<T>.SetParameterValue(ParamName,
ParamValue: String): boolean;
begin
Result := false;
end;
{ TDBXRequestFilterFactory }
class procedure TDBXRequestFilterFactory.CleanUp;
begin
FreeAndNil( FInstance );
end;
constructor TDBXRequestFilterFactory.Create;
begin
FRepo := TDBXRequestFilterDictionary.Create([doOwnsValues]);
end;
function TDBXRequestFilterFactory.RequestFilter(
Name: String): TDBXRequestFilter;
begin
if FRepo.ContainsKey(Name) then
FRepo.TryGetValue(Name, Result)
else
Result := nil
end;
destructor TDBXRequestFilterFactory.Destroy;
begin
FreeAndNil( FRepo );
inherited;
end;
procedure TDBXRequestFilterFactory.GetAllWithField(FieldName: String;
List: TObjectList<TDBXRequestFilter>);
var
Itr: TDBXRequestFilterDictionary.TValueEnumerator;
DC: TDBXRequestFilter;
begin
Itr := FRepo.Values.GetEnumerator;
try
while Itr.MoveNext do
begin
DC := Itr.Current;
if DC.HasParameter(FieldName) then
List.Add(DC);
end;
finally
Itr.Free;
end;
end;
procedure TDBXRequestFilterFactory.RegisterRequestFilter(
Converter: TDBXRequestFilter);
begin
FRepo.Add(Converter.TypeName, Converter);
end;
class procedure TDBXRequestFilterFactory.SetUp;
begin
FInstance := TDBXRequestFilterFactory.Create;
end;
{ TDBXCropDataConverter }
constructor TDBXCropRequestFilter.Create(const TypeName: String);
begin
inherited Create(TypeName);
FOff := 0;
FCount := MaxInt;
end;
constructor TDBXCropRequestFilter.Create(const TypeName: String; Off,
Count: Integer);
begin
inherited Create(TypeName);
FOff := Off;
FCount := Count;
end;
destructor TDBXCropRequestFilter.Destroy;
begin
inherited;
end;
function TDBXCropRequestFilter.HasParameter(
const ParamName: String): boolean;
begin
if (AnsiCompareText(ParamName, 'o') = 0) or (AnsiCompareText(ParamName, 'c') = 0)
or (AnsiCompareText(ParamName, 'r') = 0) then
exit(true);
Result := inherited;
end;
function TDBXCropRequestFilter.SetParameterValue(ParamName,
ParamValue: String): boolean;
var
RangeSep : Integer;
begin
if AnsiCompareText(ParamName, 'o') = 0 then
FOff := StrToInt(ParamValue)
else if AnsiCompareText(ParamName, 'c') = 0 then
FCount := StrToInt(ParamValue)
{If the 'r' field is used then the user is providing a pair of integers, separated by a comma.
Before the comma is the offset for the substring, and the number after the comma is the count
of how many character after the offset to include in the substring (the length.)}
else if AnsiCompareText(ParamName, 'r') = 0 then
begin
RangeSep := Pos(',', ParamValue);
if ( RangeSep > 1 ) and ( RangeSep < Length( ParamValue ) ) then
begin
FOff := StrToInt(Copy(ParamValue, 1, RangeSep - 1));
FCount := StrToInt(Copy(ParamValue, RangeSep + 1, Length(ParamValue) - RangeSep));
end
else
exit(false);
end
else
exit(false);
exit(true);
end;
{ TDBXSubStringDataConverter }
function TDBXSubStringRequestFilter.Clone: TDBXRequestFilter;
begin
Result := TDBXSubStringRequestFilter.Create(TypeName, Off, Count);
end;
function TDBXSubStringRequestFilter.CanConvert(Value: TDBXValue): boolean;
begin
case Value.ValueType.DataType of
{Implementation for Strings}
TDBXDataTypes.AnsiStringType, TDBXDataTypes.WideStringType,
{Implementation for Streams}
TDBXDataTypes.BlobType, TDBXDataTypes.BinaryBlobType:
exit(true);
else
exit(false);
end;
end;
function TDBXSubStringRequestFilter.ToJSON(Value: TDBXValue; IsLocal: boolean): TJSONValue;
begin
case Value.ValueType.DataType of
TDBXDataTypes.BlobType, TDBXDataTypes.BinaryBlobType:
Result := TDBXJSONTools.streamToJSON(Value.GetStream(False), Off, Count);
else
Result := TJSONString.Create(Copy(Value.AsString, Off + 1, Count));
end;
end;
{ TDBXReaderDataConverter }
function TDBXReaderRequestFilter.CanConvert(Value: TDBXValue): boolean;
begin
Result := Value.ValueType.DataType = TDBXDataTypes.TableType;
end;
function TDBXReaderRequestFilter.Clone: TDBXRequestFilter;
begin
Result := TDBXReaderRequestFilter.Create(TypeName, Off, Count);
end;
function TDBXReaderRequestFilter.ToJSON(Value: TDBXValue; IsLocal: boolean): TJSONValue;
var
DBXReader: TDBXReader;
RowCount: Integer;
begin
DBXReader := Value.GetDBXReader;
RowCount := Off;
while RowCount > 0 do
begin
DBXReader.Next;
Dec(RowCount);
end;
Result := TDBXJSONTools.TableToJSON(DBXReader, Count, IsLocal);
end;
{ TDSSessionManager }
procedure TDSSessionManager.CloseSession(session: TDSSession);
begin
try
if Assigned(session) then
begin
// Session should have been removed from the list by now
Assert(GetSession(session.SessionName) = nil);
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.CancelEvent(session.Id);
NotifyEvents(session, SessionClose);
session.Close;
end
finally
session.Free;
end;
end;
procedure TDSSessionManager.AddSessionEvent(Event: TDSSessionEvent);
begin
if not Assigned(FListeners) then
FListeners := TList<TDSSessionEvent>.Create;
System.TMonitor.Enter(FListeners);
try
if not FListeners.Contains(Event) then
FListeners.Add(Event);
finally
System.TMonitor.Exit(FListeners);
end;
end;
function TDSSessionManager.RemoveSessionEvent(Event: TDSSessionEvent): boolean;
begin
if Assigned(FListeners) then
begin
System.TMonitor.Enter(FListeners);
try
exit(FListeners.Remove(Event) > -1);
finally
System.TMonitor.Exit(FListeners);
end;
end;
Result := False;
end;
class procedure TDSSessionManager.SetAsThreadSession(Session: TDSSession);
begin
VDSSession := Session;
end;
class procedure TDSSessionManager.ClearThreadSession;
begin
VDSSession := nil;
end;
procedure TDSSessionManager.CloseSession(SessionId: string);
var
session: TDSSession;
begin
session := RemoveSession(SessionId);
if Assigned(session) then
CloseSession(session);
end;
constructor TDSSessionManager.Create;
begin
FSessionContainer := TDictionary<String, TDSSession>.Create;
end;
function TDSSessionManager.CreateSession<T>(factory: TFactoryMethod; userName: String): T;
begin
Result := CreateSession<T>(factory, False);
Result.SetUserName(userName);
NotifyEvents(Result, SessionCreate);
end;
function TDSSessionManager.CreateSession<T>(factory: TFactoryMethod; DoNotify: Boolean): T;
var
sessionId: String;
begin
TMonitor.Enter(self);
try
sessionId := GetUniqueSessionId;
Result := T(factory);
Result.SetSessionName(sessionId);
FSessionContainer.Add(sessionId, Result);
finally
TMonitor.Exit(self);
end;
if DoNotify then
NotifyEvents(Result, SessionCreate);
end;
destructor TDSSessionManager.Destroy;
var
keys: TStrings;
key: String;
begin
keys := TStringList.Create;
try
GetOpenSessionKeys(keys);
for key in keys do
begin
TerminateSession(key);
end;
finally
FInstance := nil;
FreeAndNil(FListeners);
FreeAndNil(FSessionContainer);
FreeAndNil(keys);
inherited;
end;
end;
procedure TDSSessionManager.GetOpenSessionKeys(Container: TStrings);
begin
Synchronized(self, procedure
var
keyEnumerator: TDictionary<String, TDSSession>.TKeyEnumerator;
begin
keyEnumerator := FSessionContainer.Keys.GetEnumerator;
while keyEnumerator.MoveNext do
Container.Add(keyEnumerator.Current);
keyEnumerator.Free
end);
end;
procedure TDSSessionManager.GetOpenSessionKeys(Container: TStrings; ACreator: TObject);
begin
Synchronized(self, procedure
var
valueEnumerator: TDictionary<String, TDSSession>.TValueEnumerator;
begin
valueEnumerator := FSessionContainer.Values.GetEnumerator;
while valueEnumerator.MoveNext do
if valueEnumerator.Current.ObjectCreator = ACreator then
Container.Add(valueEnumerator.Current.SessionName);
valueEnumerator.Free
end);
end;
function TDSSessionManager.GetSession(SessionId: string): TDSSession;
begin
TMonitor.Enter(self);
try
FSessionContainer.TryGetValue(SessionId, Result);
finally
TMonitor.Exit(self);
end;
end;
function TDSSessionManager.GetSessionCount: Integer;
var
Count: Integer;
begin
Synchronized(Self, procedure begin
Count := FSessionContainer.Count;
end);
Result := Count;
end;
class function TDSSessionManager.GetThreadSession: TDSSession;
begin
Result := VDSSession;
end;
function TDSSessionManager.GetTunnelSession(
SessionId: string): TDSTunnelSession;
var
session: TDSSession;
begin
session := GetSession(SessionId);
if (session <> nil) and (session is TDSTunnelSession) then
Result := TDSTunnelSession(session)
else
Result := nil;
end;
function TDSSessionManager.GetUniqueSessionId: string;
begin
// assumes the container is thread secure
repeat
Result := TDSSession.GenerateSessionId
until not FSessionContainer.ContainsKey(Result);
end;
procedure TDSSessionManager.NotifyEvents(session: TDSSession; EventType: TDSSessionEventType);
var
Event: TDSSessionEvent;
I, Count: Integer;
LListeners: TList<TDSSessionEvent>;
begin
if Assigned(FListeners) then
begin
System.TMonitor.Enter(Self);
try
LListeners := TList<TDSSessionEvent>.Create;
//copy the events into a new list, so the FListeners
//doesn't need to remain locked while calling each event.
//this prevents deadlocks if events try to remove themselves, for example
System.TMonitor.Enter(FListeners);
try
Count := FListeners.Count - 1;
for I := 0 to Count do
LListeners.Add(FListeners.Items[I]);
finally
System.TMonitor.Exit(FListeners);
end;
try
Count := LListeners.Count - 1;
for I := Count downto 0 do
begin
Event := LListeners.Items[I];
try
if FListeners.Contains(Event) then
Event(Self, EventType, session);
except
end;
end;
finally
FreeAndNil(LListeners);
end;
finally
System.TMonitor.Exit(Self);
end;
end;
end;
function TDSSessionManager.RemoveSession(SessionId: string): TDSSession;
var
session: TDSSession;
begin
session := nil;
Synchronized(self, procedure begin
FSessionContainer.TryGetValue(SessionId, session);
if session <> nil then
FSessionContainer.Remove(SessionId);
end);
Result := session;
end;
procedure TDSSessionManager.TerminateAllSessions(const ACreator: TObject; AAllSessions: Boolean);
var
LList: TList<TDSSession>;
LSession: TDSSession;
begin
LList := TList<TDSSession>.Create;
try
ForEachSession(procedure(const Session: TDSSession) begin
if AAllSessions or (Session.ObjectCreator = ACreator) then
LList.Add(RemoveSession(Session.SessionName));
end);
for LSession in LList do
TerminateSession(LSession);
finally
LList.Free;
end;
end;
procedure TDSSessionManager.TerminateAllSessions(const ACreator: TObject);
begin
TerminateAllSessions(ACreator, False);
end;
procedure TDSSessionManager.TerminateAllSessions;
begin
TerminateAllSessions(nil, True);
end;
procedure TDSSessionManager.ForEachSession(AVisitor: TDSSessionVisitor);
begin
Synchronized(self, procedure
var
valEnumerator: TDictionary<String, TDSSession>.TValueEnumerator;
begin
valEnumerator := FSessionContainer.Values.GetEnumerator;
try
while valEnumerator.MoveNext do
AVisitor(valEnumerator.Current);
finally
valEnumerator.Free
end;
end);
end;
procedure TDSSessionManager.TerminateSession(session: TDSSession);
begin
try
if Assigned(session) then
begin
// Session should have been removed from the list by now
Assert(GetSession(session.SessionName) = nil);
if TDBXScheduler.Instance <> nil then
TDBXScheduler.Instance.CancelEvent(session.Id);
session.Terminate;
NotifyEvents(session, SessionClose);
end;
finally
session.Free;
end;
end;
procedure TDSSessionManager.TerminateSession(const sessionId: String);
var
session: TDSSession;
begin
session := RemoveSession(sessionId);
if Assigned(session) then
TerminateSession(session);
end;
{ TDSAuthSession }
procedure TDSAuthSession.GetAuthRoles(ServerMethod: TDSServerMethod;
out AuthorizedRoles, DeniedRoles: TStrings);
begin
AuthorizedRoles := nil;
DeniedRoles := nil;
if (ServerMethod <> nil) and (ServerMethod.MethodInfo <> nil) then
if (FAuthManager <> nil) then
GetAuthRoleInternal(ServerMethod, FAuthManager, AuthorizedRoles, DeniedRoles);
end;
function TDSAuthSession.Authorize(EventObject: TDSAuthorizeEventObject): boolean;
begin
if (FAuthManager <> nil) then
begin
exit(FAuthManager.Authorize(EventObject))
end;
exit(True); //return true if no authentication manager is set
end;
{ TDSRESTSession }
function TDSRESTSession.Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): boolean;
begin
Inherited;
exit(True); //currently, authentication will be done elsewhere for REST
end;
constructor TDSRESTSession.Create(AAuthManager: TDSCustomAuthenticationManager);
begin
FAuthManager := AAuthManager;
Inherited Create;
end;
{ TDSSessionCache }
function TDSSessionCache.AddItem(Item: TResultCommandHandler): Integer;
var
LargestId: Integer;
Id: Integer;
begin
if (Item = nil) then
exit(-1);
TMonitor.Enter(FItems);
try
LargestId := -1;
for Id in FItems.Keys do
begin
if FItems.Items[Id] = Item then
exit(Id);
if (Id > LargestId) then
LargestId := Id;
end;
Id := LargestId + 1;
FItems.Add(Id, Item);
Result := Id;
finally
TMonitor.Exit(FItems);
end;
end;
procedure TDSSessionCache.ClearAllItems(InstanceOwner: Boolean);
var
Item: TResultCommandHandler;
begin
if Assigned(FItems) then
begin
TMonitor.Enter(FItems);
try
if InstanceOwner then
begin
for Item in FItems.Values do
try
Item.Free;
except
end;
end;
FItems.Clear;
finally
TMonitor.Exit(FItems);
end;
end;
end;
constructor TDSSessionCache.Create;
begin
FItems := TDictionary<Integer, TResultCommandHandler>.Create;
end;
destructor TDSSessionCache.Destroy;
begin
ClearAllItems(True);
FreeAndNil(FItems);
inherited;
end;
function TDSSessionCache.GetItem(ID: Integer): TResultCommandHandler;
var
Item: TResultCommandHandler;
begin
Result := nil;
if FItems.TryGetValue(ID, Item) then
begin
Result := Item;
end;
end;
function TDSSessionCache.GetItemID(Item: TResultCommandHandler): Integer;
var
Id: Integer;
begin
Result := -1;
if (Item <> nil) and Assigned(FItems) then
begin
TMonitor.Enter(FItems);
try
for Id in FItems.Keys do
begin
if FItems.Items[Id] = Item then
exit(Id);
end;
finally
TMonitor.Exit(FItems);
end;
end;
end;
function TDSSessionCache.GetItemIDs: TDSSessionCacheKeys;
var
Key: Integer;
begin
Result := TDSSessionCacheKeys.Create;
TMonitor.Enter(FItems);
try
for Key in FItems.Keys do
Result.Add(Key);
finally
TMonitor.Exit(FItems);
Result.Sort;
end;
end;
procedure TDSSessionCache.RemoveItem(Item: TResultCommandHandler);
var
Val: TResultCommandHandler;
I: Integer;
IndexToRemove: Integer;
begin
if (Item = nil) or not Assigned(FItems) then
Exit;
IndexToRemove := -1;
TMonitor.Enter(FItems);
try
for I in FItems.Keys do
begin
Val := FItems.Items[I];
if Val = Item then
begin
IndexToRemove := I;
end;
end;
if (IndexToRemove > -1) then
RemoveItem(IndexToRemove, False);
finally
TMonitor.Exit(FItems);
end;
end;
function TDSSessionCache.RemoveItem(ID: Integer; InstanceOwner: Boolean): TResultCommandHandler;
var
Item: TResultCommandHandler;
begin
Result := nil;
TMonitor.Enter(FItems);
try
if FItems.TryGetValue(ID, Item) then
begin
FItems.Remove(ID);
if InstanceOwner then
Item.Free
else
Result := Item;
end;
finally
TMonitor.Exit(FItems);
end;
end;
{ TDSRequestFilterManager }
procedure TDSRequestFilterManager.FiltersForCriteria(const TypeName: string; const Range: TParamRange;
const OnResult: boolean; out List: TObjectList<TDBXRequestFilter>);
var
itr: TObjectDictionary<String, TDBXRequestFilter>.TValueEnumerator;
begin
itr := FRequestFilterStore.Values.GetEnumerator;
try
while itr.MoveNext do
if (itr.Current.TypeName = TypeName) and
(((itr.Current.Range * Range) <> []) or (itr.Current.OnResult = OnResult)) then
List.Add(itr.Current); // add it
finally
itr.Free;
end;
end;
function TDSRequestFilterManager.CheckConvertersForConsistency: boolean;
var
itr: TObjectDictionary<String, TDBXRequestFilter>.TValueEnumerator;
Range: TParamRange;
OnResult: boolean;
begin
Range := [];
OnResult := false;
itr := FRequestFilterStore.Values.GetEnumerator;
try
while itr.MoveNext do
begin
if ((itr.Current.Range * Range) <> []) or (OnResult and (itr.Current.OnResult = OnResult)) then
exit(false);
Range := Range + itr.Current.Range;
OnResult := OnResult or itr.Current.OnResult;
end;
Result := true;
finally
itr.Free;
end;
end;
constructor TDSRequestFilterManager.Create;
begin
FRequestFilterStore := TDBXRequestFilterDictionary.Create([doOwnsValues]);
end;
destructor TDSRequestFilterManager.Destroy;
begin
FRequestFilterStore.Free;
inherited;
end;
procedure TDSRequestFilterManager.FiltersForCriteria(const Range: TParamRange; const OnResult: boolean;
out List: TObjectList<TDBXRequestFilter>);
var
itr: TObjectDictionary<String, TDBXRequestFilter>.TValueEnumerator;
begin
itr := FRequestFilterStore.Values.GetEnumerator;
try
while itr.MoveNext do
if ((itr.Current.Range * Range) <> []) or (OnResult and itr.Current.OnResult) then
List.Add(itr.Current); // add it
finally
itr.Free;
end;
end;
class procedure TDSRequestFilterManager.ParseParamName(const PName: string; out DCName, DCType, FieldName: string;
out Range: TParamRange; out OnResult: boolean);
var
TokenIndex: Integer;
RangeIndex: Integer;
LowIdx: Integer;
RangeStarted: boolean;
procedure FillRange(Low: Integer; Hi: Integer; var Range: TParamRange);
begin
while Low <= Hi do
begin
Range := Range + [Low];
Inc(Low);
end;
end;
procedure AddRange;
begin
if TokenIndex < RangeIndex then
begin
if not RangeStarted then
Range := Range + [ StrToInt(Copy(DCName, TokenIndex, RangeIndex - TokenIndex)) ]
else
begin
FillRange(LowIdx, StrToInt(Copy(DCName, TokenIndex, RangeIndex - TokenIndex)), Range);
RangeStarted := false;
end;
TokenIndex := RangeIndex + 1;
LowIdx := 0;
end
else
raise Exception.Create(Format(SBadParamName, [PName]));
end;
begin
// look for dot and extract the DC name
TokenIndex := Pos('.', PName);
if TokenIndex = 0 then
DCName := EmptyStr
else
DCName := Copy(PName, 1, TokenIndex - 1);
// field name follows the .
FieldName := Copy(PName, TokenIndex + 1, Length(PName) - TokenIndex);
// look for range
if DCName <> EmptyStr then
begin
RangeIndex := 1;
while (RangeIndex <= Length(DCName)) and not CharInSet(DCName[RangeIndex], ['0'..'9','-',',']) do
Inc(RangeIndex);
DCType := Copy(DCName, 1, RangeIndex- 1);
// check for range
Range := [];
if RangeIndex <= Length(DCName) then
begin
OnResult := false;
TokenIndex := RangeIndex;
RangeStarted := false;
while RangeIndex <= Length(DCName) do
begin
if DCName[RangeIndex] = ',' then
begin
// consume <nb>, pattern
AddRange;
end
else if DCName[RangeIndex] = '-' then
begin
// consume <nb>-<nb> pattern
if TokenIndex < RangeIndex then
LowIdx := StrToInt(Copy(DCName, TokenIndex, RangeIndex - TokenIndex))
else
LowIdx := 0;
TokenIndex := RangeIndex + 1;
RangeStarted := true;
end;
Inc(RangeIndex);
end;
AddRange;
end
else
OnResult := true
end
else
OnResult := true;
end;
function TDSRequestFilterManager.ProcessQueryParameter(const ParamName, ParamValue: String): boolean;
var
DCName, DCType, FieldName: string;
Range: TParamRange;
OnResult: boolean;
DBXConverter: TDBXRequestFilter;
DBXConverterList, CurrentList: TObjectList<TDBXRequestFilter>;
I, J: Integer;
function SetupDCParam: boolean;
begin
DBXConverter.Range := Range;
DBXConverter.OnResult := OnResult;
Result := DBXConverter.SetParameterValue(FieldName, ParamValue);
end;
begin
if ParamName = EmptyStr then
exit(true); // skip empty parameters
{handle the json parameter, which is a flag saying if streams should be passed back as json arrays}
if 'json' = AnsiLowerCase(ParamName) then
begin
FStreamAsJSON := StrToBool(ParamValue);
exit(true);
end;
// get the DC name
ParseParamName(ParamName, DCName, DCType, FieldName, Range, OnResult);
if DCType = EmptyStr then
begin
// iterate through all DC and pick the ones with given parameter
DBXConverterList := TObjectList<TDBXRequestFilter>.Create(false);
try
TDBXRequestFilterFactory.Instance.GetAllWithField(FieldName, DBXConverterList);
Result := True;
for I := 0 to DBXConverterList.Count - 1 do
begin
DBXConverter := DBXConverterList.Items[I];
// join with the existing converters
CurrentList := TObjectList<TDBXRequestFilter>.Create;
try
FiltersForCriteria(DBXConverter.TypeName, Range, OnResult, CurrentList);
if CurrentList.Count > 0 then
begin
for J := 0 to CurrentList.Count - 1 do
begin
DBXConverter := CurrentList.Items[J];
if not DBXConverter.SetParameterValue(FieldName, ParamValue) then
Result := false;
end;
end
else
begin
// add new one
DBXConverter := DBXConverter.Clone;
DBXConverter.Name := DBXConverter.TypeName;
if SetupDCParam then
FRequestFilterStore.Add(DBXConverter.TypeName, DBXConverter)
else
Result := false
end;
finally
CurrentList.Free;
end;
end;
finally
DBXConverterList.Free;
end;
end
else
begin
if FRequestFilterStore.ContainsKey(DCName) then
FRequestFilterStore.TryGetValue(DCName, DBXConverter)
else
begin
DBXConverter := TDBXRequestFilterFactory.Instance.RequestFilter(DCType);
if (DBXConverter = nil) or not DBXConverter.HasParameter(FieldName) then
exit(True); //the query parameter wasn't a request filter. return true
DBXConverter := DBXConverter.Clone;
DBXConverter.Name := DCName;
FRequestFilterStore.Add(DCName, DBXConverter);
end;
Result := SetupDCParam;
end;
end;
{ TDSTCPSession }
function TDSTCPSession.Authenticate(const AuthenticateEventObject: TDSAuthenticateEventObject; connectionProps: TDBXProperties): boolean;
begin
Inherited;
if FAuthManager <> nil then
exit(FAuthManager.Authenticate(AuthenticateEventObject, connectionProps));
exit(True);
end;
constructor TDSTCPSession.Create(AAuthManager: TObject);
begin
Create(TDSCustomAuthenticationManager(AAuthManager));
end;
constructor TDSTCPSession.Create(AAuthManager: TDSCustomAuthenticationManager);
begin
FAuthManager := AAuthManager;
Inherited Create;
end;
initialization
Randomize;
TDBXRequestFilterFactory.SetUp;
TDBXRequestFilterFactory.Instance.RegisterRequestFilter(TDBXSubStringRequestFilter.Create('ss'));
TDBXRequestFilterFactory.Instance.RegisterRequestFilter(TDBXReaderRequestFilter.Create('t'));
TDSSessionManager.FInstance := TDSSessionManager.Create;
finalization
TDBXRequestFilterFactory.CleanUp;
TDSSessionManager.FInstance.Free;
end.
|
unit CryModule;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Masks, Vcl.StdCtrls, FWZipReader, FWZipWriter, FWZipCrypt, System.ZLib,
UbuntuProgress, Winapi.ShellAPI;
type
TCryMode = class(TForm)
Button1: TButton;
Button2: TButton;
UbuntuProgress1: TUbuntuProgress;
procedure Button1Click(Sender: TObject);
procedure OnProgress(Sender: TObject; const FileName: string; Percent: Byte; TotalPercent: Byte; var Cancel: Boolean);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
CryMode: TCryMode;
implementation
{$R *.dfm}
uses MainUnit;
procedure FindFolders(StartFolder, Mask: String; List: TStrings;
ScanSubFolders: Boolean = False);
var
SearchRec: TSearchRec;
FindResult: Integer;
begin
List.BeginUpdate;
try
StartFolder:=IncludeTrailingBackslash(StartFolder);
FindResult:=FindFirst(StartFolder+'*', faDirectory, SearchRec);
try
while FindResult = 0 do with SearchRec do begin
if ((SearchRec.Attr and faDirectory) = faDirectory) and
(Name<>'.') and (Name<>'..') then
begin
if MatchesMask(Name, Mask) then
List.Add(StartFolder+Name);
end;
FindResult:=FindNext(SearchRec);
end;
finally
FindClose(SearchRec);
end;
finally
List.EndUpdate;
end;
end;
procedure FindFiles(StartFolder, Mask: String; List: TStrings;
ScanSubFolders: Boolean = True);
var
SearchRec: TSearchRec;
FindResult: Integer;
begin
List.BeginUpdate;
try
StartFolder:=IncludeTrailingBackslash(StartFolder);
FindResult:=FindFirst(StartFolder+'*.*', faAnyFile, SearchRec);
try
while FindResult = 0 do with SearchRec do begin
if (Attr and faDirectory)>0 then begin
if ScanSubFolders and (Name<>'.') and (Name<>'..') then
FindFiles(StartFolder+Name, Mask, List, ScanSubFolders);
end else begin
if MatchesMask(Name, Mask) then List.Add(StartFolder+Name);
end;
FindResult:=FindNext(SearchRec);
end;
finally
FindClose(SearchRec);
end;
finally
List.EndUpdate;
end;
end;
function GetFileNameWOExt(fn:String):String;
begin
Result := Copy(fn, 1, Length(fn)-Length(ExtractFileExt(fn)));
end;
procedure TCryMode.Button2Click(Sender: TObject);
var
FoldersToDeCrypt:TStringList;
DeCryptFile:TFWZipReader;
i,j:Integer;
begin
FoldersToDeCrypt:=TStringList.Create;
FoldersToDeCrypt.Clear;
FindFiles(MainForm.DataDir+'LanguageFiles\', '*.cryz', FoldersToDeCrypt, False);
FindFiles(MainForm.DataDir+'PrecompiledFiles\', '*.cryz', FoldersToDeCrypt, False);
for i := 0 to FoldersToDeCrypt.Count-1 do begin
DeCryptFile:=TFWZipReader.Create;
DeCryptFile.OnProgress:=OnProgress;
DeCryptFile.LoadFromFile(FoldersToDeCrypt[i]);
DeCryptFile.PasswordList.Clear;
for j := 0 to MainForm.PasswordList.Count-1 do DeCryptFile.PasswordList.Add(MainForm.PasswordList[j]);
ForceDirectories(GetFileNameWOExt(FoldersToDeCrypt[i]));
DeCryptFile.ExtractAll(GetFileNameWOExt(FoldersToDeCrypt[i]));
DeCryptFile.Free;
DeleteFile(FoldersToDeCrypt[i]);
end;
FoldersToDeCrypt.Free;
end;
procedure TCryMode.OnProgress(Sender: TObject; const FileName: string; Percent: Byte; TotalPercent: Byte; var Cancel: Boolean);
begin
UbuntuProgress1.Position:=TotalPercent;
Application.ProcessMessages;
end;
Function DelTree(DirName : string): Boolean;
var
SHFileOpStruct : TSHFileOpStruct;
DirBuf : array [0..255] of char;
begin
try
Fillchar(SHFileOpStruct,Sizeof(SHFileOpStruct),0) ;
FillChar(DirBuf, Sizeof(DirBuf), 0 ) ;
StrPCopy(DirBuf, DirName) ;
with SHFileOpStruct do begin
Wnd := 0;
pFrom := @DirBuf;
wFunc := FO_DELETE;
fFlags := FOF_NOCONFIRMATION;
fFlags := fFlags or FOF_SILENT;
end;
Result := (SHFileOperation(SHFileOpStruct) = 0) ;
except
Result := False;
end;
end;
procedure TCryMode.Button1Click(Sender: TObject);
var
FoldersToCrypt:TStringList;
CryptFile:TFWZipWriter;
i,j:Integer;
begin
FoldersToCrypt:=TStringList.Create;
FoldersToCrypt.Clear;
FindFolders(MainForm.DataDir+'LanguageFiles', '*', FoldersToCrypt);
FindFolders(MainForm.DataDir+'PrecompiledFiles', '*', FoldersToCrypt);
for i := 0 to FoldersToCrypt.Count-1 do begin
CryptFile:=TFWZipWriter.Create;
CryptFile.OnProgress:=OnProgress;
CryptFile.AddFolder('',FoldersToCrypt[i],'*');
for j := 0 to CryptFile.Count-1 do begin
CryptFile.Item[j].Password:=MainForm.PasswordList[Random(MainForm.PasswordList.Count-1)];
MainForm.AddToLog('I', CryptFile.Item[j].FileName+' - '+CryptFile.Item[j].Password);
CryptFile.Item[j].CompressionLevel:=clMax;
end;
CryptFile.BuildZip(GetFileNameWOExt(FoldersToCrypt[i])+'.cryz');
DelTree(FoldersToCrypt[i]);
CryptFile.Free;
end;
FoldersToCrypt.Free;
end;
end.
|
unit poly1305;
{Poly1305 one-time authenticator}
interface
{$i STD.INC}
(*************************************************************************
DESCRIPTION : Poly1305 one-time authenticator
REQUIREMENTS : TP5-7, D1-D7/D9-D12/D17-D18, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : [1] A. Moon's MIT/public domain source code from
https://github.com/floodyberry/poly1305-donna
[2] D.J. Bernstein's NACL library nacl-20110221.tar.bz2
file nacl-20110221\crypto_onetimeauth\poly1305\ref\auth.c
available from http://nacl.cr.yp.to/index.html
[3] Y. Nir et al, ChaCha20 and Poly1305 for IETF Protocols
http://tools.ietf.org/html/rfc7539
REMARK : The sender **MUST NOT** use poly1305_auth to authenticate
more than one message under the same key. Authenticators
for two messages under the same key should be expected to
reveal enough information to allow forgeries of
authenticators on other messages.
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 01.08.15 W.Ehrhardt Initial BP version from poly1305-donna-8.h
0.11 02.08.15 we Some fixes, complete poly1305-donna selftest
0.12 02.08.15 we Adjustments for compilers without const parameters
0.13 03.08.15 we Comments and references
0.14 03.08.15 we Packed arrays, some improvements
0.15 03.08.15 we Generic context, 8-bit types
0.16 03.08.15 we First 16x16 version (poly1305_init and poly1305_blocks)
0.17 04.08.15 we 16x16 version of poly1305_finish, published bug report
0.18 29.03.16 we 16x16 version: fixed a bug in blocks, included bug fix from polydonna in finish
0.19 02.04.16 we First 32x32 version (poly1305_init and poly1305_blocks)
0.20 03.04.16 we 32x32 version of poly1305_finish
0.21 03.04.16 we autoselect 16x16 or 32x32 (8x8 is always slower)
0.22 10.04.16 we 32x32 poly1305_blocks without copy to local msg block
0.23 10.04.16 we move poly_8x8 code to separate include file
0.24 10.04.16 we interfaced poly1305_update, poly1305_finish
*************************************************************************)
(*-------------------------------------------------------------------------
Pascal source (C) Copyright 2015-2016 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
const
poly1305_block_size = 16;
type
TPoly1305Key = packed array[0..31] of byte;
TPoly1305Mac = packed array[0..15] of byte;
type
poly1305_ctx = record
buffer: array[0..poly1305_block_size-1] of byte;
hrpad: packed array[0..59] of byte;
leftover: word;
final: byte;
end;
procedure poly1305_init(var ctx: poly1305_ctx; {$ifdef CONST}const{$endif} key: TPoly1305Key);
{Initialize context with key}
procedure poly1305_update(var ctx: poly1305_ctx; msg: pointer; nbytes: longint);
{-Update context with the data of another msg}
procedure poly1305_finish(var ctx: poly1305_ctx; var mac: TPoly1305Mac);
{-Process leftover, compute mac, clear state}
procedure poly1305_auth(var mac: TPoly1305Mac; msg: pointer; mlen: longint; {$ifdef CONST}const{$endif}key: TPoly1305Key);
{-All-in-one computation of the Poly1305 mac of msg using key}
function poly1305_verify({$ifdef CONST}const{$endif} mac1, mac2: TPoly1305Mac): boolean;
{-Return true if the two macs are identical}
function poly1305_selftest: boolean;
{-Simple self-test of Poly1305}
implementation
uses BTypes;
{$ifdef HAS_INT64}
{$define poly_32x32}
{$else}
{$define poly_16x16}
{$endif}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
{$ifdef poly_16x16}
type
TPoly_vec16 = packed array[0..9] of word; {Internal type for r,h,pad: size is multiple of 4}
TPoly_ctx16 = record
buffer: array[0..poly1305_block_size-1] of byte;
h,r,pad: TPoly_vec16;
leftover: word;
final: byte;
end;
type
TPoly1305LV = array[0..16] of longint;
{---------------------------------------------------------------------------}
procedure poly1305_init(var ctx: poly1305_ctx; {$ifdef CONST}const{$endif}key: TPoly1305Key);
{Initialize context with key}
var
t: packed array[0..15] of word;
begin
fillchar(ctx, sizeof(ctx), 0);
move(key, t, sizeof(key));
with TPoly_ctx16(ctx) do begin
{r = key and $ffffffc0ffffffc0ffffffc0fffffff}
r[0] := ( t[0] ) and $1fff;
r[1] := ((t[0] shr 13) or (t[1] shl 3)) and $1fff;
r[2] := ((t[1] shr 10) or (t[2] shl 6)) and $1f03;
r[3] := ((t[2] shr 7) or (t[3] shl 9)) and $1fff;
r[4] := ((t[3] shr 4) or (t[4] shl 12)) and $00ff;
r[5] := ((t[4] shr 1) ) and $1ffe;
r[6] := ((t[4] shr 14) or (t[5] shl 2)) and $1fff;
r[7] := ((t[5] shr 11) or (t[6] shl 5)) and $1f81;
r[8] := ((t[6] shr 8) or (t[7] shl 8)) and $1fff;
r[9] := ((t[7] shr 5) ) and $007f;
{save pad for later}
move(t[8],pad,16);
end;
end;
{---------------------------------------------------------------------------}
procedure poly1305_blocks(var ctx: poly1305_ctx; msg: pointer; nbytes: longint);
{-Process full blocks from msg}
var
st: TPoly_ctx16 absolute ctx;
t: packed array[0..7] of word;
d: array[0..9] of uint32;
c,w: uint32;
i,j: integer;
hibit: word;
begin
if ctx.final<>0 then hibit:=0 else hibit := 1 shl 11;
while (nbytes >= poly1305_block_size) do with st do begin
{h += m}
move(msg^,t,16);
inc(h[0], ( t[0] ) and $1fff);
inc(h[1], ((t[0] shr 13) or (t[1] shl 3)) and $1fff);
inc(h[2], ((t[1] shr 10) or (t[2] shl 6)) and $1fff);
inc(h[3], ((t[2] shr 7) or (t[3] shl 9)) and $1fff);
inc(h[4], ((t[3] shr 4) or (t[4] shl 12)) and $1fff);
inc(h[5], ((t[4] shr 1) ) and $1fff);
inc(h[6], ((t[4] shr 14) or (t[5] shl 2)) and $1fff);
inc(h[7], ((t[5] shr 11) or (t[6] shl 5)) and $1fff);
inc(h[8], ((t[6] shr 8) or (t[7] shl 8)) and $1fff);
inc(h[9], ((t[7] shr 5) ) or hibit );
{h *= r, (partial) h %= p}
c := 0;
for i:=0 to 9 do begin
d[i] := c;
for j:=0 to 9 do begin
if j<=i then w := r[i-j] else w := 5*r[i + 10 - j];
inc(d[i],w*h[j]);
if j=4 then begin
c := d[i] shr 13;
d[i] := d[i] and $1fff;
end;
end;
c := c + d[i] shr 13;
d[i] := d[i] and $1fff;
end;
c := ((c shl 2) + c); {c *= 5}
c := c + d[0];
d[0] := c and $1fff;
c := c shr 13;
inc(d[1], c);
for i:=0 to 9 do h[i] := word(d[i]);
inc(Ptr2Inc(msg), poly1305_block_size);
dec(nbytes, poly1305_block_size);
end;
end;
{---------------------------------------------------------------------------}
procedure poly1305_finish(var ctx: poly1305_ctx; var mac: TPoly1305Mac);
{-Process leftover, compute mac, clear state}
var
st: TPoly_ctx16 absolute ctx;
f: uint32;
g: array[0..9] of word;
c, mask: word;
i: integer;
begin
{process the remaining block}
if st.leftover>0 then begin
i := st.leftover;
st.buffer[i] := 1;
inc(i);
while i < poly1305_block_size do begin
st.buffer[i] := 0;
inc(i);
end;
st.final := 1;
poly1305_blocks(ctx, @st.buffer, poly1305_block_size);
end;
{fully carry h}
with st do begin
c := h[1] shr 13;
h[1] := h[1] and $1fff;
for i:=2 to 9 do begin
inc(h[i], c);
c := h[i] shr 13;
h[i] := h[i] and $1fff;
end;
inc(h[0], 5*c);
c := h[0] shr 13;
h[0] := h[0] and $1fff;
inc(h[1], c);
c := h[1] shr 13;
h[1] := h[1] and $1fff;
inc(h[2], c);
{compute h +- p}
g[0] := h[0] + 5;
c := g[0] shr 13;
g[0] := g[0] and $1fff;
for i:=1 to 9 do begin
g[i] := h[i] + c;
c := g[i] shr 13;
g[i] := g[i] and $1fff;
end;
dec(g[9], 1 shl 13);
{select h if h < p, or h + -p if h >= p}
{Fixed code: mask = (c ^ 1) - 1;}
mask := (c xor 1) - 1;
for i:=0 to 9 do g[i] := g[i] and mask;
mask := not(mask);
for i:=0 to 9 do h[i] := (h[i] and mask) or g[i];
{h = h % (2^128)}
h[0] := ((h[0] ) or (h[1] shl 13) ) and $ffff;
h[1] := ((h[1] shr 3) or (h[2] shl 10) ) and $ffff;
h[2] := ((h[2] shr 6) or (h[3] shl 7) ) and $ffff;
h[3] := ((h[3] shr 9) or (h[4] shl 4) ) and $ffff;
h[4] := ((h[4] shr 12) or (h[5] shl 1) or (h[6] shl 14)) and $ffff;
h[5] := ((h[6] shr 2) or (h[7] shl 11) ) and $ffff;
h[6] := ((h[7] shr 5) or (h[8] shl 8) ) and $ffff;
h[7] := ((h[8] shr 8) or (h[9] shl 5) ) and $ffff;
{mac = (h + pad) % (2^128)}
f := uint32(h[0]) + pad[0];
h[0] := word(f);
for i:=1 to 7 do begin
f := ((f shr 16) + h[i]) + pad[i];
h[i] := word(f);
end;
end;
move(st.h, mac, sizeof(mac));
{zero out the state}
fillchar(st.h, sizeof(st.h), 0);
fillchar(st.r, sizeof(st.r), 0);
fillchar(st.pad, sizeof(st.pad), 0);
end;
{$endif}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
{$ifdef poly_32x32}
type
TPoly_vec32 = packed array[0..4] of uint32; {Internal type for r,h,pad: size is multiple of 4}
TPoly_ctx32 = record
buffer: array[0..poly1305_block_size-1] of byte;
h,r,pad: TPoly_vec32;
leftover: word;
final: byte;
end;
{$ifdef VER70}
type
int64 = longint; {Use for development only!!, gives wrong results!!}
{$endif}
{$ifndef HAS_UINT64}
type
uint64 = int64; {Used for D4, D5, D6}
{$endif}
{---------------------------------------------------------------------------}
procedure poly1305_init(var ctx: poly1305_ctx; {$ifdef CONST}const{$endif}key: TPoly1305Key);
{-Initilalize context with key}
begin
fillchar(ctx, sizeof(ctx), 0);
with TPoly_ctx32(ctx) do begin
{r &= 0xffffffc0ffffffc0ffffffc0fffffff}
r[0] := puint32(@key[ 0])^ and $3ffffff;
r[1] := (puint32(@key[ 3])^ shr 2) and $3ffff03;
r[2] := (puint32(@key[ 6])^ shr 4) and $3ffc0ff;
r[3] := (puint32(@key[ 9])^ shr 6) and $3f03fff;
r[4] := (puint32(@key[12])^ shr 8) and $00fffff;
{save pad for later}
pad[0] := puint32(@key[16])^;
pad[1] := puint32(@key[20])^;
pad[2] := puint32(@key[24])^;
pad[3] := puint32(@key[28])^;
end;
end;
{---------------------------------------------------------------------------}
procedure poly1305_blocks(var ctx: poly1305_ctx; msg: pointer; nbytes: longint);
{-Process full blocks from msg}
var
hibit,c: uint32;
r0,r1,r2,r3,r4: uint32;
s1,s2,s3,s4: uint32;
h0,h1,h2,h3,h4: uint32;
d0,d1,d2,d3,d4: uint64;
st: TPoly_ctx32 absolute ctx;
pm: puint32;
begin
if st.final<>0 then hibit := 0 else hibit := uint32(1) shl 24;
r0 := st.r[0];
r1 := st.r[1];
r2 := st.r[2];
r3 := st.r[3];
r4 := st.r[4];
s1 := r1 * 5;
s2 := r2 * 5;
s3 := r3 * 5;
s4 := r4 * 5;
h0 := st.h[0];
h1 := st.h[1];
h2 := st.h[2];
h3 := st.h[3];
h4 := st.h[4];
pm := msg;
while (nbytes >= poly1305_block_size) do begin
{h += m[i]}
inc(h0, (pm^) and $3ffffff); inc(Ptr2Inc(pm),3); {->msg[ 3]}
inc(h1, (pm^ shr 2) and $3ffffff); inc(Ptr2Inc(pm),3); {->msg[ 6]}
inc(h2, (pm^ shr 4) and $3ffffff); inc(Ptr2Inc(pm),3); {->msg[ 9]}
inc(h3, (pm^ shr 6) and $3ffffff); inc(Ptr2Inc(pm),3); {->msg[12]}
inc(h4, (pm^ shr 8) or hibit); inc(Ptr2Inc(pm),4); {->msg[16]}
{h *= r}
d0 := (uint64(h0)*r0) + (uint64(h1)*s4) + (uint64(h2)*s3) + (uint64(h3)*s2) + (uint64(h4)*s1);
d1 := (uint64(h0)*r1) + (uint64(h1)*r0) + (uint64(h2)*s4) + (uint64(h3)*s3) + (uint64(h4)*s2);
d2 := (uint64(h0)*r2) + (uint64(h1)*r1) + (uint64(h2)*r0) + (uint64(h3)*s4) + (uint64(h4)*s3);
d3 := (uint64(h0)*r3) + (uint64(h1)*r2) + (uint64(h2)*r1) + (uint64(h3)*r0) + (uint64(h4)*s4);
d4 := (uint64(h0)*r4) + (uint64(h1)*r3) + (uint64(h2)*r2) + (uint64(h3)*r1) + (uint64(h4)*r0);
{(partial) h %= p}
c := uint32(d0 shr 26); h0 := uint32(d0 and $3ffffff); inc(d1,c);
c := uint32(d1 shr 26); h1 := uint32(d1 and $3ffffff); inc(d2,c);
c := uint32(d2 shr 26); h2 := uint32(d2 and $3ffffff); inc(d3,c);
c := uint32(d3 shr 26); h3 := uint32(d3 and $3ffffff); inc(d4,c);
c := uint32(d4 shr 26); h4 := uint32(d4 and $3ffffff); inc(h0, c*5);
c := h0 shr 26; h0 := h0 and $3ffffff; inc(h1, c);
dec(nbytes, poly1305_block_size);
end;
st.h[0] := h0;
st.h[1] := h1;
st.h[2] := h2;
st.h[3] := h3;
st.h[4] := h4;
end;
{---------------------------------------------------------------------------}
procedure poly1305_finish(var ctx: poly1305_ctx; var mac: TPoly1305Mac);
{-Process leftover, compute mac, clear state}
var
g0,g1,g2,g3,g4: uint32;
h0,h1,h2,h3,h4: uint32;
c,mask: uint32;
f: uint64;
i: integer;
st: TPoly_ctx32 absolute ctx;
begin
{process the remaining block}
if st.leftover>0 then begin
i := st.leftover;
st.buffer[i] := 1;
inc(i);
while i < poly1305_block_size do begin
st.buffer[i] := 0;
inc(i);
end;
st.final := 1;
poly1305_blocks(ctx, @st.buffer, poly1305_block_size);
end;
{fully carry h}
with st do begin
h0 := st.h[0];
h1 := st.h[1];
h2 := st.h[2];
h3 := st.h[3];
h4 := st.h[4];
c := h1 shr 26; h1 := h1 and $3ffffff;
inc(h2,c); c := h2 shr 26; h2 := h2 and $3ffffff;
inc(h3,c); c := h3 shr 26; h3 := h3 and $3ffffff;
inc(h4,c); c := h4 shr 26; h4 := h4 and $3ffffff;
inc(h0,c*5); c := h0 shr 26; h0 := h0 and $3ffffff;
inc(h1,c);
{compute h +- p}
g0 := h0 + 5; c := g0 shr 26; g0 := g0 and $3ffffff;
g1 := h1 + c; c := g1 shr 26; g1 := g1 and $3ffffff;
g2 := h2 + c; c := g2 shr 26; g2 := g2 and $3ffffff;
g3 := h3 + c; c := g3 shr 26; g3 := g3 and $3ffffff;
g4 := h4 + c - (uint32(1) shl 26);
{select h if h < p, or h +- p if h >= p}
mask := (g4 shr ((sizeof(uint32) * 8) - 1)) - 1;
g0 := g0 and mask;
g1 := g1 and mask;
g2 := g2 and mask;
g3 := g3 and mask;
g4 := g4 and mask;
mask := not mask;
h0 := (h0 and mask) or g0;
h1 := (h1 and mask) or g1;
h2 := (h2 and mask) or g2;
h3 := (h3 and mask) or g3;
h4 := (h4 and mask) or g4;
{h = h % (2^128)}
{*WE-TODO: remove and $ffffffff}
h0 := ((h0 ) or (h1 shl 26)) and $ffffffff;
h1 := ((h1 shr 6) or (h2 shl 20)) and $ffffffff;
h2 := ((h2 shr 12) or (h3 shl 14)) and $ffffffff;
h3 := ((h3 shr 18) or (h4 shl 8)) and $ffffffff;
{mac = (h + pad) % (2^128) }
f := uint64(h0) + pad[0] ; h[0] := uint32(f);
f := uint64(h1) + pad[1] + (f shr 32); h[1] := uint32(f);
f := uint64(h2) + pad[2] + (f shr 32); h[2] := uint32(f);
f := uint64(h3) + pad[3] + (f shr 32); h[3] := uint32(f);
end;
move(st.h, mac, sizeof(mac));
{zero out the state}
fillchar(st.h, sizeof(st.h), 0);
fillchar(st.r, sizeof(st.r), 0);
fillchar(st.pad, sizeof(st.pad), 0);
end;
{$endif}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
procedure poly1305_update(var ctx: poly1305_ctx; msg: pointer; nbytes: longint);
{-Update context with the data of another msg}
var
i,want: integer;
begin
{handle leftover}
with ctx do begin
if leftover > 0 then begin
want := (poly1305_block_size - leftover);
if want > nbytes then want := nbytes;
for i:=0 to want-1 do begin
buffer[leftover + i] := pbyte(msg)^;
inc(Ptr2Inc(msg));
end;
dec(nbytes, want);
inc(Ptr2Inc(msg), want);
inc(leftover, want);
if leftover < poly1305_block_size then exit;
poly1305_blocks(ctx, @buffer, poly1305_block_size);
leftover := 0;
end;
{process full blocks}
if nbytes >= poly1305_block_size then begin
want := (nbytes and not(poly1305_block_size - 1));
poly1305_blocks(ctx, msg, want);
inc(Ptr2Inc(msg), want);
dec(nbytes, want);
end;
{store leftover}
if nbytes>0 then begin
for i:=0 to nbytes-1 do begin
buffer[leftover + i] := pbyte(msg)^;
inc(Ptr2Inc(msg));
end;
inc(leftover, nbytes);
end;
end;
end;
{---------------------------------------------------------------------------}
procedure poly1305_auth(var mac: TPoly1305Mac; msg: pointer; mlen: longint; {$ifdef CONST}const{$endif}key: TPoly1305Key);
{-All-in-one computation of the Poly1305 mac of msg using key}
var
ctx: poly1305_ctx;
begin
poly1305_init(ctx, key);
poly1305_update(ctx, msg, mlen);
poly1305_finish(ctx, mac);
end;
{---------------------------------------------------------------------------}
function poly1305_verify({$ifdef CONST}const{$endif}mac1, mac2: TPoly1305Mac): boolean;
{-Return true if the two macs are identical}
var
i: integer;
d: byte;
begin
d := 0;
for i:=0 to 15 do d := d or (mac1[i] xor mac2[i]);
poly1305_verify := d=0;
end;
{---------------------------------------------------------------------------}
function poly1305_selftest: boolean;
{-Simple self-test of Poly1305}
const
nacl_key: TPoly1305Key = (
$ee,$a6,$a7,$25,$1c,$1e,$72,$91,
$6d,$11,$c2,$cb,$21,$4d,$3c,$25,
$25,$39,$12,$1d,$8e,$23,$4e,$65,
$2d,$65,$1f,$a4,$c8,$cf,$f8,$80);
nacl_msg: array[0..130] of byte = (
$8e,$99,$3b,$9f,$48,$68,$12,$73,
$c2,$96,$50,$ba,$32,$fc,$76,$ce,
$48,$33,$2e,$a7,$16,$4d,$96,$a4,
$47,$6f,$b8,$c5,$31,$a1,$18,$6a,
$c0,$df,$c1,$7c,$98,$dc,$e8,$7b,
$4d,$a7,$f0,$11,$ec,$48,$c9,$72,
$71,$d2,$c2,$0f,$9b,$92,$8f,$e2,
$27,$0d,$6f,$b8,$63,$d5,$17,$38,
$b4,$8e,$ee,$e3,$14,$a7,$cc,$8a,
$b9,$32,$16,$45,$48,$e5,$26,$ae,
$90,$22,$43,$68,$51,$7a,$cf,$ea,
$bd,$6b,$b3,$73,$2b,$c0,$e9,$da,
$99,$83,$2b,$61,$ca,$01,$b6,$de,
$56,$24,$4a,$9e,$88,$d5,$f9,$b3,
$79,$73,$f6,$22,$a4,$3d,$14,$a6,
$59,$9b,$1f,$65,$4c,$b4,$5a,$74,
$e3,$55,$a5);
nacl_mac: TPoly1305Mac = (
$f3,$ff,$c7,$70,$3f,$94,$00,$e5,
$2a,$7d,$fb,$4b,$3d,$33,$05,$d9);
{generates a final value of (2^130 - 2) == 3}
wrap_key: TPoly1305Key = (
$02,$00,$00,$00,$00,$00,$00,$00,
$00,$00,$00,$00,$00,$00,$00,$00,
$00,$00,$00,$00,$00,$00,$00,$00,
$00,$00,$00,$00,$00,$00,$00,$00);
wrap_msg: array[0..15] of byte = (
$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,
$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff);
wrap_mac: TPoly1305Mac = (
$03,$00,$00,$00,$00,$00,$00,$00,
$00,$00,$00,$00,$00,$00,$00,$00);
{mac of the macs of messages of length 0 to 256, where the}
{key and messages have all their values set to the length }
total_key : TPoly1305Key = (
$01,$02,$03,$04,$05,$06,$07,
$ff,$fe,$fd,$fc,$fb,$fa,$f9,
$ff,$ff,$ff,$ff,$ff,$ff,$ff,
$ff,$ff,$ff,$ff,$ff,$ff,$ff,
0,0,0,0); {WE Note: these 0 are missing in original test vector}
total_mac: TPoly1305Mac = (
$64,$af,$e2,$e8,$d6,$ad,$7b,$bd,
$d2,$87,$f9,$7c,$44,$62,$3d,$39);
var
mac: TPoly1305Mac;
all_key: TPoly1305Key;
all_msg: array[byte] of byte;
ctx: poly1305_ctx;
i: integer;
test: boolean;
begin
test := true;
{Test 1}
fillchar(mac, sizeof(mac), 0);
poly1305_auth(mac, @nacl_msg, sizeof(nacl_msg), nacl_key);
test := test and poly1305_verify(nacl_mac, mac);
{Test 2}
fillchar(mac, sizeof(mac), 0);
poly1305_init(ctx, nacl_key);
poly1305_update(ctx, @nacl_msg[ 0], 32);
poly1305_update(ctx, @nacl_msg[ 32], 64);
poly1305_update(ctx, @nacl_msg[ 96], 16);
poly1305_update(ctx, @nacl_msg[112], 8);
poly1305_update(ctx, @nacl_msg[120], 4);
poly1305_update(ctx, @nacl_msg[124], 2);
poly1305_update(ctx, @nacl_msg[126], 1);
poly1305_update(ctx, @nacl_msg[127], 1);
poly1305_update(ctx, @nacl_msg[128], 1);
poly1305_update(ctx, @nacl_msg[129], 1);
poly1305_update(ctx, @nacl_msg[130], 1);
poly1305_finish(ctx, mac);
test := test and poly1305_verify(nacl_mac, mac);
{Test 3}
fillchar(mac, sizeof(mac), 0);
poly1305_auth(mac, @wrap_msg, sizeof(wrap_msg), wrap_key);
test := test and poly1305_verify(wrap_mac, mac);
{Test 4}
fillchar(mac, sizeof(mac), 0);
poly1305_init(ctx, total_key);
for i:=0 to 255 do begin
{set key and message to 'i,i,i..'}
fillchar(all_key, sizeof(all_key), i);
fillchar(all_msg, i, i);
poly1305_auth(mac, @all_msg, i, all_key);
poly1305_update(ctx, @mac, 16);
end;
poly1305_finish(ctx, mac);
test := test and poly1305_verify(total_mac, mac);
poly1305_selftest := test;
end;
end.
|
unit GMTermMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, GMGlobals, IniFiles, Devices.ModbusBase, GMConst,
Vcl.ComCtrls, Math, Devices.Tecon.Common, Connection.Base, Connection.COM, WinSock,
Connection.TCP, Connection.UDP, Threads.Base, StrUtils, Devices.Logica.Base, System.Win.ScktComp;
type
TListenComThread = class(TGMThread)
protected
FConnectionObject: TConnectionObjectBase;
procedure SafeExecute(); override;
constructor Create();
end;
TForm1 = class(TForm)
btGo: TButton;
Memo1: TMemo;
cmbTxt: TComboBox;
PageControl1: TPageControl;
tsCOM: TTabSheet;
tsEthernet: TTabSheet;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
lePort: TLabeledEdit;
cmbBaud: TComboBox;
leLen: TLabeledEdit;
cmbStopBits: TComboBox;
cmbParity: TComboBox;
Label1: TLabel;
cmbMode: TComboBox;
cmbTrailing: TComboBox;
cbListen: TCheckBox;
Label2: TLabel;
rgProtocol: TRadioGroup;
leIP: TLabeledEdit;
leTCPPort: TLabeledEdit;
leWaitFirst: TLabeledEdit;
leWaitNext: TLabeledEdit;
ssListen: TServerSocket;
cbRepeat: TCheckBox;
Timer1: TTimer;
btBreak: TButton;
procedure btGoClick(Sender: TObject);
procedure cbListenClick(Sender: TObject);
procedure lePortChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure PageControl1Change(Sender: TObject);
procedure cmbTxtKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure rgProtocolClick(Sender: TObject);
procedure ssListenClientRead(Sender: TObject; Socket: TCustomWinSocket);
procedure ssListenAccept(Sender: TObject; Socket: TCustomWinSocket);
procedure ssListenGetSocket(Sender: TObject; Socket: NativeInt; var ClientSocket: TServerClientWinSocket);
procedure Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure cbRepeatClick(Sender: TObject);
procedure btBreakClick(Sender: TObject);
private
ListenPortThread: TGMThread;
procedure SaveParams;
procedure LoadParams;
procedure SaveHistory(const s: string);
procedure ListenPort(bListen: bool);
function CreateConnectionObject: TConnectionObjectBase;
procedure ApplyTrailing(obj: TConnectionObjectBase; trailingIndex: int);
procedure ProcessExchangeBlockData(thr: TConnectionObjectBase; et: TExchangeType);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TListenComThread }
constructor TListenComThread.Create;
begin
inherited Create();
FConnectionObject := Form1.CreateConnectionObject();
FConnectionObject.InitEquipmentBeforeExchange := false;
end;
procedure TListenComThread.SafeExecute;
begin
while not Terminated do
begin
case FConnectionObject.ExchangeBlockData(etRec) of
ccrBytes:
begin
Form1.Memo1.Lines.Add(FormatDateTime('hh:nn:ss.zzz', Now()) + ' < ' + ArrayToString(FConnectionObject.buffers.BufRec, FConnectionObject.buffers.NumberOfBytesRead, true, true));
end;
ccrError:
begin
Form1.Memo1.Lines.Add(FormatDateTime('hh:nn:ss.zzz', Now()) + ' Error');
end;
ccrEmpty:
begin
//Form1.Memo1.Lines.Add('No responce');
end;
end;
sleep(200);
end;
end;
procedure TForm1.SaveHistory(const s: string);
var n: int;
begin
if s = '' then Exit;
n := cmbTxt.Items.IndexOf(s);
if n = 0 then Exit;
if n > 0 then
cmbTxt.Items.Delete(n);
cmbTxt.Items.Insert(0, s);
cmbTxt.Text := s;
SaveParams();
end;
function TForm1.CreateConnectionObject(): TConnectionObjectBase;
begin
if PageControl1.ActivePageIndex = 0 then
begin
Result := TConnectionObjectCOM.Create();
TConnectionObjectCOM(Result).nPort := StrToInt(lePort.Text);
TConnectionObjectCOM(Result).nBaudRate := StrToInt(cmbBaud.Text);
TConnectionObjectCOM(Result).nParity := cmbParity.ItemIndex;
TConnectionObjectCOM(Result).nStopBits := cmbStopBits.ItemIndex;
TConnectionObjectCOM(Result).nWordLen := StrToInt(leLen.Text);
end
else
begin
if rgProtocol.ItemIndex = 0 then
begin
Result := TConnectionObjectTCP_OwnSocket.Create();
TConnectionObjectTCP_OwnSocket(Result).Host := leIP.Text;
TConnectionObjectTCP_OwnSocket(Result).Port := StrToInt(leTCPPort.Text);
end
else
begin
Result := TConnectionObjectUDP.Create();
TConnectionObjectUDP(Result).UDPObject.Host := leIP.Text;
TConnectionObjectUDP(Result).UDPObject.Port := StrToInt(leTCPPort.Text);
TConnectionObjectUDP(Result).UDPObject.ReceiveTimeout := StrToIntDef(leWaitFirst.Text, 1000);
end;
end;
Result.WaitFirst := StrToIntDef(leWaitFirst.Text, 1000);
Result.WaitNext := StrToIntDef(leWaitNext.Text, 100);
end;
procedure TForm1.ApplyTrailing(obj: TConnectionObjectBase; trailingIndex: int);
begin
case cmbTrailing.ItemIndex of
1:
begin
obj.buffers.BufSend[obj.buffers.LengthSend] := 13;
inc(obj.buffers.LengthSend);
end;
2:
begin
obj.buffers.BufSend[obj.buffers.LengthSend] := 26;
inc(obj.buffers.LengthSend);
end;
3:
begin
obj.buffers.BufSend[obj.buffers.LengthSend] := 13;
obj.buffers.BufSend[obj.buffers.LengthSend + 1] := 10;
inc(obj.buffers.LengthSend, 2);
end;
4:
begin
Modbus_CRC(obj.buffers.BufSend, obj.buffers.LengthSend);
inc(obj.buffers.LengthSend, 2);
end;
5: // Tecon_CRC + 0x16
begin
Tecon_CRC(obj.buffers.BufSend, obj.buffers.LengthSend);
inc(obj.buffers.LengthSend, 2);
end;
6: // Ëîãèêà ÑÏÒ941, 943
begin
LogicaM4_CRC(obj.buffers.BufSend, obj.buffers.LengthSend);
inc(obj.buffers.LengthSend, 2);
end;
7: // Ëîãèêà ÑÏÒ961
begin
LogicaSPBUS_CRC(obj.buffers.BufSend, obj.buffers.LengthSend);
inc(obj.buffers.LengthSend, 2);
end;
8:
begin
Modbus_LRC(obj.buffers.BufSend, obj.buffers.LengthSend);
obj.buffers.BufSend[obj.buffers.LengthSend + 2] := 13;
obj.buffers.BufSend[obj.buffers.LengthSend + 3] := 10;
inc(obj.buffers.LengthSend, 4);
end;
end;
end;
procedure TForm1.ProcessExchangeBlockData(thr: TConnectionObjectBase; et: TExchangeType);
begin
case thr.ExchangeBlockData(etSenRec) of
ccrBytes:
begin
Memo1.Lines.Add(FormatDateTime('hh:nn:ss.zzz', Now()) + ' < ' + ArrayToString(thr.buffers.BufRec, thr.buffers.NumberOfBytesRead, true, true));
end;
ccrError:
begin
Memo1.Lines.Add(FormatDateTime('hh:nn:ss.zzz', Now()) + ' Error ' + thr.LastError);
end;
ccrEmpty:
begin
Memo1.Lines.Add(FormatDateTime('hh:nn:ss.zzz', Now()) + ' No responce');
end;
end;
end;
procedure TForm1.btGoClick(Sender: TObject);
var l: TStringList;
i, n: int;
thr: TConnectionObjectBase;
s, v: string;
begin
Timer1.Enabled := false;
s := Trim(cmbTxt.Text);
SaveHistory(s);
if cbListen.Checked then
begin
ListenPort(false);
end;
thr := CreateConnectionObject();
Timer1.Interval := thr.WaitFirst;
l := TStringList.Create();
try
case cmbMode.ItemIndex of
0, 2:
begin
l.CommaText := s;
n := l.Count;
for i := 0 to l.Count - 1 do
begin
v := Trim(l[i]);
if v = '' then
dec(n)
else
thr.buffers.BufSend[i] := StrToInt(IfThen((cmbMode.ItemIndex = 0) and (v[1] <> '$'), '$') + v);
end;
end;
1:
begin
n := Length(s);
for i := 1 to n do
thr.buffers.BufSend[i - 1] := Ord(AnsiString(s)[i]);
end;
else Exit;
end;
thr.buffers.LengthSend := n;
ApplyTrailing(thr, cmbTrailing.ItemIndex);
Memo1.Lines.Add(FormatDateTime('hh:nn:ss.zzz', Now()) + ' ? ' + ArrayToString(thr.buffers.BufSend, thr.buffers.LengthSend, true, true));
ProcessExchangeBlockData(thr, etSenRec);
finally
l.Free();
thr.Free();
ListenPort(cbListen.Visible and cbListen.Checked);
if cbRepeat.Checked then
begin
Timer1.Enabled := true;
end;
end;
end;
procedure TForm1.btBreakClick(Sender: TObject);
var
thr: TConnectionObjectBase;
begin
thr := CreateConnectionObject();
try
if TConnectionObjectCOM(thr).SendBreak() then
begin
thr.FreePort();
ProcessExchangeBlockData(thr, etRec)
end
else
ShowMessageBox('Break failed ' + thr.LastError);
finally
thr.Free();
end;
end;
procedure TForm1.ListenPort(bListen: bool);
begin
cbListen.Checked := bListen;
if bListen then
begin
if PageControl1.ActivePageIndex = 0 then
begin
ListenPortThread := TListenComThread.Create()
end
else
begin
ssListen.Port := StrToIntDef(leTCPPort.Text, 0);
try
ssListen.Active := true;
except
cbListen.Checked := false;
raise;
end;
end;
end
else
begin
TryFreeAndNil(ListenPortThread);
ssListen.Active := false;
end;
end;
procedure TForm1.cbListenClick(Sender: TObject);
begin
if cbListen.Checked then
cbRepeat.Checked := false;
ListenPort(cbListen.Checked);
end;
procedure TForm1.cbRepeatClick(Sender: TObject);
begin
if cbRepeat.Checked then
cbListen.Checked := false;
end;
procedure TForm1.cmbTxtKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then
btGoClick(nil);
end;
procedure TForm1.SaveParams();
var f: TIniFile;
i: int;
begin
try
f := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
f.WriteInteger('COMMON', 'COM', StrToInt(lePort.Text));
f.WriteInteger('COMMON', 'BAUD', StrToInt(cmbBaud.Text));
f.WriteInteger('COMMON', 'PARITY', cmbParity.ItemIndex);
f.WriteInteger('COMMON', 'STOPBITS', cmbStopBits.ItemIndex);
f.WriteInteger('COMMON', 'WORDLEN', StrToInt(leLen.Text));
f.WriteInteger('COMMON', 'MODE', cmbMode.ItemIndex);
f.WriteInteger('COMMON', 'TRAILING', cmbTrailing.ItemIndex);
f.WriteString('COMMON', 'WAITFIRST', leWaitFirst.Text);
f.WriteString('COMMON', 'WAITNEXT', leWaitNext.Text);
f.WriteInteger('COMMON', 'PAGE', PageControl1.ActivePageIndex);
f.WriteInteger('COMMON', 'PROTOCOL', rgProtocol.ItemIndex);
f.WriteString('COMMON', 'IP', leIP.Text);
f.WriteString('COMMON', 'TCPPORT', leTCPPort.Text);
f.WriteInteger('HISTORY', 'Count', cmbTxt.Items.Count);
for i := 0 to cmbTxt.Items.Count - 1 do
f.WriteString('HISTORY', 'Record_' + IntToStr(i), cmbTxt.Items[i]);
f.UpdateFile();
f.Free();
except
end;
end;
procedure TForm1.ssListenAccept(Sender: TObject; Socket: TCustomWinSocket);
var opt: integer;
begin
opt := 1;
SetSockOpt(Socket.SocketHandle, SOL_SOCKET, SO_KEEPALIVE, PAnsiChar(@opt), SizeOf(opt));
end;
procedure TForm1.ssListenClientRead(Sender: TObject; Socket: TCustomWinSocket);
var cnt: int;
buf: array[0..1000] of byte;
action: string;
begin
try
action := 'CreateConn';
cnt := Socket.ReceiveBuf(buf, Length(buf));
Memo1.Lines.Add(FormatDateTime('hh:nn:ss.zzz', Now()) + ' TCP > ' + ArrayToString(buf, cnt, false, true));
except
on e: Exception do
Memo1.Lines.Add(FormatDateTime('hh:nn:ss.zzz', Now()) + 'TCP error: ' + action + ' - ' + e.Message);
end;
end;
procedure TForm1.ssListenGetSocket(Sender: TObject; Socket: NativeInt; var ClientSocket: TServerClientWinSocket);
begin
ClientSocket := TServerClientWinSocket.Create(Socket, Sender as TServerWinSocket);
end;
procedure TForm1.LoadParams();
var f: TIniFile;
i, n: int;
s: string;
begin
try
f := TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
lePort.Text := f.ReadString('COMMON', 'COM', lePort.Text);
n := cmbBaud.ItemIndex;
cmbBaud.ItemIndex := cmbBaud.Items.IndexOf(f.ReadString('COMMON', 'BAUD', '9600'));
if cmbBaud.ItemIndex < 0 then
cmbBaud.ItemIndex := n;
cmbParity.ItemIndex := f.ReadInteger('COMMON', 'PARITY', cmbParity.ItemIndex);
cmbStopBits.ItemIndex := f.ReadInteger('COMMON', 'STOPBITS', cmbStopBits.ItemIndex);
leLen.Text := f.ReadString('COMMON', 'WORDLEN', leLen.Text);
cmbMode.ItemIndex := f.ReadInteger('COMMON', 'MODE', cmbMode.ItemIndex);
cmbTrailing.ItemIndex := f.ReadInteger('COMMON', 'TRAILING', cmbTrailing.ItemIndex);
leWaitFirst.Text := f.ReadString('COMMON', 'WAITFIRST', leWaitFirst.Text);
leWaitNext.Text := f.ReadString('COMMON', 'WAITNEXT', leWaitNext.Text);
PageControl1.ActivePageIndex := IfThen(f.ReadInteger('COMMON', 'PAGE', 1) = 1, 1, 0);
PageControl1Change(nil);
rgProtocol.ItemIndex := IfThen(f.ReadInteger('COMMON', 'PROTOCOL', 1) = 1, 1, 0);
leIP.Text := f.ReadString('COMMON', 'IP', '');
leTCPPort.Text := f.ReadString('COMMON', 'TCPPORT', '');
n := f.ReadInteger('HISTORY', 'Count', 0);
for i := 0 to n - 1 do
begin
s := Trim(f.ReadString('HISTORY', 'Record_' + IntToStr(i), ''));
if s <> '' then
cmbTxt.Items.Add(s);
end;
f.Free();
except
end;
end;
procedure TForm1.Memo1KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Key = ord('A')) then
Memo1.SelectAll();
end;
procedure TForm1.PageControl1Change(Sender: TObject);
begin
ListenPort(false);
end;
procedure TForm1.rgProtocolClick(Sender: TObject);
begin
ListenPort(false);
end;
procedure TForm1.lePortChange(Sender: TObject);
begin
SaveParams();
end;
procedure TForm1.FormShow(Sender: TObject);
begin
LoadParams();
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
SaveParams();
end;
end.
|
unit FrmExercise;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ImgList, Vcl.ComCtrls,
Vcl.StdCtrls, System.ImageList, xExerciseControl, xExerciseInfo,
System.Actions, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan,
Vcl.Menus, FrmQuestionListC, xQuestionInfo, FrmQInfoC, Vcl.Buttons, xSortControl;
type
TfExercise = class(TForm)
grp2: TGroupBox;
lvExercises: TListView;
imglstil1: TImageList;
actnmngr1: TActionManager;
actAddPath: TAction;
pmn1: TPopupMenu;
actReName: TAction;
mntmReName: TMenuItem;
actSelectQuestion: TAction;
actUpPath: TAction;
btnUpPath: TSpeedButton;
actDel: TAction;
mntmDel: TMenuItem;
mntmAddPath: TMenuItem;
mntmSelectQuestion: TMenuItem;
mntmN1: TMenuItem;
procedure actAddPathExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure actSelectQuestionExecute(Sender: TObject);
procedure lvExercisesDblClick(Sender: TObject);
procedure actUpPathExecute(Sender: TObject);
procedure actDelExecute(Sender: TObject);
procedure lvExercisesContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
procedure pmn1Popup(Sender: TObject);
procedure actReNameExecute(Sender: TObject);
private
{ Private declarations }
FQuestionList : TfQuestionListC;
FIsClientExercise: Boolean;
/// <summary>
/// 刷新目录
/// </summary>
procedure RefurshExercise;
/// <summary>
/// 进入答题环境
/// </summary>
procedure AnswerQuestion(AQuesiton : TQuestionInfo);
public
{ Public declarations }
/// <summary>
/// 是否是客户端练习模式
/// </summary>
property IsClientExercise : Boolean read FIsClientExercise write FIsClientExercise;
end;
var
fExercise: TfExercise;
implementation
{$R *.dfm}
{ TfExercise }
procedure TfExercise.actAddPathExecute(Sender: TObject);
var
sName : string;
AExerciseInfo : TExerciseInfo;
begin
sName := InputBox('输入','目录名称', '新建目录');
if not ExerciseControl.IsExist(sName) then
begin
AExerciseInfo := TExerciseInfo.Create;
AExerciseInfo.Imageindex := 0;
AExerciseInfo.Path := ExerciseControl.CurrentPath;
AExerciseInfo.Ename := sName;
ExerciseControl.AddExercise(AExerciseInfo);
RefurshExercise;
end
else
begin
Application.MessageBox('目录已存在,请重新建立目录!', '', MB_OK + MB_ICONINFORMATION);
end;
end;
procedure TfExercise.actDelExecute(Sender: TObject);
var
i : Integer;
AExerciseInfo : TExerciseInfo;
begin
if Application.MessageBox('确定要删除选择记录(记录下的内容全部删除)!', '提示', MB_OKCANCEL +
MB_ICONQUESTION) = IDOK then
begin
for i := 0 to lvExercises.Items.Count - 1 do
begin
if lvExercises.Items[i].Selected then
begin
AExerciseInfo := TExerciseInfo(lvExercises.Items[i].Data);
ExerciseControl.DelExercise(AExerciseInfo, True);
end;
end;
ExerciseControl.LoadExercise(ExerciseControl.CurrentPath);
RefurshExercise;
end;
end;
procedure TfExercise.actReNameExecute(Sender: TObject);
var
sName : string;
AExerciseInfo : TExerciseInfo;
begin
if lvExercises.ItemIndex <> -1 then
begin
AExerciseInfo := TExerciseInfo(lvExercises.Items[lvExercises.ItemIndex].Data);
sName := InputBox('输入','目录名称', AExerciseInfo.Ename);
if not ExerciseControl.IsExist(sName) then
begin
ExerciseControl.ReName(AExerciseInfo, sName);
RefurshExercise;
end
else
begin
Application.MessageBox('目录已存在!', '', MB_OK + MB_ICONINFORMATION);
end;
end;
end;
procedure TfExercise.actSelectQuestionExecute(Sender: TObject);
var
AQInfo : TQuestionInfo;
AExerciseInfo : TExerciseInfo;
begin
AQInfo := FQuestionList.SelOneQuestion;
if Assigned(AQInfo) then
begin
if not ExerciseControl.IsExist(AQInfo.QName) then
begin
AExerciseInfo := TExerciseInfo.Create;
AExerciseInfo.Imageindex := 1;
AExerciseInfo.Ptype := 1;
AExerciseInfo.Path := ExerciseControl.CurrentPath;
AExerciseInfo.Ename := AQInfo.QName;
AExerciseInfo.Code1 := AQInfo.QCode;
AExerciseInfo.Code2 := AQInfo.QRemark2;
AExerciseInfo.Remark := IntToStr(AQInfo.QID);
ExerciseControl.AddExercise(AExerciseInfo);
end
else
begin
Application.MessageBox('习题已经存在,请重新选择!', '', MB_OK + MB_ICONINFORMATION);
end;
RefurshExercise;
end;
end;
procedure TfExercise.actUpPathExecute(Sender: TObject);
begin
ExerciseControl.LoadPreviousPath;
RefurshExercise;
end;
procedure TfExercise.AnswerQuestion(AQuesiton: TQuestionInfo);
begin
end;
procedure TfExercise.FormCreate(Sender: TObject);
begin
FQuestionList := TfQuestionListC.Create(nil);
FIsClientExercise := False;
ExerciseControl.LoadExercise();
RefurshExercise;
end;
procedure TfExercise.FormDestroy(Sender: TObject);
begin
FQuestionList.Free;
end;
procedure TfExercise.lvExercisesContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
begin
if FIsClientExercise then
begin
lvExercises.PopupMenu := nil;
Handled := False;
end
else
begin
if Assigned(lvExercises.Selected) then
begin
actReName.Enabled := TExerciseInfo(lvExercises.Selected.Data).Ptype = 0
end;
end;
end;
procedure TfExercise.lvExercisesDblClick(Sender: TObject);
var
AExerciseInfo : TExerciseInfo;
AQInfo : TQuestionInfo;
begin
if Assigned(lvExercises.Selected) then
begin
AExerciseInfo := TExerciseInfo(lvExercises.Selected.Data);
case AExerciseInfo.Ptype of
0 :
begin
ExerciseControl.LoadExercise(ExerciseControl.CurrentPath + '\' + AExerciseInfo.Ename);
RefurshExercise;
end;
1 :
begin
AQInfo := TQuestionInfo.Create;
AQInfo.QCode := AExerciseInfo.Code1;
AQInfo.QName := AExerciseInfo.Ename;
AQInfo.QRemark2 := AExerciseInfo.Code2;
if FIsClientExercise then
begin
AnswerQuestion(AQInfo);
end
else
begin
with TfQInfo.Create(nil) do
begin
ShowInfoReadOnly(AQInfo);
ShowModal;
Free;
end;
end;
AQInfo.Free;
end;
end;
end;
end;
procedure TfExercise.pmn1Popup(Sender: TObject);
begin
Caption := '1';
end;
procedure TfExercise.RefurshExercise;
var
i : Integer;
AExerciseInfo : TExerciseInfo;
begin
lvExercises.Clear;
for i := 0 to ExerciseControl.ExerciseList.Count - 1 do
begin
AExerciseInfo := ExerciseControl.ExerciseInfo[i];
if Assigned(AExerciseInfo) then
begin
with lvExercises.Items.Add do
begin
Caption := AExerciseInfo.Ename;
ImageIndex := AExerciseInfo.Imageindex;
Data := AExerciseInfo;
end;
end;
end;
actUpPath.Enabled := ExerciseControl.CurrentPath <> '';
end;
end.
|
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+}
unit Screen;
Interface
Procedure scrInitPages(Pages : Byte);
Procedure scrDeInitPages;
Procedure scrStoreScreen(Page : Byte);
Procedure scrRestoreScreen(Page : Byte);
Implementation
uses Strings, Global;
Const
MaxPages = 20;
Type
PageType = Array [1..50,1..80] Of Word;
PageArray = Array [1..MaxPages] Of ^PageType;
Var
ScrPtr : ^PageType;
ScrPages : PageArray;
PageInMem : Array [1..MaxPages] Of Boolean;
VideoMode : ^Byte;
UseDisk : Boolean;
Var
MPages : Byte;
SaveExitProc : Pointer;
Procedure scrInitPages(Pages : Byte);
Var
Loop : Byte;
begin
If Pages>MaxPages Then
Pages := MaxPages;
For Loop:=1 To Pages Do
If (MaxAvail>=SizeOf(PageType)) And (Not UseDisk) Then
begin
PageInMem[Loop] := True;
GetMem(ScrPages[Loop],SizeOf(PageType));
end
Else
begin
PageInMem[Loop] := False;
ScrPages[Loop] := NIL;
end;
MPages := Pages;
end;
Procedure scrDeInitPages;
Var Loop : Byte;
begin
If MPages>0 Then
For Loop:=MPages DownTo 1 Do
If PageInMem[Loop] Then
begin
Release(ScrPages[Loop]);
PageInMem[Loop] := False;
end;
MPages := 0;
end;
Procedure scrStoreScreen(Page : Byte);
Var
F : File Of PageType;
begin
If Page<=MPages Then
begin
If PageInMem[Page] Then
Move(ScrPtr^,ScrPages[Page]^,SizeOf(PageType))
Else
begin
Assign(F,Cfg^.pathData+'INISCREEN.S'+St(Page));
{$I-}
ReWrite(F);
{$I+}
If IOResult=0 Then
begin
Write(F,ScrPtr^);
Close(F);
end;
end;
end;
end;
Procedure scrRestoreScreen(Page : Byte);
Var
F : File Of PageType;
begin
If Page<=MPages Then
begin
If PageInMem[Page] Then
Move(ScrPages[Page]^,ScrPtr^,SizeOf(PageType))
Else
begin
Assign(F,Cfg^.pathData+'INISCREEN.S'+St(Page));
{$I-}
Reset(F);
{$I+}
If IOResult=0 Then
begin
Read(F,ScrPtr^);
Close(F);
end;
end;
end;
end;
{$F+}
Procedure ScreenExitProc;
Var
Loop : Byte;
F : File;
begin
ExitProc := SaveExitProc;
If MPages>0 Then
For Loop:=1 To MPages Do
begin
Assign(F,'INISCREEN.S'+St(Loop));
{$I-} Erase(F); {$I+}
If IOResult <> 0 Then;
end;
end;
{$F-}
begin
VideoMode := Ptr(Seg0040,$0049);
If VideoMode^=7 Then
ScrPtr := Ptr(SegB000,$0000)
Else
ScrPtr := Ptr(SegB800,$0000);
MPages := 0;
UseDisk := False;
SaveExitProc := ExitProc;
ExitProc := @ScreenExitProc;
end.
(*
This simple Unit is able to store up to 20 screens. If there is enough free
heap all screens are stored to heap which is Really fast. If there is not
enough free heap or UseDisk=True all screens are stored virtually to disk. This
method isn't very fast, of course, but it helps you to save heap.
Use this Unit as follows:
Program ThisIsMyProgram;
Uses Screen;
begin
InitPages(5); { initialize 5 pages }
{...} { this is on you }
end.
*)
|
{***************************************************************************
*
* Orion-project.org Lazarus Helper Library
* Copyright (C) 2016-2017 by Nikolay Chunosov
*
* This file is part of the Orion-project.org Lazarus Helper Library
* https://github.com/Chunosov/orion-lazarus
*
* This Library is free software: you can redistribute it and/or modify it
* under the terms of the MIT License. See enclosed LICENSE.txt for details.
*
***************************************************************************}
unit OriXmlFile;
{$mode objfpc}{$H+}
{-$define TRACE_READING}
interface
uses
SysUtils, DOM, FGL;
type
TOriXmlFile = class
protected
FDoc: TXMLDocument;
FNode: TDOMNode;
FFormat: TFormatSettings;
public
constructor Create;
destructor Destroy; override;
procedure Close; virtual;
end;
TOriXmlFileWriter = class(TOriXmlFile)
private
FFileName: String;
procedure SetAttribute(const AName, AValue: String);
procedure SetBoolAttribute(const AName: String; AValue: Boolean);
procedure SetTextNode(const AName, AValue: String);
procedure SetValueNode(const AName: String; const AValue: Double);
public
constructor Create(const AFileName: String); reintroduce;
destructor Destroy; override;
procedure Open(const AName: String);
property Attribute[const AName: String]: String write SetAttribute;
property BoolAttribute[const AName: String]: Boolean write SetBoolAttribute;
property Text[const AName: String]: String write SetTextNode;
property Value[const AName: String]: Double write SetValueNode;
end;
TNodeListers = specialize TFPGMap<DOMString, TDOMNode>;
TOriXmlFileReader = class(TOriXmlFile)
private
FListers: TNodeListers;
FListed: TDOMNode;
function GetCurrentNode: TDOMNode;
function GetAttribute(const AName: String): String;
function GetBoolAttribute(const AName: String): Boolean;
function GetTextNode(const AName: String; Required: Boolean): String;
function GetTextNodeOptional(const AName: String): String;
function GetTextNodeRequired(const AName: String): String;
function GetValueNode(const AName: String): Double;
function GetListing(const AName: DOMString): TDOMNode;
procedure RemoveListing(const AName: DOMString);
procedure AppendListing(const AName: DOMString; ANode: TDOMNode);
public
constructor Create(const AFileName: String); reintroduce;
destructor Destroy; override;
procedure Open(const AName: String);
function TryOpen(const AName: String): Boolean;
procedure Close; override;
function List(const AName: String): Boolean;
function HasNode(const AName: String): Boolean;
property Attribute[const AName: String]: String read GetAttribute;
property BoolAttribute[const AName: String]: Boolean read GetBoolAttribute;
property Text[const AName: String]: String read GetTextNodeOptional;
property TextRequired[const AName: String]: String read GetTextNodeRequired;
property Value[const AName: String]: Double read GetValueNode;
property CurrentNode: TDOMNode read GetCurrentNode;
end;
EOriXmlFile = class(Exception)
end;
implementation
uses
{$ifdef TRACE_READING}
OriDebugConsole, StrUtils,
{$endif}
Math, LazUTF8, XMLRead, XMLWrite;
resourcestring
SFileNotFound = 'File "%s" does not exist.';
SNodeNotFound = 'Node "%s" not found in the parent "%s".';
SNotTextNode = '"%s" is not a text node.';
{%region Helpers}
function NotNull(AFirst, ASecond: TDOMNode): TDOMNode; inline;
begin
if Assigned(AFirst) then Result := AFirst else Result := ASecond;
end;
function GetPath(ANode: TDOMNode): DOMString;
var node: TDOMNode;
begin
Result := '';
node := ANode;
repeat
Result := '\' + node.NodeName + Result;
node := node.ParentNode;
until not Assigned(node) or (node.NodeType = DOCUMENT_NODE);
end;
function NodeToStr(ANode: TDOMNode): String;
begin
Result := Format('%s %d %s', [ANode.NodeName, ANode.NodeType, ANode.NodeValue]);
end;
{$ifdef TRACE_READING}
procedure Trace(const Msg: String); overload;
begin
DebugPrint(Msg);
end;
procedure Trace(const Msg: String; Args: array of const); overload;
begin
DebugPrint(Msg, Args);
end;
{$endif}
{%endregion}
{%region TOriXmlFile}
constructor TOriXmlFile.Create;
begin
FFormat := DefaultFormatSettings;
FFormat.DecimalSeparator := '.';
FFormat.ThousandSeparator := #0;
end;
destructor TOriXmlFile.Destroy;
begin
FDoc.Free;
end;
procedure TOriXmlFile.Close;
begin
FNode := FNode.ParentNode;
if FNode = FDoc then FNode := nil;
end;
{%endregion}
{%region TOriXmlFileWriter}
constructor TOriXmlFileWriter.Create(const AFileName: String);
begin
inherited Create;
FFileName := AFileName;
FDoc := TXMLDocument.Create;
end;
destructor TOriXmlFileWriter.Destroy;
begin
if FFileName <> '' then
try
WriteXMLFile(FDoc, UTF8ToSys(FFileName));
finally
inherited;
end;
end;
procedure TOriXmlFileWriter.Open(const AName: String);
begin
FNode := NotNull(FNode, FDoc).AppendChild(FDoc.CreateElement(UTF8ToUTF16(AName)));
end;
procedure TOriXmlFileWriter.SetAttribute(const AName, AValue: String);
var attr: TDOMAttr;
begin
if Assigned(FNode) then
begin
attr := FDoc.CreateAttribute(UTF8ToUTF16(AName));
attr.NodeValue := UTF8ToUTF16(AValue);
FNode.Attributes.SetNamedItem(attr);
end;
end;
procedure TOriXmlFileWriter.SetBoolAttribute(const AName: String; AValue: Boolean);
begin
SetAttribute(AName, BoolToStr(AValue, True));
end;
procedure TOriXmlFileWriter.SetTextNode(const AName, AValue: String);
begin
if Assigned(FNode) then
FNode.AppendChild(FDoc.CreateElement(UTF8ToUTF16(AName))).TextContent := UTF8ToUTF16(AValue);
end;
procedure TOriXmlFileWriter.SetValueNode(const AName: String; const AValue: Double);
var S: String;
begin
if IsNaN(AValue) then S := '' else S := FloatToStr(AValue, FFormat);
SetTextNode(AName, S);
end;
{%endregion}
{%region TOriXmlFileReader}
constructor TOriXmlFileReader.Create(const AFileName: String);
begin
inherited Create;
if not FileExists(UTF8ToSys(AFileName)) then
raise EOriXmlFile.CreateFmt(SFileNotFound, [AFileName]);
ReadXMLFile(FDoc, UTF8ToSys(AFileName));
FListers := TNodeListers.Create;
end;
destructor TOriXmlFileReader.Destroy;
begin
FListers.Free;
inherited;
end;
function TOriXmlFileReader.GetCurrentNode: TDOMNode;
begin
Result := NotNull(FListed, NotNull(FNode, FDoc));
end;
procedure TOriXmlFileReader.Open(const AName: String);
var node: TDOMNode;
begin
node := CurrentNode.FindNode(UTF8ToUTF16(AName));
if not Assigned(node) then
raise EOriXmlFile.CreateFmt(SNodeNotFound, [AName, GetPath(CurrentNode)]);
FNode := node;
FListed := nil;
{$ifdef TRACE_READING}
Trace('OPEN: %s (%s)', [AName, GetPath(CurrentNode)]);
{$endif}
end;
function TOriXmlFileReader.TryOpen(const AName: String): Boolean;
var node: TDOMNode;
begin
node := CurrentNode.FindNode(UTF8ToUTF16(AName));
if not Assigned(node) then Exit(False);
FNode := node;
FListed := nil;
Result := True;
{$ifdef TRACE_READING}
Trace('OPEN: %s (%s)', [AName, GetPath(CurrentNode)]);
{$endif}
end;
procedure TOriXmlFileReader.Close;
begin
{$ifdef TRACE_READING}
Trace('CLOSE: ' + GetPath(CurrentNode));
{$endif}
if Assigned(FListed) then
begin
RemoveListing(FListed.NodeName);
FListed := nil
end
else inherited;
// Previously opened node could be obtained as result of list()
// but not of open() method, so return previous listing state.
FListed := GetListing(GetPath(CurrentNode));
if Assigned(FListed) then FNode := FListed.ParentNode;
{$ifdef TRACE_READING}
Trace('Current: ' + GetPath(CurrentNode));
{$endif}
end;
function TOriXmlFileReader.GetListing(const AName: DOMString): TDOMNode;
var index: Integer;
begin
index := FListers.IndexOf(AName);
if index >= 0 then Result := FListers.Data[index] else Result := nil;
{$ifdef TRACE_READING}
Trace('Listing %sfound: %s', [IfThen(index < 0, 'not '), AName]);
{$endif}
end;
procedure TOriXmlFileReader.RemoveListing(const AName: DOMString);
var index: Integer;
begin
index := FListers.IndexOf(AName);
if index > -1 then FListers.Delete(index);
{$ifdef TRACE_READING}
Trace('Listing %sremoved: %s', [IfThen(index < 0, 'not found to be '), AName]);
{$endif}
end;
procedure TOriXmlFileReader.AppendListing(const AName: DOMString; ANode: TDOMNode);
begin
{$ifdef TRACE_READING}
Trace('Listing %s: %s', [IfThen(FListers.IndexOf(AName) < 0, 'added', 'updated'), AName]);
{$endif}
FListers[AName] := ANode;
end;
function TOriXmlFileReader.List(const AName: String): Boolean;
var
node: TDOMNode;
key: DOMString;
begin
{$ifdef TRACE_READING}
Trace('LIST: ' + AName);
Trace('Current: ' + GetPath(CurrentNode));
{$endif}
key := GetPath(NotNull(FNode, FDoc)) + '\' + UTF8ToUTF16(AName);
node := GetListing(key);
if Assigned(node) then
begin
FListed := node.NextSibling;
if Assigned(FListed)
then AppendListing(key, FListed)
else RemoveListing(key);
end
else
begin
FListed := CurrentNode.FindNode(UTF8ToUTF16(AName));
if Assigned(FListed) then
AppendListing(key, FListed)
end;
Result := Assigned(FListed);
end;
function TOriXmlFileReader.GetAttribute(const AName: String): String;
var node: TDOMNode;
begin
node := CurrentNode.Attributes.GetNamedItem(UTF8ToUTF16(AName));
if Assigned(node)
then Result := UTF16ToUTF8(node.NodeValue)
else Result := '';
end;
function TOriXmlFileReader.GetBoolAttribute(const AName: String): Boolean;
begin
if not TryStrToBool(GetAttribute(AName), Result) then Result := False;
end;
function TOriXmlFileReader.GetTextNode(const AName: String; Required: Boolean): String;
var node, txt: TDOMNode;
begin
node := CurrentNode.FindNode(UTF8ToUTF16(AName));
if not Assigned(node) then
begin
if Required then
raise EOriXmlFile.CreateFmt(SNodeNotFound, [AName, GetPath(CurrentNode)])
else Exit('');
end;
txt := node.FirstChild;
if not Assigned(txt) then Exit(''); // case: <node/>
if txt.NodeType <> TEXT_NODE then
raise EOriXmlFile.CreateFmt(SNotTextNode, [GetPath(node)]);
Result := UTF8Encode(txt.NodeValue);
end;
function TOriXmlFileReader.GetTextNodeOptional(const AName: String): String;
begin
Result := GetTextNode(AName, False);
end;
function TOriXmlFileReader.GetTextNodeRequired(const AName: String): String;
begin
Result := GetTextNode(AName, True);
end;
function TOriXmlFileReader.GetValueNode(const AName: String): Double;
var S: String;
begin
S := Trim(GetTextNode(AName, True));
if S = '' then Result := NaN else Result := StrToFloat(S, FFormat);
end;
function TOriXmlFileReader.HasNode(const AName: String): Boolean;
begin
Result := Assigned(CurrentNode.FindNode(UTF8ToUTF16(AName)));
end;
{%endregion}
end.
|
unit uXplPluginEngine;
{$Define DEBUG}
interface
uses MemMap, XPLMDataAccess, uXplCommon;
type
{ TXplEngine }
TXplEngine = class (TObject)
fMM: TMemMap;
fPosCountDown: Integer;
fLatitudeRef: XPLMDataRef;
fLongitudeRef: XPLMDataRef;
fHeadingRef: XPLMDataRef;
fHeightRef: XPLMDataRef;
fDebugging: Boolean;
pBuffer: PXplComRecord;
fTextToBeDrawn: String;
fScreenWidth: Integer;
fScreenHeight: Integer;
fBasicFontHeight: Integer;
fBasicFontWidth: Integer;
fTextFloatPosition: Single;
fTextHideTs: TDateTime;
procedure DebugLog(Value: String);
function GetArrayLength(pDataRef: XPLMDataRef ;pDataType: XPLMDataTypeID): Integer;
procedure ProcessSlot(pSlot: PXplComSlot);
procedure String2XplValue(pIn:String; pOut: PXplValue; pDataType: XPLMDataTypeID);
procedure SimpleReadWrite(pSlot: PXplComSlot; pMakeChecks: Boolean);
procedure ToggleVar(pSlot: PXplComSlot);
procedure InitGlValues;
public
{ Public declarations }
constructor Create;
destructor Destroy; Override;
procedure XplTick;
procedure DrawText();
end;
implementation
uses Classes, SysUtils, Windows, XPLMUtilities, XPLMGraphics, gl, glu, XPLMDisplay, dateutils;
{ TXplEngine }
constructor TXplEngine.Create;
begin
pBuffer := nil;
fDebugging := FileExists('hidmacros.log');
fPosCountDown := -1;
fTextToBeDrawn:='';
fTextFloatPosition := 0;
fMM := TMemMap.Create(XPL_MEM_FILE, SizeOf(TXplComRecord));
if fMM.Memory <> nil then
begin
pBuffer := fMM.Memory;
//DebugLog(Format('pBuffer addr is %s.', [IntToStr(ULong(pBuffer))]));
//DebugLog(Format('Slot size: %d, mem size: %d', [SizeOf(TXplComSlot), SizeOf(TXplComRecord)]));
if pBuffer^.HdmConnected > 0 then
begin
DebugLog('Hidmacros already connected to shared memory.');
fPosCountDown := pBuffer^.PosInterval;
end
else
DebugLog('Hidmacros not yet connected to shared memory.');
pBuffer^.XplConnected := 1;
pBuffer^.XplRequestFlag := 0;
end
else
DebugLog('FATAL: Shared memory not created.');
InitGlValues;
end;
procedure TXplEngine.DebugLog(Value: String);
var
tmp: PChar;
lVal: String;
logFile: TextFile;
begin
if pBuffer = nil then
exit;
if not fDebugging then
exit;
lVal := 'XPLHDMplugin:'+ Value;
{$IFDEF OUTPUTDEBUGSTRING}
GetMem(tmp, Length(lVal) + 1);
try
StrPCopy(tmp, lVal);
OutputDebugString(tmp);
finally
FreeMem(tmp);
end;
{$ENDIF}
// to file
AssignFile(logFile, 'hidmacros.log');
if FileExists('hidmacros.log') then
Append(logFile)
else
Rewrite(logFile);
WriteLn(logFile, lVal);
CloseFile(logFile);
end;
destructor TXplEngine.Destroy;
begin
if pBuffer <> nil then
pBuffer^.XplConnected := 0;
fMM.Free;
inherited;
end;
function TXplEngine.GetArrayLength(pDataRef: XPLMDataRef ;pDataType: XPLMDataTypeID): Integer;
begin
Result := 0;
if (pDataType = xplmType_IntArray) then
Result := XPLMGetDatavi(pDataRef, nil, 0, 0);
if (pDataType = xplmType_FloatArray) then
Result := XPLMGetDatavf(pDataRef, nil, 0, 0);
if (pDataType = xplmType_Data) then
Result := XPLMGetDatab(pDataRef, nil, 0, 0);
end;
procedure TXplEngine.XplTick;
var
i: Integer;
lAllDone : Boolean;
begin
//DebugLog('Tick');
if pBuffer = nil then
exit;
if pBuffer^.XplRequestFlag = 1 then
begin
for I := 0 to COM_SLOTS_COUNT - 1 do
if pBuffer^.ComSlots[i].XplRequestFlag = 1 then
ProcessSlot(@pBuffer^.ComSlots[i]);
lAllDone := True;
for I := 0 to COM_SLOTS_COUNT - 1 do
lAllDone := lAllDone and (pBuffer^.ComSlots[i].XplRequestFlag = 0);
if lAllDone then
pBuffer^.XplRequestFlag := 0;
end;
if (pBuffer^.HdmConnected > 0) and (fPosCountDown > 0) then
begin
Dec(fPosCountDown);
if (fPosCountDown = 0) then
begin
// refresh pos values
if fLatitudeRef = nil then
fLatitudeRef := XPLMFindDataRef('sim/flightmodel/position/latitude');
if fLongitudeRef = nil then
fLongitudeRef := XPLMFindDataRef('sim/flightmodel/position/longitude');
if fHeadingRef = nil then
fHeadingRef := XPLMFindDataRef('sim/flightmodel/position/psi');
if fHeightRef = nil then
fHeightRef := XPLMFindDataRef('sim/flightmodel/position/elevation');
if fLatitudeRef <> nil then
pBuffer^.Latitude := XPLMGetDatad(fLatitudeRef);
if fLongitudeRef <> nil then
pBuffer^.Longitude := XPLMGetDatad(fLongitudeRef);
if fHeadingRef <> nil then
pBuffer^.Heading := XPLMGetDataf(fHeadingRef);
if fHeightRef <> nil then
pBuffer^.Height := XPLMGetDataf(fHeightRef);
fPosCountDown := pBuffer^.PosInterval;
//DebugLog('Pos: lat ' + FloatToStr(pBuffer^.Latitude) +
// ', lon ' + FloatToStr(pBuffer^.Longitude) +
// ', heading ' + FloatToStr(pBuffer^.Heading));
end;
end;
DrawText();
end;
procedure TXplEngine.ProcessSlot(pSlot: PXplComSlot);
var
lMakeChecks: Boolean;
begin
if pSlot^.XplRequestFlag = 1 then
begin
// check command
if (pSlot^.HDMcommand = HDMC_GET_VAR) or
(pSlot^.HDMcommand = HDMC_SET_VAR) or
(pSlot^.HDMcommand = HDMC_TOGGLE_NEXT) or
(pSlot^.HDMcommand = HDMC_TOGGLE_PREVIOUS) or
(pSlot^.HDMcommand = HDMC_SWITCH_NEXT) or
(pSlot^.HDMcommand = HDMC_SWITCH_PREVIOUS)
then
begin
// is already registered?
if pSlot^.DataRef = 0 then
begin
// register first
DebugLog('Finding ref for ' + pSlot^.ValueName);
pSlot^.DataRef := Pointer2Pointer8b(XPLMFindDataRef(pSlot^.ValueName));
if pSlot^.DataRef <> 0 then
begin
DebugLog(Format('Got valid pointer %x.', [pSlot^.DataRef]));
pSlot^.Writable := (XPLMCanWriteDataRef(Pointer8b2Pointer(pSlot^.DataRef)) <> 0);
if (pSlot^.Writable) then
DebugLog('Variable is writable.')
else
DebugLog('Variable is not writable.');
pSlot^.DataType := XPLMGetDataRefTypes(Pointer8b2Pointer(pSlot^.DataRef));
DebugLog('Data type is ' + IntToStr(Ord(pSlot^.DataType)));
pSlot^.Length := GetArrayLength(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.DataType);
end
else
DebugLog('Ref not found.');
lMakeChecks := True; // we can make check only when all pBuffer items
// were just filled
end
else
lMakeChecks := False;
if pSlot^.DataRef <> 0 then
begin
DebugLog(Format('Using data ref %x.', [pSlot^.DataRef]));
if (pSlot^.HDMcommand = HDMC_SET_VAR) then
begin
String2XplValue(pSlot^.ValueUntyped, @(pSlot^.Value), pSlot^.DataType);
end;
if lMakeChecks and (not pSlot^.Writable) and (
(pSlot^.HDMcommand = HDMC_SET_VAR) or
(pSlot^.HDMcommand = HDMC_TOGGLE_NEXT) or
(pSlot^.HDMcommand = HDMC_TOGGLE_PREVIOUS) or
(pSlot^.HDMcommand = HDMC_SWITCH_NEXT) or
(pSlot^.HDMcommand = HDMC_SWITCH_PREVIOUS)
) then
begin
DebugLog('Can''t set variable which is read only, chenging to get.');
pSlot^.HDMcommand := HDMC_GET_VAR;
end;
if (pSlot^.HDMcommand = HDMC_GET_VAR) or
(pSlot^.HDMcommand = HDMC_SET_VAR) then
SimpleReadWrite(pSlot, lMakeChecks);
if (pSlot^.HDMcommand = HDMC_TOGGLE_NEXT) or
(pSlot^.HDMcommand = HDMC_TOGGLE_PREVIOUS) or
(pSlot^.HDMcommand = HDMC_SWITCH_NEXT) or
(pSlot^.HDMcommand = HDMC_SWITCH_PREVIOUS) then
ToggleVar(pSlot);
end;
end;
if (pSlot^.HDMcommand = HDMC_EXEC_COMMAND) or
(pSlot^.HDMcommand = HDMC_COMMAND_BEGIN) or
(pSlot^.HDMcommand = HDMC_COMMAND_END)
then
begin
// is already registered?
if pSlot^.CommandRef = 0 then
begin
// register first
DebugLog('Finding ref for command ' + pSlot^.ValueName);
pSlot^.CommandRef := Pointer2Pointer8b(XPLMFindCommand(pSlot^.ValueName));
if pSlot^.CommandRef <> 0 then
begin
DebugLog(Format('Got valid pointer %p.', [Pointer8b2Pointer(pSlot^.CommandRef)]));
end;
end;
if pSlot^.CommandRef <> 0 then
begin
DebugLog(Format('Sending command for %p.', [Pointer8b2Pointer(pSlot^.CommandRef)]));
case pSlot^.HDMcommand of
HDMC_EXEC_COMMAND: XPLMCommandOnce(Pointer8b2Pointer(pSlot^.CommandRef));
HDMC_COMMAND_BEGIN: XPLMCommandBegin(Pointer8b2Pointer(pSlot^.CommandRef));
HDMC_COMMAND_END: XPLMCommandEnd(Pointer8b2Pointer(pSlot^.CommandRef));
end;
end;
end;
if (pSlot^.HDMcommand = HDMC_SET_POSINTERVAL) then
fPosCountDown := pBuffer^.PosInterval;
if (pSlot^.HDMcommand = HDMC_SHOW_TEXT) then
begin
fTextFloatPosition := pSlot^.Value.floatData;
fTextToBeDrawn := pSlot^.StringBuffer;
if (pSlot^.Length > 0) then
fTextHideTs := IncSecond(Now(), pSlot^.Length)
else
fTextHideTs := 0;
DebugLog(Format('Received DrawText %s at pos %f.', [fTextToBeDrawn, fTextFloatPosition]));
end;
pSlot^.XplRequestFlag := 0;
end;
end;
procedure TXplEngine.String2XplValue(pIn: String; pOut: PXplValue; pDataType: XPLMDataTypeID);
var
lBuff: PChar;
lMessage: String;
FS: TFormatSettings;
begin
FillChar(FS, SizeOf(FS), 0);
//FS.ThousandSeparator := ',';
FS.DecimalSeparator := '.';
DebugLog(Format('Converting value %s.', [pIn]));
// convert from string to appropriate value
try
case pDataType of
xplmType_Float,
xplmType_FloatArray:
pOut^.floatData := StrToFloat(pIn, FS);
xplmType_Double:
pOut^.doubleData := StrToFloat(pIn, FS);
xplmType_Int,
xplmType_IntArray:
pOut^.intData := StrToint(pIn);
end;
except
on E: EConvertError do
begin
lMessage:=Format('Converting error in value %s. %s', [pIn, e.Message]);
DebugLog(lMessage);
GetMem(lBuff, Length(lMessage) + 1);
try
StrPCopy(lBuff, lMessage);
XPLMDebugString(lBuff);
finally
FreeMem(lBuff);
end;
pOut^.floatData := 0;
pOut^.doubleData := 0;
pOut^.intData := 0;
end;
end;
end;
procedure TXplEngine.SimpleReadWrite(pSlot: PXplComSlot; pMakeChecks: Boolean);
var
lInt: Integer;
lFloat: Single;
lBuff: PChar;
begin
case pSlot^.DataType of
xplmType_Float:
begin
DebugLog('Got/set-ing value ' + FloatToStr(pSlot^.Value.floatData));
case pSlot^.HDMcommand of
HDMC_GET_VAR: pSlot^.Value.floatData := XPLMGetDataf(Pointer8b2Pointer(pSlot^.DataRef));
HDMC_SET_VAR: XPLMSetDataf(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.Value.floatData);
end;
DebugLog('Got/set value ' + FloatToStr(pSlot^.Value.floatData));
end;
xplmType_Double:
begin
case pSlot^.HDMcommand of
HDMC_GET_VAR: pSlot^.Value.doubleData := XPLMGetDatad(Pointer8b2Pointer(pSlot^.DataRef));
HDMC_SET_VAR: XPLMSetDatad(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.Value.doubleData);
end;
DebugLog('Got/set value ' + FloatToStr(pSlot^.Value.doubleData));
end;
xplmType_Int:
begin
case pSlot^.HDMcommand of
HDMC_GET_VAR: pSlot^.Value.intData := XPLMGetDatai(Pointer8b2Pointer(pSlot^.DataRef));
HDMC_SET_VAR: XPLMSetDatai(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.Value.intData);
end;
DebugLog('Got/set value ' + IntToStr(pSlot^.Value.intData));
end;
xplmType_IntArray:
begin
// check range
if pSlot^.Index < 0 then
pSlot^.Value.intData := GetArrayLength(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.DataType)
else if (not pMakeChecks) or (pSlot^.Index < (pSlot^.Length - 1)) then
begin
case pSlot^.HDMcommand of
HDMC_GET_VAR:
begin
XPLMGetDatavi(Pointer8b2Pointer(pSlot^.DataRef), @lInt,
pSlot^.Index, 1);
pSlot^.Value.intData := lInt;
end;
HDMC_SET_VAR:
begin
lInt := pSlot^.Value.intData;
XPLMSetDatavi(Pointer8b2Pointer(pSlot^.DataRef), @lInt, pSlot^.Index, 1);
end;
end;
DebugLog('Got/Set value ' + IntToStr(pSlot^.Value.intData));
end else
DebugLog('Index for int array too high ' + IntToStr(pSlot^.Index));
end;
xplmType_FloatArray:
begin
// check range
if pSlot^.Index < 0 then
pSlot^.Value.intData := GetArrayLength(Pointer8b2Pointer(pSlot^.DataRef), pSlot^.DataType)
else if (not pMakeChecks) or (pSlot^.Index < (pSlot^.Length - 1)) then
begin
case pSlot^.HDMcommand of
HDMC_GET_VAR:
begin
XPLMGetDatavf(Pointer8b2Pointer(pSlot^.DataRef), @lFloat,
pSlot^.Index, 1);
pSlot^.Value.floatData := lFloat;
end;
HDMC_SET_VAR:
begin
lFloat := pSlot^.Value.floatData;
XPLMSetDatavf(Pointer8b2Pointer(pSlot^.DataRef), @lFloat, pSlot^.Index, 1);
end;
end;
DebugLog('Got/Set value ' + FloatToStr(pSlot^.Value.floatData));
end else
DebugLog('Index for array too high ' + IntToStr(pSlot^.Index));
end;
xplmType_Data:
begin
if (pSlot^.Length > XPL_MAX_STRING_SIZE) then
pSlot^.Length := XPL_MAX_STRING_SIZE;
lBuff := pSlot^.StringBuffer;
case pSlot^.HDMcommand of
HDMC_GET_VAR:
begin
XPLMGetDatab(Pointer8b2Pointer(pSlot^.DataRef), lBuff, 0, pSlot^.Length);
end;
HDMC_SET_VAR:
begin
lInt := StrLen(lBuff)+1; // copy also end str char
XPLMSetDatab(Pointer8b2Pointer(pSlot^.DataRef), lBuff, 0, lInt);
end;
end;
DebugLog('Got/Set value ' + lBuff);
end;
end;
end;
procedure TXplEngine.ToggleVar(pSlot: PXplComSlot);
var
lVals: array of TXplValue;
lStrings: TStringList;
i: Integer;
lClosest: TXplValue;
lClosestIndex : Integer;
lCount: Integer;
lSetIndex: Integer;
begin
// step 1 - read current value
case pSlot^.DataType of
xplmType_Float:
pSlot^.Value.floatData := XPLMGetDataf(Pointer8b2Pointer(pSlot^.DataRef));
xplmType_Double:
pSlot^.Value.doubleData := XPLMGetDatad(Pointer8b2Pointer(pSlot^.DataRef));
xplmType_Int:
pSlot^.Value.intData := XPLMGetDatai(Pointer8b2Pointer(pSlot^.DataRef));
else
exit;
end;
// step 2 - split incoming string to array
lStrings:= TStringList.Create;
try
lStrings.Delimiter:=';';
lStrings.DelimitedText:=pSlot^.ValueUntyped;
if lStrings.Count = 0 then
exit;
lCount := lStrings.Count;
SetLength(lVals, lCount);
for i := 0 to lCount - 1 do
String2XplValue(lStrings[i], @(lVals[i]), pSlot^.DataType);
finally
lStrings.Free;
end;
// step 3 - find the closest value
lClosestIndex := 0;
case pSlot^.DataType of
xplmType_Float: lClosest.floatData := Abs(lVals[lClosestIndex].floatData - pSlot^.Value.floatData);
xplmType_Double: lClosest.doubleData := Abs(lVals[lClosestIndex].doubleData - pSlot^.Value.doubleData);
xplmType_Int: lClosest.intData := Abs(lVals[lClosestIndex].intData - pSlot^.Value.intData);
end;
for i := 0 to lCount - 1 do
case pSlot^.DataType of
xplmType_Float:
begin
if Abs(lVals[i].floatData - pSlot^.Value.floatData) < lClosest.floatData then
begin
lClosestIndex:=i;
lClosest.floatData := Abs(lVals[i].floatData - pSlot^.Value.floatData);
end;
if lClosest.floatData = 0 then
break;
end;
xplmType_Double:
begin
if Abs(lVals[i].doubleData - pSlot^.Value.doubleData) < lClosest.doubleData then
begin
lClosestIndex:=i;
lClosest.doubleData := Abs(lVals[i].doubleData - pSlot^.Value.doubleData);
end;
if lClosest.doubleData = 0 then
break;
end;
xplmType_Int:
begin
if Abs(lVals[i].intData - pSlot^.Value.intData) < lClosest.intData then
begin
lClosestIndex:=i;
lClosest.intData := Abs(lVals[i].intData - pSlot^.Value.intData);
end;
if lClosest.intData = 0 then
break;
end;
end;
// step 4 - decide next value index
case pSlot^.HDMcommand of
HDMC_TOGGLE_NEXT:
if (lClosestIndex + 1 = lCount) then
lSetIndex:= 0
else
lSetIndex:= lClosestIndex + 1;
HDMC_SWITCH_NEXT:
if (lClosestIndex + 1 = lCount) then
lSetIndex:= lClosestIndex
else
lSetIndex:= lClosestIndex + 1;
HDMC_TOGGLE_PREVIOUS:
if (lClosestIndex - 1 < 0) then
lSetIndex:= lCount - 1
else
lSetIndex:= lClosestIndex - 1;
HDMC_SWITCH_PREVIOUS:
if (lClosestIndex - 1 < 0) then
lSetIndex:= 0
else
lSetIndex:= lClosestIndex - 1;
end;
DebugLog(Format('Toggle: The closest index is %d, so setting %d in values [%s].', [lClosestIndex, lSetIndex, pSlot^.ValueUntyped]));
// step 5 - set value
case pSlot^.DataType of
xplmType_Float: XPLMSetDataf(Pointer8b2Pointer(pSlot^.DataRef), lVals[lSetIndex].floatData);
xplmType_Double: XPLMSetDatad(Pointer8b2Pointer(pSlot^.DataRef), lVals[lSetIndex].doubleData);
xplmType_Int: XPLMSetDatai(Pointer8b2Pointer(pSlot^.DataRef), lVals[lSetIndex].intData);
end;
end;
procedure TXplEngine.InitGlValues;
begin
XPLMGetScreenSize(@fScreenWidth, @fScreenHeight);
XPLMGetFontDimensions(xplmFont_Basic, @fBasicFontWidth, @fBasicFontHeight, nil);
end;
procedure TXplEngine.DrawText;
var
rgb : array[0..2] of single;
lTextYPos : Integer;
begin
if (fTextToBeDrawn = '') then
exit;
if (fTextHideTs > 0) and (fTextHideTs - Now() < 0) then
begin
fTextToBeDrawn := '';
fTextHideTs := 0;
exit;
end;
rgb[0] := 1;
rgb[1] := 1;
rgb[2] := 1;
//XPLMSetGraphicsState(0, 0, 0, 0, 0, 0, 0); // turn off blending
XPLMGetScreenSize(@fScreenWidth, @fScreenHeight);
lTextYPos := Round(fScreenHeight*(1-fTextFloatPosition))-fBasicFontHeight;
XPLMDrawTranslucentDarkBox(8, lTextYPos + fBasicFontHeight + 3, 12 + fBasicFontWidth * Length(fTextToBeDrawn), lTextYPos - 6);
XPLMDrawString(@rgb, 10, lTextYPos, PAnsiChar(fTextToBeDrawn), nil, xplmFont_Basic);
end;
end.
|
unit u_xpl_filter_message;
{==============================================================================
UnitDesc = xPL Message management object and function
This unit implement strictly conform to specification message
structure
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
0.95 : First Release
1.0 : Now descendant of TxPLHeader
}
{$ifdef fpc}
{$mode objfpc}{$H+}{$M+}
{$endif}
interface
uses classes
, u_xpl_body
, u_xpl_schema
, u_xpl_common
, u_xpl_filter_header
;
type { TxPLCustomMessage =====================================================}
TxPLFilterMessage = class(TxPLFilterHeader, IxPLCommon, IxPLRaw)
private
fBody : TxPLBody;
function Get_RawXPL: string;
procedure Set_RawXPL(const AValue: string);
public
constructor Create(const aOwner : TComponent; const aRawxPL : string = ''); reintroduce;
procedure Assign(aMessage : TPersistent); override;
procedure ResetValues; override;
function IsValid : boolean; override;
published
property Body : TxPLBody read fBody ;
property RawXPL : string read Get_RawXPL write Set_RawXPL stored false;
end;
implementation // =============================================================
Uses SysUtils
, StrUtils
;
// TxPLFilterMessage ==========================================================
constructor TxPLFilterMessage.Create(const aOwner : TComponent; const aRawxPL : string = '');
begin
inherited Create(aOwner);
fBody := TxPLBody.Create(self);
if aRawxPL<>'' then RawXPL := aRawXPL;
end;
procedure TxPLFilterMessage.ResetValues;
begin
inherited;
if Assigned(Body) then Body.ResetValues;
end;
procedure TxPLFilterMessage.Assign(aMessage: TPersistent);
begin
if aMessage is TxPLFilterMessage then begin
fBody.Assign(TxPLFilterMessage(aMessage).Body); // Let me do specific part
inherited Assign(aMessage);
end else inherited;
end;
function TxPLFilterMessage.Get_RawXPL: string;
begin
result := inherited RawxPL + Body.RawxPL;
end;
function TxPLFilterMessage.IsValid: boolean;
begin
result := (inherited IsValid) and (Body.IsValid);
end;
procedure TxPLFilterMessage.Set_RawXPL(const AValue: string);
var LeMessage : string;
HeadEnd, BodyStart, BodyEnd : integer;
begin
LeMessage := AnsiReplaceText(aValue,#13,''); // Delete all CR
HeadEnd := AnsiPos('}',LeMessage);
BodyStart := Succ(PosEx('{',LeMessage,HeadEnd));
BodyEnd := LastDelimiter('}',LeMessage);
inherited RawxPL := AnsiLeftStr(LeMessage,BodyStart-2);
Body.RawxPL := Copy(LeMessage,BodyStart,BodyEnd-BodyStart);
end;
initialization // =============================================================
Classes.RegisterClass(TxPLFilterMessage);
end.
|
unit ufEstabMenu;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.Objects, FMX.Layouts, FMX.Controls.Presentation, FMX.ListBox, uBusiObj,
FMX.TabControl;
const
cTabName = 'TabEstabMenu';
cHeaderTitle = 'Member Businesses';
cTag = uBusiObj.tnEstabMenu;
type
TfraEstabMenu = class(TFrame)
ToolBar1: TToolBar;
btnCancel: TSpeedButton;
shpCarPic: TCircle;
lblName: TLabel;
ListBox1: TListBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
Layout1: TLayout;
Button1: TButton;
Button2: TButton;
Button3: TButton;
lblAddress: TLabel;
Label1: TLabel;
lblHeaderTItle: TLabel;
Rectangle1: TRectangle;
Rectangle2: TRectangle;
procedure btnCancelClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
FOnNextBtnClick: ^TProc; //<TObject>; -in the future, this should contain the ID of the next question.
FOnCloseTab: ^TProc;
FOnMapBtnClick: ^TProc;
FOnComplBtnClick: ^TProc;
FOnTakeSurvBtnClick: ^TProc;
FTID: integer;
procedure AnimateTrans(AAnimateRule: TAnimateRule);
public
{ Public declarations }
FLat, FLon: double;
procedure PopuUI;
end;
TTabOfFrame = class(TTabItem)
strict private
FOnNextBtnClick: TProc; //<TObject>;
FOnCloseTab: TProc; //<TObject>;
FOnMapBtnClick: TProc;
FOnComplBtnClick: TProc;
FOnTakeSurvBtnClick: TProc;
{
FTabItemState: TTabItemState;
//FOnBackBtnClick: TProc<TObject>;
//FOnDoneBtnClick: TProc<TObject>; // TProc<TObject, TUpdateMade, integer>;
FOnAfterSave: TProc<TUpdateMade, integer>;
FOnAfterDeleted: TProc<TUpdateMade, integer>;
FCarID: integer;
FOnUOMPickList: TProc<TEdit>;
FOnATPickList: TProc<TEdit>;
}
private
// FRecID: integer;
public
FCallerTab: TTabItem;
FFrameMain: TfraEstabMenu;
property OnNextBtnClick: TProc read FOnNextBtnClick write FOnNextBtnClick;
property OnCloseTab: TProc read FOnCloseTab write FOnCloseTab;
property OnMapBtnClick: TProc read FOnMapBtnClick write FOnMapBtnClick;
property OnComplBtnClick: TProc read FOnComplBtnClick write FOnComplBtnClick;
property OnTakeSurvBtnClick: TProc read FOnTakeSurvBtnClick write FOnTakeSurvBtnClick;
procedure CloseTab(AIsRelease: Boolean);
constructor Create(AOwner: TComponent); // supply various params here. AReccordID: integer); // ; AUserRequest: TUserRequest
destructor Destroy; override;
procedure ShowTab(ACallerTab: TTabItem; ATID: integer; ATitle,
AAddress: string; ALat, ALon: double); //; AUserRequest: TUserIntentInit; ATID, ACarID: integer);
end;
implementation
{$R *.fmx}
{ TfraEstabMenu }
procedure TfraEstabMenu.AnimateTrans(AAnimateRule: TAnimateRule);
begin
try
if AAnimateRule = uBusiObj.TAnimateRule.arInit then
begin
Layout1.Align := TAlignLayout.None;
Layout1.Position.X := Layout1.Width;
end
else if AAnimateRule = uBusiObj.TAnimateRule.arIn then
begin
//Layout1.Position.X := Layout1.Width;
Layout1.AnimateFloat('Position.X', 0, 0.3, TAnimationType.InOut, TInterpolationType.Linear);
end
else if AAnimateRule = uBusiObj.TAnimateRule.arOut then
begin
// Layout1.Position.X := Layout1.Width;
Layout1.Align := TAlignLayout.None;
Layout1.AnimateFloat('Position.X', Layout1.Width, 0.2, TAnimationType.Out, TInterpolationType.Linear);
end;
finally
if AAnimateRule = uBusiObj.TAnimateRule.arIn then
Layout1.Align := TAlignLayout.Client;
end;
end;
{ TTabOfFrame }
procedure TTabOfFrame.CloseTab(AIsRelease: Boolean);
begin
// FFrameMain.AnimateTrans(TAnimateRule.arOut); // animate the main tab
TTabControl(Self.Owner).ActiveTab := FCallerTab;
if Assigned(FOnCloseTab) then
FOnCloseTab();
end;
procedure TfraEstabMenu.btnCancelClick(Sender: TObject);
begin
AnimateTrans(TAnimateRule.arOut); // animate the main tab
TTabOfFrame(Owner).CloseTab(false);
end;
procedure TfraEstabMenu.Button1Click(Sender: TObject);
begin
if Assigned(FOnComplBtnClick^) then
FOnComplBtnClick^();
end;
procedure TfraEstabMenu.Button2Click(Sender: TObject);
begin
if Assigned(FOnMapBtnClick^) then
FOnMapBtnClick^();
end;
procedure TfraEstabMenu.Button3Click(Sender: TObject);
begin
if Assigned(FOnTakeSurvBtnClick^) then
FOnTakeSurvBtnClick^();
end;
procedure TfraEstabMenu.PopuUI;
begin
// update photo here.
end;
constructor TTabOfFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Name := cTabName;
Tag := Integer(cTag);
// create main frame
FFrameMain := TfraEstabMenu.Create(Self);
FFrameMain.Parent := Self;
// FFrameMain.Layout1.Align := TAlignLayout.None;
FFrameMain.Tag := Integer(cTag); //uBusiObj.tnUOMUpd);
// define events
FFrameMain.FOnNextBtnClick := @OnNextBtnClick;
FFrameMain.FOnCloseTab := @OnCloseTab;
FFrameMain.FOnMapBtnClick := @OnMapBtnClick;
FFrameMain.FOnComplBtnClick := @OnComplBtnClick;
FFrameMain.FOnTakeSurvBtnClick := @OnTakeSurvBtnClick;
end;
destructor TTabOfFrame.Destroy;
begin
FFrameMain.Free;
inherited;
end;
procedure TTabOfFrame.ShowTab(ACallerTab: TTabItem; ATID: integer; ATitle,
AAddress: string; ALat, ALon: double);
begin
FCallerTab := ACallerTab;
FFrameMain.FTID := ATID;
FFrameMain.FLat := ALat;
FFrameMain.FLon := ALon;
FFrameMain.AnimateTrans(TAnimateRule.arInit);
TTabControl(Self.Owner).ActiveTab := Self;
// if FTabItemState.UserIntentCurr = uicAdding then
// FFrameMain.edtDescript.SetFocus;
FFrameMain.AnimateTrans(TAnimateRule.arIn);
// update fields
FFrameMain.lblName.Text := ATitle;
FFrameMain.lblAddress.Text := AAddress;
end;
end.
|
unit Uterror;
interface
uses
vcl.dialogs;
type
Terror = class
private
Fcodierror: integer;
procedure Setcodierror(const Value: integer);
public
property codierror:integer read Fcodierror write Setcodierror;
function quinerror:string;
procedure mostrarerror;
end;
implementation
{ Terror }
procedure Terror.mostrarerror;
begin
messagedlg (quinerror,mterror,[mbok],1);
end;
function Terror.quinerror: string;
var
res : string;
begin
case self.codierror of
//errors interfície (-1-100)
-1: res := 'Dades de creació incomplertes';
-2: res := 'La quantitat ha de ser superior o igual a 0';
-3: res := 'Cap vaixell seleccionat';
-4: res := 'Soc el puto amo';
//errors nau (-101-200)
-101: res := 'No es poden crear més vaixells';
-102: res := 'El vaixell que es vol crear ja existeix';
-103: res := 'El vaixell escollit es incorrecte o no existeix';
-104: res := 'Per eliminar un vaixell ha d''estar En manteniment';
-105: res := 'per a carregar un vaixell aquest ha d''estar a port i no pot estar en manteniment';
-106: res := 'El vaixell no es troba a port o ja està en manteniment';
-107: res := 'El vaixell no es troba actualment en manteniment';
-108: res := 'Per a descarregar un vaixell ha d''estar a port i no pot estar en manteniment';
-109: res := 'Un vaixell momés es considera carragat quan porta un 90% o més de la seva capacitat';
-110: res := 'Per a poder posar en manteniment aquest no pot estar carregat';
-111: res := 'El vaixell no es troba a port o està averiat';
//errors vaixell (-201-300)
-201: res := 'Un vaixell en reparació no pot navegar';
-202: res := 'El port destí ha de ser diferent al actual';
-203: res := 'Per a poder navegar, el vaixell ha destar actualment a port';
-204: res := 'No es pot introduir aquesta càrrega degut a que sobrepasa a la capacitat màxima';
end;
result := res;
end;
procedure Terror.Setcodierror(const Value: integer);
begin
Fcodierror := Value;
end;
end.
|
unit uFaceView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ImgList, ComCtrls, StdCtrls, pngimage, ExtCtrls, FaceUnit;
type
TForm4 = class(TForm)
Panel3: TPanel;
Bevel2: TBevel;
Label1: TLabel;
Label2: TLabel;
Panel1: TPanel;
Bevel1: TBevel;
Button2: TButton;
Button3: TButton;
Button1: TButton;
Button4: TButton;
Panel2: TPanel;
Image1: TImage;
ListView1: TListView;
Edit2: TEdit;
Button5: TButton;
ImageList1: TImageList;
Image2: TImage;
Function ScanDir(Dir:String) : Boolean;
procedure FormShow(Sender: TObject);
procedure ListView1SelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure Button4Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
private
{ Private declarations }
public
FaceName : String;
{ Public declarations }
end;
var
Form4: TForm4;
MyFace : TFaceStatus;
implementation
uses uCreateFace;
Function TForm4.ScanDir(Dir:String) : Boolean;
Var
SR : TSearchRec;
FindRes,i : Integer;
begin
Result := false;
FindRes:=FindFirst(Dir+'*.*',faAnyFile,SR);
While FindRes=0 do
begin
if ((SR.Attr and faDirectory)=faDirectory) and
((SR.Name='.')or(SR.Name='..')) then
begin
FindRes:=FindNext(SR);
Continue;
end;
if ((SR.Attr and faDirectory)=faDirectory) then
begin
ScanDir(Dir+SR.Name+'\');
FindRes:=FindNext(SR);
Continue;
end;
if FileExists(Dir+SR.Name) then
if LowerCase(ExtractFileExt(Dir+SR.Name)) = '.fc' then
begin
with ListView1.Items.Add do begin
Caption := ExtractFileName(SR.Name);
if LoadFace(MyFace,SR.Name) then
if ExistFaceRes(MyFace) then
ImageIndex := 0 else ImageIndex := 1;
end;
end;
FindRes:=FindNext(SR);
end;
SysUtils.FindClose(SR);
Result := true;
end;
{$R *.dfm}
procedure TForm4.FormShow(Sender: TObject);
begin
ModalResult := mrNone;
ListView1.Clear;
ScanDir(facepath);
end;
procedure TForm4.ListView1SelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
begin
if item.ImageIndex = 0 then begin
FaceName := Item.Caption;
LoadFace(MyFace,Item.Caption);
DrawFace(Image1.Canvas,MyFace);
Button3.Enabled := true;
Edit2.Text := FaceName;
end else Button3.Enabled := false;
end;
procedure TForm4.Button4Click(Sender: TObject);
begin
Form2.EditFace := false;
Form2.NewFace := true;
Form2.ShowModal;
ListView1.Clear;
ScanDir(facepath);
end;
procedure TForm4.Button1Click(Sender: TObject);
begin
if ListView1.Selected = nil then exit;
Form2.EditFace := true;
Form2.FaceName := ListView1.Selected.Caption;
Form2.NewFace := true;
Form2.MyFace := MyFace;
Form2.ShowModal;
ListView1.Clear;
ScanDir(facepath);
end;
procedure TForm4.Button2Click(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TForm4.Button3Click(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TForm4.Button5Click(Sender: TObject);
begin
if ListView1.Selected = nil then exit;
if FileExists(facepath+ListView1.Selected.Caption) then
begin
DeleteFile(facepath+ListView1.Selected.Caption);
ListView1.Clear;
ScanDir(facepath);
end;
end;
end.
|
unit NTLib;
interface
//function MessageBox(HWnd: Integer; Text, Caption: PChar; Flags: Integer): Integer; stdcall; external 'user32.dll' name 'MessageBoxA';
type
NTSTATUS =LongInt;
var
MsgBin:PByte;
MsgLen:PCardinal;
function ConnectToServer(const ServerName:WideString):NTSTATUS;
function ReceiveMsgFromServer:NTSTATUS;
function ClientDisconnect(Flag:Cardinal = 0):NTSTATUS;
function ServerCreatePort(const ServerName:WideString):NTSTATUS;
function ServerListenAndPeekMessage:NTSTATUS;
function SendMsgToServer:NTSTATUS;
procedure test();
implementation
uses
Windows,Logger,SysUtils,Generics.Collections;
{$REGION 'Type'}
type
ULONG = DWORD;
SIZE_T = Cardinal;
PSIZE_T =^SIZE_T;
PULONG =^ULONG;
HANDLE = THandle;
PHANDLE =^HANDLE;
PVOID = Pointer;
PUNICODE_STRING = ^UNICODE_STRING;
UNICODE_STRING = record
Length:Word;
MaximumLength:Word;
Buffer:PWideChar;
end;
_OBJECT_ATTRIBUTES = record
Length:ULONG;
RootDirectory:THandle;
ObjectName:PUNICODE_STRING;
Attributes:ULONG;
SecurityDescriptor:PSecurityDescriptor;
SecurityQualityOfService:PSecurityQualityOfService;
end;
OBJECT_ATTRIBUTES = _OBJECT_ATTRIBUTES;
POBJECT_ATTRIBUTES = ^OBJECT_ATTRIBUTES;
_ALPC_PORT_ATTRIBUTES = record
Flags:ULONG;
SecurityQos:SECURITY_QUALITY_OF_SERVICE;
MaxMessageLength:SIZE_T;
MemoryBandwidth:SIZE_T;
MaxPoolUsage:SIZE_T;
MaxSectionSize:SIZE_T;
MaxViewSize:SIZE_T;
MaxTotalSectionSize:SIZE_T;
DupObjectTypes:ULONG
end;
ALPC_PORT_ATTRIBUTES = _ALPC_PORT_ATTRIBUTES;
PALPC_PORT_ATTRIBUTES = ^ALPC_PORT_ATTRIBUTES;
_CLIENT_ID = record
UniqueProcess:THandle;
UniqueThread:THandle;
end;
CLIENT_ID = _CLIENT_ID;
PCLIENT_ID = ^CLIENT_ID;
Ts1 = record
DataLength:Word;
TotalLength:Word
end;
Ts2 = record
_Type:Word;
DataInfoOffset:Word
end;
Tu1 = record
case Integer of
0:(s1:Ts1);
1:(Length:ULONG);
end;
Tu2 = record
case Integer of
0:(s2:Ts2);
1:(ZeroInit:ULONG);
end;
Tu3 = record
case Integer of
0:(ClientId:CLIENT_ID);
1:(DoNotUseThisField:Double);
end;
Tu4 = record
case Integer of
0:(ClientViewSize:SIZE_T);
1:(CallbackId:ULONG);
end;
_PORT_MESSAGE = record
u1:Tu1;
u2:Tu2;
u3:Tu3;
MessageId:ULONG;
u4:Tu4
end;
PORT_MESSAGE = _PORT_MESSAGE;
PPORT_MESSAGE =^PORT_MESSAGE;
_ALPC_MESSAGE_ATTRIBUTES = record
AllocatedAttributes:ULONG;
ValidAttributes:ULONG
end;
ALPC_MESSAGE_ATTRIBUTES = _ALPC_MESSAGE_ATTRIBUTES;
PALPC_MESSAGE_ATTRIBUTES = ^ALPC_MESSAGE_ATTRIBUTES;
TDUMMYSTRUCTNAME =record
LowPart:DWORD;
HighPart:Integer;
end;
Tu = TDUMMYSTRUCTNAME;
_LARGE_INTEGER =record
case Integer of
0:(DUMMYSTRUCTNAME:TDUMMYSTRUCTNAME);
1:(u:Tu);
2:(QuadPart:Int64)
end;
LARGE_INTEGER = _LARGE_INTEGER;
PLARGE_INTEGER =^LARGE_INTEGER;
_argument = record
funcid:Cardinal;
do_return:BOOL
end;
_result = record
error:BOOL
end;
_info = record
case Integer of
0:(argumen:_argument);
1:(result:_result);
end;
_DataHeader = record
totalsize:Cardinal;
info:_info;
end;
PDataHeader = ^DataHeader;
DataHeader = _DataHeader;
_DataCache =record
header:DataHeader;
buff:array [0..0] of Byte;
end;
PDataCache = ^DataCache;
DataCache = _DataCache;
TALPC_PORT_ATTRIBUTES_VALUES = record
kAlpcPortAttributesNone:ULONG;
kAlpcPortAttributesLpcPort :ULONG;
kAlpcPortAttributesAllowImpersonation :ULONG;
kAlpcPortAttributesAllowLpcRequests :ULONG;
kAlpcPortAttributesWaitablePort :ULONG;
kAlpcPortAttributesAllowDupObject :ULONG;
kAlpcPortAttributesSystemProcess :ULONG;// Not accessible outside the kernel.
kAlpcPortAttributesLrpcWakePolicy1 :ULONG;
kAlpcPortAttributesLrpcWakePolicy2 :ULONG;
kAlpcPortAttributesLrpcWakePolicy3 :ULONG;
kAlpcPortAttributesDirectMessage :ULONG;
kAlpcPortAttributesAllowMultiHandleAttribute :ULONG
end;
_ALPC_CUSTOM_MESSAGE = packed record
Header:PORT_MESSAGE;
Buffer:array[0..0] of Byte
end;
ALPC_CUSTOM_MESSAGE = _ALPC_CUSTOM_MESSAGE;
PALPC_CUSTOM_MESSAGE = ^ALPC_CUSTOM_MESSAGE;
TBinCache = array[0..MAXWORD -1] of Byte;
TALPC_MESSAGE_FLAGS = record
kAlpcMessageFlagNone:ULONG;
kAlpcMessageFlagReplyMessage:ULONG;
kAlpcMessageFlagLpcMode:ULONG;
kAlpcMessageFlagReleaseMessage:ULONG;
kAlpcMessageFlagSyncRequest:ULONG;
kAlpcMessageFlagTrackPortReferences:ULONG;
kAlpcMessageFlagWaitUserMode:ULONG;
kAlpcMessageFlagWaitAlertable:ULONG;
kAlpcMessageFlagWaitChargePolicy:ULONG;
kAlpcMessageFlagUnknown1000000:ULONG;
kAlpcMessageFlagWow64Call:ULONG
end;
TALPC_MESSAGE_ATTRIBUTES_VALUES = record
kAlpcMessageAttributesNone:ULONG;
kAlpcMessageAttributesWorkOnBehalfOf:ULONG;
kAlpcMessageAttributesDirect:ULONG;
kAlpcMessageAttributesToken:ULONG;
kAlpcMessageAttributesHandle:ULONG;
kAlpcMessageAttributesContext:ULONG;
kAlpcMessageAttributesView:ULONG;
kAlpcMessageAttributesSecurity:ULONG
end;
{$IFDEF DynLib}
TCreatePort =function(
PortHandle:PHANDLE;
PortName:PUNICODE_STRING;
ObjectAttributes:POBJECT_ATTRIBUTES;
PortAttributes:PALPC_PORT_ATTRIBUTES;
Flags:ULONG;
RequiredServerSid:PSID;
ConnectionMessage:PPORT_MESSAGE;
BufferLength:PULONG;
OutMessageAttributes:PALPC_MESSAGE_ATTRIBUTES;
InMessageAttributes:PALPC_MESSAGE_ATTRIBUTES;
Timeout:PLARGE_INTEGER
):NTSTATUS;
TDoPeekMessage =function(
PortHandle:HANDLE;
Flags:ULONG;
SendMessage:PPORT_MESSAGE;
SendMessageAttributes:PALPC_MESSAGE_ATTRIBUTES;
ReceiveMessage:PPORT_MESSAGE;
BufferLength:PSIZE_T;
ReceiveMessageAttributes:PALPC_MESSAGE_ATTRIBUTES;
Timeout:PLARGE_INTEGER
):NTSTATUS;
TAlpcInitializeMessageAttribute =function(
AttributeFlags:ULONG;
var Buffer:ALPC_MESSAGE_ATTRIBUTES;
BufferSize:ULONG;
var RequiredBufferSize:ULONG
):NTSTATUS;
TCreateServer =function(
PortHandle:PHANDLE;
ObjectAttributes:POBJECT_ATTRIBUTES;
PortAttributes:PALPC_PORT_ATTRIBUTES
):NTSTATUS;
TAcceptClients =function(
PortHandle:PHANDLE;
ConnectionPortHandle:HANDLE;
Flags:ULONG;
ObjectAttributes:POBJECT_ATTRIBUTES;
PortAttributes:PALPC_PORT_ATTRIBUTES;
PortContext:PVOID;
ConnectionRequest:PPORT_MESSAGE;
ConnectionMessageAttributes:PALPC_MESSAGE_ATTRIBUTES;
AcceptConnection:Boolean
):NTSTATUS;
TDisconnectFromServer =function(
PortHandle:HANDLE;
Flags:ULONG
):NTSTATUS;
{$ENDIF}
{$ENDREGION}
{$REGION 'Const'}
const
ALPC_PORT_ATTRIBUTES_VALUES:TALPC_PORT_ATTRIBUTES_VALUES =
(
kAlpcPortAttributesNone:$0;
kAlpcPortAttributesLpcPort:$1000;
kAlpcPortAttributesAllowImpersonation:$10000;
kAlpcPortAttributesAllowLpcRequests:$20000;
kAlpcPortAttributesWaitablePort:$40000;
kAlpcPortAttributesAllowDupObject:$80000;
kAlpcPortAttributesSystemProcess:$100000;
kAlpcPortAttributesLrpcWakePolicy1:$200000;
kAlpcPortAttributesLrpcWakePolicy2:$400000;
kAlpcPortAttributesLrpcWakePolicy3:$800000;
kAlpcPortAttributesDirectMessage:$1000000;
kAlpcPortAttributesAllowMultiHandleAttribute:$2000000
);
m_MaxMessageLength =Word($1000);
m_MemoryBandwith:SIZE_T = $1000;
m_MaxPoolUsage:SIZE_T = $1000;
m_MaxSectionSize:SIZE_T = $1000;
m_MaxViewSize:SIZE_T = $1000;
m_MaxTotalSectionSize:SIZE_T = $1000;
m_DupObjectTypes:ULONG = $0;
STATUS_INSUFFICIENT_RESOURCES = $C000009A;
STATUS_SUCCESS = ULONG($0);
STATUS_INFO_LENGTH_MISMATCH = ULONG($C0000004);
ALPC_MESSAGE_FLAGS :TALPC_MESSAGE_FLAGS =
(
kAlpcMessageFlagNone:ULONG($0);
kAlpcMessageFlagReplyMessage:$1;
kAlpcMessageFlagLpcMode:$2;
kAlpcMessageFlagReleaseMessage:$10000;
kAlpcMessageFlagSyncRequest:$20000;
kAlpcMessageFlagTrackPortReferences:$40000;
kAlpcMessageFlagWaitUserMode:$100000;
kAlpcMessageFlagWaitAlertable:$200000;
kAlpcMessageFlagWaitChargePolicy:$400000;
kAlpcMessageFlagUnknown1000000:$1000000;
kAlpcMessageFlagWow64Call:$40000000
);
ALPC_MESSAGE_ATTRIBUTES_VALUES:TALPC_MESSAGE_ATTRIBUTES_VALUES =
(
kAlpcMessageAttributesNone:ULONG($0);
kAlpcMessageAttributesWorkOnBehalfOf:$2000000;
kAlpcMessageAttributesDirect:$4000000;
kAlpcMessageAttributesToken:$8000000;
kAlpcMessageAttributesHandle:$10000000;
kAlpcMessageAttributesContext:$20000000;
kAlpcMessageAttributesView:$40000000;
kAlpcMessageAttributesSecurity:$80000000
);
LPC_REQUEST = ULONG(1);
LPC_REPLY = ULONG(2);
LPC_DATAGRAM = ULONG(3);
LPC_LOST_REPLY = ULONG(4);
LPC_PORT_CLOSED = ULONG(5);
LPC_CLIENT_DIED = ULONG(6);
LPC_EXCEPTION = ULONG(7);
LPC_DEBUG_EVENT = ULONG(8);
LPC_ERROR_EVENT = ULONG(90) ;
LPC_CONNECTION_REQUEST =(10);
LPC_KERNELMODE_MESSAGE =Word($8000);
LPC_NO_IMPERSONATE = Word($4000);
{$ENDREGION}
{$REGION 'Var'}
var
BinCache,MsgCache:TBinCache;
m_AlpcClientPortHandle:HANDLE;
m_AlpcServerPortHandle:HANDLE;
m_ClientList:TDictionary<ULONG,HANDLE>;
{$ENDREGION}
{$REGION 'DllCall'}
function CreatePort(
PortHandle:PHANDLE;
PortName:PUNICODE_STRING;
ObjectAttributes:POBJECT_ATTRIBUTES;
PortAttributes:PALPC_PORT_ATTRIBUTES;
Flags:ULONG;
RequiredServerSid:PSID;
ConnectionMessage:PPORT_MESSAGE;
BufferLength:PULONG;
OutMessageAttributes:PALPC_MESSAGE_ATTRIBUTES;
InMessageAttributes:PALPC_MESSAGE_ATTRIBUTES;
Timeout:PLARGE_INTEGER
):NTSTATUS;stdcall;external 'ntdll.dll' name 'NtAlpcConnectPort';
function DoPeekMessage(
PortHandle:HANDLE;
Flags:ULONG;
SendMessage:PPORT_MESSAGE;
SendMessageAttributes:PALPC_MESSAGE_ATTRIBUTES;
ReceiveMessage:PPORT_MESSAGE;
BufferLength:PSIZE_T;
ReceiveMessageAttributes:PALPC_MESSAGE_ATTRIBUTES;
Timeout:PLARGE_INTEGER
):NTSTATUS;stdcall;external 'ntdll.dll' name 'NtAlpcSendWaitReceivePort';
function AlpcInitializeMessageAttribute
(
AttributeFlags:ULONG;
var Buffer:ALPC_MESSAGE_ATTRIBUTES;
BufferSize:ULONG;
var RequiredBufferSize:ULONG
):NTSTATUS;stdcall;external 'ntdll.dll' name 'AlpcInitializeMessageAttribute';
function CreateServer(
PortHandle:PHANDLE;
ObjectAttributes:POBJECT_ATTRIBUTES;
PortAttributes:PALPC_PORT_ATTRIBUTES
):NTSTATUS;stdcall;external 'ntdll.dll' name 'NtAlpcCreatePort';
function AcceptClients(
PortHandle:PHANDLE;
ConnectionPortHandle:HANDLE;
Flags:ULONG;
ObjectAttributes:POBJECT_ATTRIBUTES;
PortAttributes:PALPC_PORT_ATTRIBUTES;
PortContext:PVOID;
ConnectionRequest:PPORT_MESSAGE;
ConnectionMessageAttributes:PALPC_MESSAGE_ATTRIBUTES;
AcceptConnection:Boolean
):NTSTATUS;stdcall;external 'ntdll.dll' name 'NtAlpcAcceptConnectPort';
function DisconnectFromServer(
PortHandle:HANDLE;
Flags:ULONG
):NTSTATUS;stdcall;external 'ntdll.dll' name 'NtAlpcDisconnectPort';
{$ENDREGION}
{$REGION 'Functions'}
procedure RTL_CONSTANT_STRING(const ServerName:WideString;var PortName:UNICODE_STRING);
begin
PortName.Length:= Length(ServerName) * SizeOf(ServerName[1]);
PortName.MaximumLength:= (Length(ServerName) + 1)*SizeOf(ServerName[1]);
PortName.Buffer:= Addr(ServerName[1]);
end;
procedure test();
begin
MessageBox(0,PWideChar(IntToStr(SizeOf(PORT_MESSAGE))),PWideChar('size'),0);
end;
procedure InitializeAlpcPortAttributes(var AlpcPortAttributes:ALPC_PORT_ATTRIBUTES);
begin
FillChar(AlpcPortAttributes,SizeOf(ALPC_PORT_ATTRIBUTES),#0);
AlpcPortAttributes.Flags := ALPC_PORT_ATTRIBUTES_VALUES.kAlpcPortAttributesAllowImpersonation;
AlpcPortAttributes.MaxMessageLength := m_MaxMessageLength;
AlpcPortAttributes.MemoryBandwidth := m_MemoryBandwith;
AlpcPortAttributes.MaxMessageLength := m_MaxPoolUsage;
AlpcPortAttributes.MaxSectionSize := m_MaxSectionSize;
AlpcPortAttributes.MaxViewSize := m_MaxViewSize;
AlpcPortAttributes.DupObjectTypes := m_DupObjectTypes;
AlpcPortAttributes.SecurityQos.Length := sizeof(AlpcPortAttributes.SecurityQos);
AlpcPortAttributes.SecurityQos.ImpersonationLevel := SecurityImpersonation;
AlpcPortAttributes.SecurityQos.ContextTrackingMode := SECURITY_DYNAMIC_TRACKING;
AlpcPortAttributes.SecurityQos.EffectiveOnly := FALSE;
end;
function AlpcMessageInitialize(Buffer:PByte;BufferSize:Word;var AlpcMessage:TBinCache):NTSTATUS;
var
totalSize:Word;
begin
Result:=STATUS_SUCCESS;
totalSize:=BufferSize+sizeof(PORT_MESSAGE);
if totalSize < SizeOf(PORT_MESSAGE) then Exit(STATUS_INTEGER_OVERFLOW);
if totalSize > SizeOf(TBinCache) then Exit(STATUS_INSUFFICIENT_RESOURCES);
FillChar(AlpcMessage,totalSize,#0);
PALPC_CUSTOM_MESSAGE(Addr(AlpcMessage)).Header.u1.s1.TotalLength := totalSize;
if Buffer <> nil then
begin
//Move(Buffer^,PALPC_CUSTOM_MESSAGE(Addr(AlpcMessage)).Buffer,BufferSize);
MoveMemory(Addr(PALPC_CUSTOM_MESSAGE(Addr(AlpcMessage)).Buffer[0]),Buffer,BufferSize);
PALPC_CUSTOM_MESSAGE(Addr(AlpcMessage)).Header.u1.s1.DataLength := BufferSize;
end;
end;
function AlpcMessageAttributesInitialize(
MessageAttributesFlags:ULONG;
var AlpcMessageAttrib:ALPC_MESSAGE_ATTRIBUTES //fixed size, no need cache
):NTSTATUS;inline;
var
requiredSize:ULONG;
Ret:NTSTATUS;
begin
Ret:=AlpcInitializeMessageAttribute(
MessageAttributesFlags,
AlpcMessageAttrib,
0,
requiredSize
); //Calc the require size for the flag
if requiredSize = 0 then
begin
if Ret = 0 then Exit(STATUS_INFO_LENGTH_MISMATCH)
else
Exit(Ret);
end;
FillChar(AlpcMessageAttrib,SizeOf(ALPC_MESSAGE_ATTRIBUTES),#0); //zero Msgattribcache
Ret:=AlpcInitializeMessageAttribute(
MessageAttributesFlags,
AlpcMessageAttrib,
requiredSize,
requiredSize
); //Store attrib to MsgAttribache
Result:=Ret;
end;
function InitializeMessageAndAttributes(
MessageAttributesFlags:ULONG;
Buffer:PByte;
BufferSize:Word;
var AlpcMessage:TBinCache; //BinCache
var AlpcMessageAttributes:ALPC_MESSAGE_ATTRIBUTES
):NTSTATUS;
begin
if BufferSize > MAXWORD then Exit(STATUS_INSUFFICIENT_RESOURCES);
Result:=AlpcMessageInitialize(Buffer,BufferSize,AlpcMessage);//Move Buffer to MsgContextCache
if Result <> 0 then Exit;
Result := AlpcMessageAttributesInitialize(
MessageAttributesFlags,
AlpcMessageAttributes
); //Move Attrib to
end;
function ConnectToServer(const ServerName:WideString):NTSTATUS;
const
timeout:LARGE_INTEGER =(QuadPart:0);
var
connectMessage:PALPC_CUSTOM_MESSAGE;
connectMessageLength:ULONG;
alpcPortAttributes:ALPC_PORT_ATTRIBUTES;
PortName:UNICODE_STRING;
begin
InitializeAlpcPortAttributes(alpcPortAttributes);
AlpcMessageInitialize(
nil,
0,
BinCache
);
connectMessage:=Addr(BinCache);
connectMessageLength := connectMessage.Header.u1.s1.TotalLength;
RTL_CONSTANT_STRING(ServerName,PortName);
m_AlpcClientPortHandle:=0;
Result:= CreatePort(
Addr(m_AlpcClientPortHandle),
Addr(PortName),
nil,
Addr(alpcPortAttributes),
ALPC_MESSAGE_FLAGS.kAlpcMessageFlagSyncRequest,
nil,
Addr(connectMessage.Header),
Addr(connectMessageLength),
nil,
nil,
nil
);
end;
function SendMsg(
AlpcPortHandle:HANDLE;
MsgID:ULONG = 0;
Flag:ULONG = 0
):NTSTATUS;
var
MsgAttrib:ALPC_MESSAGE_ATTRIBUTES;
begin
Result := InitializeMessageAndAttributes(
ALPC_MESSAGE_ATTRIBUTES_VALUES.kAlpcMessageAttributesNone,
MsgBin, //In,The Msg should be sended
MsgLen^, //In,The Msg Length
BinCache, //Out the MsgContextcache
MsgAttrib //Out the MsgAttribCache
);
if Result = 0 then
begin
PALPC_CUSTOM_MESSAGE(Addr(BinCache[0])).Header.MessageId:=MsgID;
Result:=DoPeekMessage(
AlpcPortHandle,
Flag,
Addr(PALPC_CUSTOM_MESSAGE(Addr(BinCache[0])).Header),
Addr(MsgAttrib),
nil,
nil,
nil,
nil
);
end;
end;
function SendMsgToServer:NTSTATUS;
begin
Result:=SendMsg(m_AlpcClientPortHandle);
end;
function ClientDisconnect(Flag:Cardinal = 0):NTSTATUS;
begin
Result:=DisconnectFromServer(m_AlpcClientPortHandle,Flag);
end;
function SendMsgToClient(ClientMsgID:ULONG):NTSTATUS;
begin
Result:=SendMsg(m_AlpcServerPortHandle,ClientMsgID,ALPC_MESSAGE_FLAGS.kAlpcMessageFlagReplyMessage);
end;
function ReceiveMsg(AlpcPortHandle:HANDLE):NTSTATUS;
var
MsgAttrib:ALPC_MESSAGE_ATTRIBUTES;
MsgSize:SIZE_T;
begin
Result:=InitializeMessageAndAttributes(
ALPC_MESSAGE_ATTRIBUTES_VALUES.kAlpcMessageAttributesNone,
nil,
m_MaxMessageLength,
MsgCache,
MsgAttrib
);
MsgSize:=PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Header.u1.s1.TotalLength;
if Result = 0 then
begin
Result:= DoPeekMessage(
AlpcPortHandle,//PortHandle:HANDLE
ALPC_MESSAGE_FLAGS.kAlpcMessageFlagNone,//Flags:ULONG
nil, //SendMessage:PPORT_MESSAGE
nil,//SendMessageAttributes:PALPC_MESSAGE_ATTRIBUTES
Addr(PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Header), //ReceiveMessage:PPORT_MESSAGE
@MsgSize,
Addr(MsgAttrib), //ReceiveMessageAttributes:PALPC_MESSAGE_ATTRIBUTES
nil //Timeout:PLARGE_INTEGER
);
end;
end;
function ReceiveMsg2(AlpcPortHandle:HANDLE):NTSTATUS;
var
MsgAttrib:ALPC_MESSAGE_ATTRIBUTES;
MsgSize:SIZE_T;
PMSG:PORT_MESSAGE;
begin
Result:=InitializeMessageAndAttributes(
ALPC_MESSAGE_ATTRIBUTES_VALUES.kAlpcMessageAttributesNone,
nil,
m_MaxMessageLength,
BinCache,
MsgAttrib
);
MsgSize:=PALPC_CUSTOM_MESSAGE(Addr(BinCache[0])).Header.u1.s1.TotalLength;
PMSG.u1.s1.TotalLength:=MsgSize;
if Result = 0 then
begin
MsgSize:=0;
Result:= DoPeekMessage(
AlpcPortHandle,//PortHandle:HANDLE
ALPC_MESSAGE_FLAGS.kAlpcMessageFlagNone,//Flags:ULONG
nil, //SendMessage:PPORT_MESSAGE
nil,//SendMessageAttributes:PALPC_MESSAGE_ATTRIBUTES
Addr(PMSG), //ReceiveMessage:PPORT_MESSAGE
//Addr(PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Header.u1.s1.TotalLength), //BufferLength:PSIZE_T
@MsgSize,
Addr(MsgAttrib), //ReceiveMessageAttributes:PALPC_MESSAGE_ATTRIBUTES
nil //Timeout:PLARGE_INTEGER
);
end;
end;
function ReceiveMsgFromServer:NTSTATUS;
begin
Result:=ReceiveMsg(m_AlpcClientPortHandle);
end;
function ReceiveMsgFromClient:NTSTATUS;
begin
Result:=ReceiveMsg(m_AlpcServerPortHandle);
end;
procedure InitializeObjectAttributes(
Len:ULONG;
RootDirectory:Cardinal;
Attributes:ULONG;
ObjectName:PUNICODE_STRING;
SecurityDescriptor:PSECURITY_DESCRIPTOR;
SecurityQualityOfService:PSecurityQualityOfService;
var alpcPortObjectAttributes:OBJECT_ATTRIBUTES
);inline;
begin
alpcPortObjectAttributes.Length:=Len;
alpcPortObjectAttributes.RootDirectory:=RootDirectory;
alpcPortObjectAttributes.Attributes:=Attributes;
alpcPortObjectAttributes.ObjectName:=ObjectName;
alpcPortObjectAttributes.SecurityDescriptor:=SecurityDescriptor;
alpcPortObjectAttributes.SecurityQualityOfService:=SecurityQualityOfService;
end;
function ServerCreatePort(
const ServerName:WideString
):NTSTATUS;
var
alpcPortObjectAttributes:OBJECT_ATTRIBUTES;
alpcPortAttributes:ALPC_PORT_ATTRIBUTES;
PortName:UNICODE_STRING;
begin
InitializeAlpcPortAttributes(alpcPortAttributes);
RTL_CONSTANT_STRING(ServerName,PortName);
InitializeObjectAttributes(SizeOf(OBJECT_ATTRIBUTES),0,0,Addr(PortName),nil,nil,alpcPortObjectAttributes);
Result :=CreateServer(
Addr(m_AlpcServerPortHandle),
Addr(alpcPortObjectAttributes),
Addr(alpcPortAttributes)
);
end;
function ServerAcceptClient(
):NTSTATUS;
var
alpcPortAttributes:ALPC_PORT_ATTRIBUTES;
clientHandle:HANDLE;
//connectionRequest:PPORT_MESSAGE;
begin
InitializeAlpcPortAttributes(alpcPortAttributes);
Result:= AcceptClients(
Addr(clientHandle), // [out] PortHandle : PHANDLE
m_AlpcServerPortHandle, // [in] ConnectionPortHandle : HANDLE
ALPC_MESSAGE_FLAGS.kAlpcMessageFlagNone, // [in] Flags : ULONG
nil, //[in opt] ObjectAttributes : POBJECT_ATTRIBUTES
Addr(alpcPortAttributes), // [in opt] PortAttributes : PALPC_PORT_ATTRIBUTES
nil, //[in opt] PortContext : PVOID
Addr(PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Header), // [in] ConnectionRequest : PPORT_MESSAGE
nil, // [inout opt] ConnectionMessageAttributes : PALPC_MESSAGE_ATTRIBUTES
True
);
if Result = 0 then
begin
m_ClientList.Add(PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Header.MessageId,clientHandle);
end;
end;
function ServerListenAndPeekMessage:NTSTATUS;
var
s:RawByteString;
status:ULONG;
begin
Result:= ReceiveMsgFromClient;
if Result = 0 then
begin
status:= PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Header.u2.s2._Type and $FFF;
case status of
LPC_PORT_CLOSED,
LPC_LOST_REPLY,
LPC_CLIENT_DIED:
begin
{SaveLog('Delete Client,HANDLE:' + IntToStr(
Cardinal(m_ClientList[PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Header.MessageId])
));
}
m_ClientList.Remove(PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Header.MessageId);
end;
LPC_REQUEST:
begin
{SaveLog(
'Rec Msg:' + PWideChar(MsgBin) + ',MsgID:' +
IntToStr(PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Header.MessageId)
);
}
s:='Hello,response from server';
//SaveLog('Msg Context:' + s);
MoveMemory(MsgBin,@s[1],Length(s));
MsgLen^:=Length(s);
Result:=SendMsgToClient(PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Header.MessageId);
if Result = 0 then
begin
// SaveLog('Send Msg To Client!,True');
end
else
begin
//SaveLog('Send Msg To Client,False,errcode:' + IntToHex(Result,8));
Exit;
end;
end;
LPC_CONNECTION_REQUEST:
begin
Result:=ServerAcceptClient;
if Result <> 0 then
begin
//SaveLog('Accept Client, Occur a error,errcode:' + IntToHex(Result,8));
Exit;
end;
end
else
begin
//SaveLog('Rec a message ,code:' + IntToHex(Result,8));
end;
end;
end;
end;
{$ENDREGION}
initialization
MsgBin:=Addr(PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Buffer[0]);
MsgLen:=Addr(PALPC_CUSTOM_MESSAGE(Addr(MsgCache[0])).Header.u1.s1.DataLength);
m_ClientList:=TDictionary<ULONG,HANDLE>.Create;
finalization
m_ClientList.Free;
end.
|
unit FC.Trade.Trader.MT4StatementImport;
interface
uses
Classes, Math,Graphics, Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions,
StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators,
Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage;
type
//Интерфейс нашего трейдера
//Пока здесь объявлен. Потом как устоится, вынести в Definitions
IStockTraderMT4StatementImport = interface
['{D80AB38D-90BC-4F46-BDBA-02417B946A95}']
end;
TImportedRecord = class
Time : TDateTime;
Type_: string;
OrderNo : integer;
Size : TSCRealNumber;
Price: TSCRealNumber;
SL : TSCRealNumber;
TP : TSCRealNumber;
Order : IStockOrder;
end;
//Собственно трейдер
TStockTraderMT4StatementImport = class (TStockTraderBase,IStockTraderMT4StatementImport)
private
FPropPath: TPropertyString;
FImportedData : TObjectList;
procedure LoadFromFile;
procedure CleanOrders;
protected
procedure OnBeginWorkSession; override;
procedure OnEndWorkSession; override;
public
//Создание-удаление своих объектов
procedure OnCreateObjects; override;
procedure OnReleaseObjects; override;
procedure OnPropertyChanged(aNotifier:TProperty); override;
//Посчитать
procedure UpdateStep2(const aTime: TDateTime); override;
constructor Create; override;
destructor Destroy; override;
procedure Dispose; override;
end;
implementation
uses Variants,Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message,
StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory,
FC.DataUtils,DateUtils;
{ TStockTraderMT4StatementImport }
procedure TStockTraderMT4StatementImport.CleanOrders;
var
i: Integer;
begin
if FImportedData=nil then
exit;
for i := 0 to FImportedData.Count - 1 do
TImportedRecord(FImportedData[i]).Order:=nil;
end;
constructor TStockTraderMT4StatementImport.Create;
begin
inherited Create;
RegisterProperties([FPropPath]);
end;
destructor TStockTraderMT4StatementImport.Destroy;
begin
inherited;
end;
procedure TStockTraderMT4StatementImport.Dispose;
begin
inherited;
end;
procedure TStockTraderMT4StatementImport.OnBeginWorkSession;
begin
inherited;
CleanOrders;
end;
procedure TStockTraderMT4StatementImport.OnCreateObjects;
begin
inherited;
end;
procedure TStockTraderMT4StatementImport.OnEndWorkSession;
begin
inherited;
CleanOrders;
end;
procedure TStockTraderMT4StatementImport.OnPropertyChanged(
aNotifier: TProperty);
begin
inherited;
if aNotifier=FPropPath then
begin
FreeAndNil(FImportedData);
if FPropPath.Value<>'' then
LoadFromFile;
end;
end;
procedure TStockTraderMT4StatementImport.OnReleaseObjects;
begin
inherited;
end;
procedure TStockTraderMT4StatementImport.LoadFromFile;
var
aText: TStringList;
i: integer;
aRecord: TImportedRecord;
aParts : TStringList;
begin
if FImportedData<>nil then
exit;
aText:=TStringList.Create;
aParts:=TStringList.Create;
try
aText.LoadFromFile(FPropPath.ValueAsText);
for i := 1 to aText.Count-1 do
begin
SplitString(aText[i],aParts,[';']);
aRecord:=TImportedRecord.Create;
//aRecord.N:=StrToInt(aParts[0]);
aRecord.Time:=StrToDateTime(aParts[1]);
aRecord.Type_:=aParts[2];
aRecord.OrderNo:=StrToInt(aParts[3]);
aRecord.Size:=StrToFloat(aParts[4]);
aRecord.TP:=StrToFloat(aParts[5]);
aRecord.SL:=StrToFloat(aParts[5]);
FImportedData.Add(aRecord);
end;
finally
aText.Free;
end;
end;
procedure TStockTraderMT4StatementImport.UpdateStep2(const aTime: TDateTime);
var
i: integer;
aRecord: TImportedRecord;
begin
LoadFromFile;
aRecord:=nil;
for I := 0 to FImportedData.Count-1 do
begin
if SameDateTime(TImportedRecord(FImportedData[i]).Time,aTime) then
begin
aRecord:=TImportedRecord(FImportedData[i]);
break;
end;
end;
if aRecord=nil then
exit;
if SameText(aRecord.Type_,'buy') then
aRecord.Order:=OpenOrder(okBuy,1,aRecord.SL,aRecord.TP,0)
else if SameText(aRecord.Type_,'buy limit') then
aRecord.Order:=OpenOrderAt(okBuy,aRecord.Price, 1,aRecord.SL,aRecord.TP,0)
else if SameText(aRecord.Type_,'sell') then
aRecord.Order:=OpenOrder(okSell,1,aRecord.SL,aRecord.TP,0)
else if SameText(aRecord.Type_,'sell limit') then
aRecord.Order:=OpenOrderAt(okSell,aRecord.Price,1,aRecord.SL,aRecord.TP,0)
end;
initialization
FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Samples','MT4StatementImport',TStockTraderMT4StatementImport,IStockTraderMT4StatementImport);
end.
|
{
Double Commander
-------------------------------------------------------------------------
PCRE - Perl Compatible Regular Expressions
Copyright (C) 2019 Alexander Koblov (alexx2000@mail.ru)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
}
unit uRegExprU;
{$mode delphi}
interface
uses
Classes, SysUtils, CTypes;
type
{ TRegExprU }
TRegExprU = class
private
FCode: Pointer;
FMatch: Pointer;
FInput: PAnsiChar;
FVector: pcsize_t;
FVectorLength: cint;
FExpression: String;
FInputLength: UIntPtr;
FOvector: array[Byte] of cint;
procedure SetExpression(AValue: String);
function GetMatchLen(Idx : integer): PtrInt;
function GetMatchPos(Idx : integer): PtrInt;
public
destructor Destroy; override;
class function Available: Boolean;
function Exec(AOffset: UIntPtr): Boolean;
procedure SetInputString(AInputString : PAnsiChar; ALength : UIntPtr);
public
property Expression : String read FExpression write SetExpression;
property MatchPos [Idx : integer] : PtrInt read GetMatchPos;
property MatchLen [Idx : integer] : PtrInt read GetMatchLen;
end;
implementation
uses
DynLibs, DCOSUtils, uDebug;
// PCRE 2
const
libpcre2 = {$IF DEFINED(MSWINDOWS)}
'libpcre2-8.dll'
{$ELSEIF DEFINED(DARWIN)}
'libpcre2-8.dylib'
{$ELSEIF DEFINED(UNIX)}
'libpcre2-8.so.0'
{$IFEND};
const
PCRE2_CONFIG_UNICODE = 9;
PCRE2_UTF = $00080000;
var
pcre2_compile: function(pattern: PAnsiChar; length: csize_t; options: cuint32; errorcode: pcint; erroroffset: pcsize_t; ccontext: Pointer): Pointer; cdecl;
pcre2_code_free: procedure(code: Pointer); cdecl;
pcre2_get_error_message: function(errorcode: cint; buffer: PAnsiChar; bufflen: csize_t): cint; cdecl;
pcre2_match: function(code: Pointer; subject: PAnsiChar; length: csize_t; startoffset: csize_t; options: cuint32; match_data: Pointer; mcontext: Pointer): cint; cdecl;
pcre2_get_ovector_pointer: function(match_data: Pointer): pcsize_t; cdecl;
pcre2_match_data_create_from_pattern: function(code: Pointer; gcontext: Pointer): Pointer; cdecl;
pcre2_match_data_free: procedure(match_data: Pointer); cdecl;
pcre2_config: function(what: cuint32; where: pointer): cint; cdecl;
// PCRE 1
const
libpcre = {$IF DEFINED(MSWINDOWS)}
'libpcre.dll'
{$ELSEIF DEFINED(DARWIN)}
'libpcre.dylib'
{$ELSEIF DEFINED(UNIX)}
'libpcre.so.1'
{$IFEND};
const
PCRE_CONFIG_UTF8 = 0;
PCRE_UTF8 = $00000800;
var
pcre_compile: function(pattern: PAnsiChar; options: cint; errptr: PPAnsiChar; erroffset: pcint; tableptr: PAnsiChar): pointer; cdecl;
pcre_exec: function(code: pointer; extra: Pointer; subject: PAnsiChar; length: cint; startoffset: cint; options: cint; ovector: pcint; ovecsize: cint): cint; cdecl;
pcre_free: procedure(code: pointer); cdecl;
pcre_study: function(code: Pointer; options: cint; errptr: PPAnsiChar): Pointer; cdecl;
pcre_free_study: procedure(extra: Pointer); cdecl;
pcre_config: function(what: cint; where: pointer): cint; cdecl;
var
pcre_new: Boolean;
hLib: TLibHandle = NilHandle;
{ TRegExprU }
procedure TRegExprU.SetExpression(AValue: String);
var
Message: String;
error: PAnsiChar;
errornumber: cint;
erroroffset: cint;
begin
FExpression:= AValue;
if pcre_new then
begin
FCode := pcre2_compile(PAnsiChar(AValue), Length(AValue), PCRE2_UTF, @errornumber, @erroroffset, nil);
if Assigned(FCode) then
FMatch := pcre2_match_data_create_from_pattern(FCode, nil)
else begin
SetLength(Message, MAX_PATH + 1);
pcre2_get_error_message(errornumber, PAnsiChar(Message), MAX_PATH);
raise Exception.Create(Message);
end;
end
else begin
FCode := pcre_compile(PAnsiChar(AValue), PCRE_UTF8, @error, @erroroffset, nil);
if Assigned(FCode) then
FMatch:= pcre_study(FCode, 0, @error)
else
raise Exception.Create(StrPas(error));
end;
end;
function TRegExprU.GetMatchLen(Idx : integer): PtrInt;
begin
if (Idx < FVectorLength) then
begin
if pcre_new then
Result := UIntPtr(FVector[Idx * 2 + 1]) - UIntPtr(FVector[Idx * 2])
else
Result := UIntPtr(FOvector[Idx * 2 + 1]) - UIntPtr(FOvector[Idx * 2]);
end
else
Result:= 0;
end;
function TRegExprU.GetMatchPos(Idx : integer): PtrInt;
begin
if (Idx < FVectorLength) then
begin
if pcre_new then
Result := UIntPtr(FVector[Idx * 2]) + 1
else
Result := UIntPtr(FOvector[Idx * 2]) + 1;
end
else
Result:= 0;
end;
destructor TRegExprU.Destroy;
begin
if Assigned(FCode) then
begin
if pcre_new then
pcre2_code_free(FCode)
else
pcre_free(FCode);
end;
if Assigned(FMatch) then
begin
if pcre_new then
pcre2_match_data_free(FMatch)
else
pcre_free_study(FMatch);
end;
inherited Destroy;
end;
class function TRegExprU.Available: Boolean;
begin
Result:= (hLib <> NilHandle);
end;
function TRegExprU.Exec(AOffset: UIntPtr): Boolean;
begin
Dec(AOffset);
if pcre_new then
begin
FVectorLength:= pcre2_match(FCode, FInput, FInputLength,
AOffset, 0, FMatch, nil);
Result:= (FVectorLength >= 0);
if Result then
FVector := pcre2_get_ovector_pointer(FMatch);
end
else begin
FVectorLength := pcre_exec(FCode, FMatch, FInput, FInputLength,
AOffset, 0, FOvector, SizeOf(FOvector));
// The output vector wasn't big enough
if (FVectorLength = 0) then FVectorLength:= SizeOf(FOvector) div 3;
Result:= (FVectorLength >= 0);
end;
end;
procedure TRegExprU.SetInputString(AInputString: PAnsiChar; ALength: UIntPtr);
begin
FInput:= AInputString;
FInputLength:= ALength;
end;
procedure Initialize;
var
Where: IntPtr;
begin
hLib:= LoadLibrary(libpcre2);
if (hLib <> NilHandle) then
begin
pcre_new:= True;
try
@pcre2_config:= SafeGetProcAddress(hLib, 'pcre2_config_8');
if (pcre2_config(PCRE2_CONFIG_UNICODE, @Where) <> 0) or (Where = 0) then
raise Exception.Create('pcre2_config(PCRE2_CONFIG_UNICODE)');
@pcre2_compile:= SafeGetProcAddress(hLib, 'pcre2_compile_8');
@pcre2_code_free:= SafeGetProcAddress(hLib, 'pcre2_code_free_8');
@pcre2_get_error_message:= SafeGetProcAddress(hLib, 'pcre2_get_error_message_8');
@pcre2_match:= SafeGetProcAddress(hLib, 'pcre2_match_8');
@pcre2_get_ovector_pointer:= SafeGetProcAddress(hLib, 'pcre2_get_ovector_pointer_8');
@pcre2_match_data_create_from_pattern:= SafeGetProcAddress(hLib, 'pcre2_match_data_create_from_pattern_8');
@pcre2_match_data_free:= SafeGetProcAddress(hLib, 'pcre2_match_data_free_8');
except
on E: Exception do
begin
FreeLibrary(hLib);
hLib:= NilHandle;
DCDebug(E.Message);
end;
end;
end
else begin
hLib:= LoadLibrary(libpcre);
{$IF DEFINED(LINUX)}
// Debian use another library name
if (hLib = NilHandle) then
hLib:= LoadLibrary('libpcre.so.3');
{$ENDIF}
if (hLib <> NilHandle) then
begin
pcre_new:= False;
try
@pcre_config:= SafeGetProcAddress(hLib, 'pcre_config');
if (pcre_config(PCRE_CONFIG_UTF8, @Where) <> 0) or (Where = 0) then
raise Exception.Create('pcre_config(PCRE_CONFIG_UTF8)');
@pcre_compile:= SafeGetProcAddress(hLib, 'pcre_compile');
@pcre_exec:= SafeGetProcAddress(hLib, 'pcre_exec');
@pcre_free:= PPointer(SafeGetProcAddress(hLib, 'pcre_free'))^;
@pcre_study:= SafeGetProcAddress(hLib, 'pcre_study');
@pcre_free_study:= SafeGetProcAddress(hLib, 'pcre_free_study');
except
on E: Exception do
begin
FreeLibrary(hLib);
hLib:= NilHandle;
DCDebug(E.Message);
end;
end;
end;
end;
end;
initialization
Initialize;
end.
|
program Float1;
var
A,B,C : Real;
begin
A := 1.1;
B := 2.2;
C := A + B;
WriteLn('A = ', A, ', B = ', B, ', C = ', C);
end.
|
unit UCirculo;
interface
uses
UFormaGeometrica
, Math
, Graphics
, Controls
;
type
TCirculo = class(TFormaGeometrica)
private
FDiametro: Integer;
public
constructor Create(const coCor: TColor);
function CalculaArea: Double; override;
function SolicitaParametros: Boolean; override;
procedure Desenha(const ciX: Integer; const ciY: Integer;
const coParent: TWinControl); override;
end;
implementation
uses
SysUtils
, Dialogs
, ExtCtrls
;
{ Circulo }
constructor TCirculo.Create(const coCor: TColor);
begin
Inherited Create(tfgCirculo, coCor);
FShape.Shape := stCircle;
end;
function TCirculo.CalculaArea: Double;
var
ldRaio: Double;
begin
ldRaio := FDiametro / 2;
Result := PI * Power(ldRaio, 2);
end;
procedure TCirculo.Desenha(const ciX, ciY: Integer;
const coParent: TWinControl);
begin
inherited;
FShape.Width := FDiametro;
FShape.Height := FDiametro;
end;
function TCirculo.SolicitaParametros: Boolean;
begin
FDiametro := StrToIntDef(InputBox('Informe', 'Diametro do Circulo', ''), -1);
Result := FDiametro > -1;
end;
end.
|
unit FormSimpleCameraUnit;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Viewport3D,
System.Math.Vectors, FMX.Types3D, FMX.Controls3D, FMX.Objects3D,
FMX.MaterialSources, FMX.Gestures;
type
TFormSimpleCamera = class(TForm)
Viewport3DMain: TViewport3D;
DummyScene: TDummy;
DummyXY: TDummy;
CameraZ: TCamera;
LightCamera: TLight;
GestureManager1: TGestureManager;
MaterialSourceY: TLightMaterialSource;
MaterialSourceZ: TLightMaterialSource;
MaterialSourceX: TLightMaterialSource;
CylX: TCylinder;
ConeX: TCone;
CylY: TCylinder;
ConeY: TCone;
CylZ: TCylinder;
ConeZ: TCone;
procedure Viewport3DMainMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure Viewport3DMainMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
procedure Viewport3DMainMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; var Handled: Boolean);
procedure FormGesture(Sender: TObject;
const [Ref] EventInfo: TGestureEventInfo; var Handled: Boolean);
private
FDown: TPointF;
FLastDistance: integer;
procedure DoZoom(aIn: boolean);
public
{ Public declarations }
end;
var
FormSimpleCamera: TFormSimpleCamera;
implementation
{$R *.fmx}
const
ROTATION_STEP = 0.3;
ZOOM_STEP = 2;
CAMERA_MAX_Z = -2;
CAMERA_MIN_Z = -102;
procedure TFormSimpleCamera.DoZoom(aIn: boolean);
var newZ: single;
begin
if aIn then
newZ := CameraZ.Position.Z + ZOOM_STEP
else
newZ := CameraZ.Position.Z - ZOOM_STEP;
if (newZ < CAMERA_MAX_Z) and (newZ > CAMERA_MIN_Z) then
CameraZ.Position.Z := newZ;
end;
procedure TFormSimpleCamera.FormGesture(Sender: TObject;
const [Ref] EventInfo: TGestureEventInfo; var Handled: Boolean);
var delta: integer;
begin
if EventInfo.GestureID = igiZoom then
begin
if (not(TInteractiveGestureFlag.gfBegin in EventInfo.Flags)) and (not(TInteractiveGestureFlag.gfEnd in EventInfo.Flags)) then
begin
delta := EventInfo.Distance - FLastDistance;
DoZoom(delta > 0);
end;
FLastDistance := EventInfo.Distance;
end;
end;
procedure TFormSimpleCamera.Viewport3DMainMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
FDown := PointF(X, Y);
end;
procedure TFormSimpleCamera.Viewport3DMainMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Single);
begin
if (ssLeft in Shift) then
begin
DummyXY.RotationAngle.X := DummyXY.RotationAngle.X - ((Y - FDown.Y) * ROTATION_STEP);
DummyXY.RotationAngle.Y := DummyXY.RotationAngle.Y + ((X - FDown.X) * ROTATION_STEP);
FDown := PointF(X, Y);
end;
end;
procedure TFormSimpleCamera.Viewport3DMainMouseWheel(Sender: TObject;
Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean);
begin
DoZoom(WheelDelta > 0);
end;
end.
|
(**
This module contains code which represents a form for configuring the zipping of
projects during the compilation cycle.
@Author David Hoyle
@Version 1.0
@Date 05 Jan 2018
**)
Unit ITHelper.ZIPDialogue;
Interface
Uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
Buttons,
ToolsAPI,
ITHelper.Interfaces;
{$INCLUDE 'CompilerDefinitions.inc'}
Type
(** A class to represent the form. **)
TfrmITHZIPDialogue = Class(TForm)
lblZipInfo: TLabel;
lblZIPName: TLabel;
lblAdditionalFiles: TLabel;
lblFilePatternsToExclude: TLabel;
cbxEnabledZipping: TCheckBox;
lbAdditionalWildcards: TListBox;
btnAddZip: TBitBtn;
btnEditZip: TBitBtn;
btnDeleteZip: TBitBtn;
edtZipName: TEdit;
btnBrowseZip: TButton;
edtBasePath: TEdit;
btnBrowseBasePath: TButton;
mmoExclusionPatterns: TMemo;
btnOK: TBitBtn;
btnCancel: TBitBtn;
dlgOpenZIP: TOpenDialog;
btnHelp: TBitBtn;
Procedure btnAddZipClick(Sender: TObject);
Procedure btnBrowseBasePathClick(Sender: TObject);
Procedure btnBrowseZipClick(Sender: TObject);
Procedure btnDeleteZipClick(Sender: TObject);
Procedure btnEditZipClick(Sender: TObject);
Procedure cbxEnabledZippingClick(Sender: TObject);
Procedure edtZipEXEExit(Sender: TObject);
Procedure btnOKClick(Sender: TObject);
Procedure InitialiseOptions(Const GlobalOps: IITHGlobalOptions);
Procedure SaveOptions(Const GlobalOps: IITHGlobalOptions);
procedure btnHelpClick(Sender: TObject);
Strict Private
{ Private declarations }
FProject : IOTAProject;
FFileName: String;
Public
{ Public declarations }
Class Procedure Execute(Const Project: IOTAProject; Const GlobalOps: IITHGlobalOptions);
End;
Implementation
{$R *.dfm}
Uses
ITHelper.AdditionalZipFilesForm,
FileCtrl,
ITHelper.TestingHelperUtils,
IniFiles,
ITHelper.CommonFunctions;
Const
(** An INI Section for the dialogues size and position. **)
strZIPDlgSection = 'ZIP Dlg';
(** An INI Key for the top **)
strTopKey = 'Top';
(** An INI Key for the left **)
strLeftLey = 'Left';
(** An INI Key for the height **)
strHeightKey = 'Height';
(** An INI Key for the width **)
strWidthKey = 'Width';
(**
This is an on click event handler for the Add ZIP button.
@precon None.
@postcon Allows the user to add
@param Sender as a TObject
**)
Procedure TfrmITHZIPDialogue.btnAddZipClick(Sender: TObject);
Var
strWildcard: String;
Begin
strWildcard := edtBasePath.Text;
If strWildcard = '' Then
strWildcard := ExtractFilePath(edtZipName.Text);
If TfrmITHAdditionalZipFiles.Execute(FProject, strWildcard) Then
lbAdditionalWildcards.Items.Add(strWildcard);
End;
(**
This method is an on click event handler for the Browse Base Path button.
@precon None.
@postcon Allows the user to select a directory to be the base path for
relative directories in the zip process.
@param Sender as a TObject
**)
Procedure TfrmITHZIPDialogue.btnBrowseBasePathClick(Sender: TObject);
ResourceString
strZipBaseDirectory = 'Zip Base Directory';
Var
strDir: String;
Begin
strDir := edtBasePath.Text;
If strDir = '' Then
strDir := ExpandMacro(ExtractFilePath(edtZipName.Text), FProject.FileName);
If SelectDirectory(strZipBaseDirectory, '', strDir {$IFDEF D2005},
[sdNewFolder, sdShowShares, sdNewUI, sdValidateDir] {$ENDIF}) Then
edtBasePath.Text := strDir + '\';
End;
(**
This method allows the user to browse for a zip file.
@precon None.
@postcon If the dialogue is confirmed the zip file name is updated with the
selected file.
@param Sender as a TObject
**)
Procedure TfrmITHZIPDialogue.btnBrowseZipClick(Sender: TObject);
Begin
dlgOpenZIP.FileName := ExtractFileName(ExpandMacro(edtZipName.Text, FProject.FileName));
dlgOpenZIP.InitialDir := ExtractFilePath(ExpandMacro(edtZipName.Text, FProject.FileName));
If dlgOpenZIP.Execute Then
edtZipName.Text := dlgOpenZIP.FileName;
End;
(**
This is an on click event handler for the Delete Zip button.
@precon None.
@postcon Deletes the selected items from the additional wildcards list box.
@param Sender as a TObject
**)
Procedure TfrmITHZIPDialogue.btnDeleteZipClick(Sender: TObject);
Begin
If lbAdditionalWildcards.ItemIndex > -1 Then
lbAdditionalWildcards.DeleteSelected;
End;
(**
This is an on click event handler for the Edit Zip button.
@precon None.
@postcon Displays the selected additional wildcard so that it can be edited.
@param Sender as a TObject
**)
Procedure TfrmITHZIPDialogue.btnEditZipClick(Sender: TObject);
Var
strWildcard: String;
iIndex : Integer;
Begin
iIndex := lbAdditionalWildcards.ItemIndex;
If iIndex > -1 Then
Begin
strWildcard := lbAdditionalWildcards.Items[iIndex];
If TfrmITHAdditionalZipFiles.Execute(FProject, strWildcard) Then
lbAdditionalWildcards.Items[iIndex] := strWildcard;
End;
End;
(**
This is an on click event handler for the Help button.
@precon None.
@postcon Displays the ZIP Options help page.
@param Sender as a TObject
**)
Procedure TfrmITHZIPDialogue.btnHelpClick(Sender: TObject);
Const
strZIPOptions = 'ZIPOptions';
Begin
HtmlHelp(0, PChar(ITHHTMLHelpFile(strZIPOptions)), HH_DISPLAY_TOPIC, 0);
End;
(**
This is an on click event handler for the OK button.
@precon None.
@postcon Checks the paths of the zip file and base directory and then confirms the
dialogue.
@param Sender as a TObject
**)
Procedure TfrmITHZIPDialogue.btnOKClick(Sender: TObject);
ResourceString
strZipFileBaseDirectoryDoesNotExist = 'The zip file base directory "%s" does not exist.';
strZipFilePathDirectoryDoesNotExist = 'The zip file path directory "%s" does not exist.';
Begin
If cbxEnabledZipping.Checked And Not SysUtils.DirectoryExists(ExpandMacro(edtBasePath.Text,
FProject.FileName)) Then
Begin
MessageDlg(Format(strZipFileBaseDirectoryDoesNotExist,
[ExpandMacro(edtBasePath.Text, FProject.FileName)]), mtError, [mbOK], 0);
ModalResult := mrNone;
End;
If cbxEnabledZipping.Checked And Not SysUtils.DirectoryExists(ExtractFilePath(ExpandMacro(
edtZipName.Text, FProject.FileName))) Then
Begin
MessageDlg(Format(strZipFilePathDirectoryDoesNotExist,
[ExpandMacro(ExtractFilePath(edtZipName.Text), FProject.FileName)]), mtError, [mbOK], 0);
ModalResult := mrNone;
End;
End;
(**
This method enabled or disabled the zip controls depend on whether the user
wishes to use this facility.
@precon None.
@postcon Enabled or disabled the zip controls depend on whether the user
wishes to use this facility.
@param Sender as a TObject
**)
Procedure TfrmITHZIPDialogue.cbxEnabledZippingClick(Sender: TObject);
Begin
lblZIPName.Enabled := cbxEnabledZipping.Checked;
edtZipName.Enabled := cbxEnabledZipping.Checked;
lbAdditionalWildcards.Enabled := cbxEnabledZipping.Checked;
btnAddZip.Enabled := cbxEnabledZipping.Checked;
btnBrowseZip.Enabled := cbxEnabledZipping.Checked;
btnEditZip.Enabled := cbxEnabledZipping.Checked;
btnDeleteZip.Enabled := cbxEnabledZipping.Checked;
lblZipInfo.Enabled := cbxEnabledZipping.Checked;
edtBasePath.Enabled := cbxEnabledZipping.Checked;
btnBrowseBasePath.Enabled := cbxEnabledZipping.Checked;
lblAdditionalFiles.Enabled := cbxEnabledZipping.Checked;
lblFilePatternsToExclude.Enabled := cbxEnabledZipping.Checked;
mmoExclusionPatterns.Enabled := cbxEnabledZipping.Checked;
End;
(**
This is an on exit event handler for the ZIPEXE control.
@precon None.
@postcon Updates the ZIP EXE status on exiting the zip exe control.
@param Sender as a TObject
**)
Procedure TfrmITHZIPDialogue.edtZipEXEExit(Sender: TObject);
ResourceString
strCorrect = 'The zip executable "%s" has been found!';
strInCorrect = 'The zip executable "%s" CAN NOT be found!';
Begin
If FileExists(FFileName) Or DGHFindOnPath(FFileName, '') Then
Begin
lblZipInfo.Caption := Format(strCorrect, [FFileName]);
lblZipInfo.Font.Color := clGreen;
End
Else
Begin
lblZipInfo.Caption := Format(strInCorrect, [FFileName]);
lblZipInfo.Font.Color := clRed;
End;
End;
(**
This is the forms main interface method for editing a projects zipping opions..
@precon Project and GlobalOps must be valid instances.
@postcon Dislays the dialogue.
@param Project as an IOTAProject as a constant
@param GlobalOps as a IITHGlobalOptions as a constant
**)
Class Procedure TfrmITHZIPDialogue.Execute(Const Project: IOTAProject;
Const GlobalOps: IITHGlobalOptions);
ResourceString
strZIPOptionsFor = 'ZIP Options for %s';
Var
frm: TfrmITHZIPDialogue;
Begin
frm := TfrmITHZIPDialogue.Create(Nil);
Try
frm.FProject := Project;
frm.InitialiseOptions(GlobalOps);
frm.cbxEnabledZippingClick(Nil);
frm.edtZipEXEExit(Nil);
frm.Caption := Format(strZIPOptionsFor, [GetProjectName(Project)]);
If frm.ShowModal = mrOK Then
frm.SaveOptions(GlobalOps);
Finally
frm.Free;
End;
End;
(**
This method initialises the project options in the dialogue.
@precon None.
@postcon Initialises the project options in the dialogue.
@param GlobalOps as a IITHGlobalOptions as a constant
**)
Procedure TfrmITHZIPDialogue.InitialiseOptions(Const GlobalOps: IITHGlobalOptions);
Var
iniFile: TMemIniFile;
ProjectOps: IITHProjectOptions;
Begin
iniFile := TMemIniFile.Create(GlobalOps.INIFileName);
Try
Top := iniFile.ReadInteger(strZIPDlgSection, strTopKey, (Screen.Height - Height) Div 2);
Left := iniFile.ReadInteger(strZIPDlgSection, strLeftLey, (Screen.Width - Width) Div 2);
Height := iniFile.ReadInteger(strZIPDlgSection, strHeightKey, Height);
Width := iniFile.ReadInteger(strZIPDlgSection, strWidthKey, Width);
Finally
iniFile.Free;
End;
FFileName := GlobalOps.ZipEXE;
ProjectOps := GlobalOps.ProjectOptions(FProject);
Try
cbxEnabledZipping.Checked := ProjectOps.EnableZipping;
edtZipName.Text := ProjectOps.ZipName;
edtBasePath.Text := ProjectOps.BasePath;
mmoExclusionPatterns.Text := ProjectOps.ExcPatterns;
lbAdditionalWildcards.Items.Assign(ProjectOps.AddZipFiles);
Finally
ProjectOps := Nil;
End;
End;
(**
This method saves the project options to the ini file.
@precon None.
@postcon Saves the project options to the ini file.
@param GlobalOps as a IITHGlobalOptions as a constant
**)
Procedure TfrmITHZIPDialogue.SaveOptions(Const GlobalOps: IITHGlobalOptions);
Var
iniFile: TMemIniFile;
ProjectOps: IITHProjectOptions;
Begin
iniFile := TMemIniFile.Create(GlobalOps.INIFileName);
Try
iniFile.WriteInteger(strZIPDlgSection, strTopKey, Top);
iniFile.WriteInteger(strZIPDlgSection, strLeftLey, Left);
iniFile.WriteInteger(strZIPDlgSection, strHeightKey, Height);
iniFile.WriteInteger(strZIPDlgSection, strWidthKey, Width);
iniFile.UpdateFile;
Finally
iniFile.Free;
End;
ProjectOps := GlobalOps.ProjectOptions(FProject);
Try
ProjectOps.EnableZipping := cbxEnabledZipping.Checked;
ProjectOps.ZipName := edtZipName.Text;
ProjectOps.BasePath := edtBasePath.Text;
ProjectOps.ExcPatterns := mmoExclusionPatterns.Text;
ProjectOps.AddZipFiles.Assign(lbAdditionalWildcards.Items);
Finally
ProjectOps := Nil;
End;
End;
End.
|
unit NtUtils.Tokens.Logon;
interface
uses
Winapi.WinNt, Winapi.WinBase, Winapi.NtSecApi, NtUtils.Exceptions,
NtUtils.Security.Sid, NtUtils.Objects;
// Logon a user
function NtxLogonUser(out hxToken: IHandle; Domain, Username: String;
Password: PWideChar; LogonType: TSecurityLogonType; AdditionalGroups:
TArray<TGroup> = nil): TNtxStatus;
// Logon a user without a password using S4U logon
function NtxLogonS4U(out hxToken: IHandle; Domain, Username: String;
const TokenSource: TTokenSource; AdditionalGroups: TArray<TGroup> = nil):
TNtxStatus;
implementation
uses
Ntapi.ntdef, Ntapi.ntstatus, Ntapi.ntseapi, NtUtils.Processes,
NtUtils.Tokens.Misc;
function NtxLogonUser(out hxToken: IHandle; Domain, Username: String;
Password: PWideChar; LogonType: TSecurityLogonType; AdditionalGroups:
TArray<TGroup>): TNtxStatus;
var
hToken: THandle;
GroupsBuffer: PTokenGroups;
begin
if Length(AdditionalGroups) = 0 then
begin
// Use regular LogonUserW if the caller did not specify additional groups
Result.Location := 'LogonUserW';
Result.Win32Result := LogonUserW(PWideChar(Username), PWideChar(Domain),
Password, LogonType, lpDefault, hToken);
if Result.IsSuccess then
hxToken := TAutoHandle.Capture(hToken);
end
else
begin
// Prepare groups
GroupsBuffer := NtxpAllocGroups2(AdditionalGroups);
// Call LogonUserExExW that allows us to add arbitrary groups to a token.
Result.Location := 'LogonUserExExW';
Result.LastCall.ExpectedPrivilege := SE_TCB_PRIVILEGE;
Result.Win32Result := LogonUserExExW(PWideChar(Username), PWideChar(Domain),
Password, LogonType, lpDefault, GroupsBuffer, hToken, nil, nil, nil,
nil);
if Result.IsSuccess then
hxToken := TAutoHandle.Capture(hToken);
// Note: LogonUserExExW returns ERROR_ACCESS_DENIED where it
// should return ERROR_PRIVILEGE_NOT_HELD which is confusing.
FreeMem(GroupsBuffer);
end;
end;
function NtxLogonS4U(out hxToken: IHandle; Domain, Username: String;
const TokenSource: TTokenSource; AdditionalGroups: TArray<TGroup>):
TNtxStatus;
var
hToken: THandle;
SubStatus: NTSTATUS;
LsaHandle: TLsaHandle;
PkgName: ANSI_STRING;
AuthPkg: Cardinal;
Buffer: PKERB_S4U_LOGON;
BufferSize: Cardinal;
OriginName: ANSI_STRING;
GroupArray: PTokenGroups;
ProfileBuffer: Pointer;
ProfileSize: Cardinal;
LogonId: TLuid;
Quotas: TQuotaLimits;
begin
{$IFDEF Win32}
// TODO -c WoW64: LsaLogonUser overwrites our memory for some reason
if RtlxAssertNotWoW64(Result) then
Exit;
{$ENDIF}
// Connect to LSA
Result.Location := 'LsaConnectUntrusted';
Result.Status := LsaConnectUntrusted(LsaHandle);
// Lookup for Negotiate package
PkgName.FromString(NEGOSSP_NAME_A);
Result.Location := 'LsaLookupAuthenticationPackage';
Result.Status := LsaLookupAuthenticationPackage(LsaHandle, PkgName, AuthPkg);
if not Result.IsSuccess then
begin
LsaDeregisterLogonProcess(LsaHandle);
Exit;
end;
// We need to prepare a blob where KERB_S4U_LOGON is followed by the username
// and the domain.
BufferSize := SizeOf(KERB_S4U_LOGON) + Length(Username) * SizeOf(WideChar) +
Length(Domain) * SizeOf(WideChar);
Buffer := AllocMem(BufferSize);
Buffer.MessageType := KerbS4ULogon;
Buffer.ClientUpn.Length := Length(Username) * SizeOf(WideChar);
Buffer.ClientUpn.MaximumLength := Buffer.ClientUpn.Length;
// Place the username just after the structure
Buffer.ClientUpn.Buffer := Pointer(NativeUInt(Buffer) +
SizeOf(KERB_S4U_LOGON));
Move(PWideChar(Username)^, Buffer.ClientUpn.Buffer^, Buffer.ClientUpn.Length);
Buffer.ClientRealm.Length := Length(Domain) * SizeOf(WideChar);
Buffer.ClientRealm.MaximumLength := Buffer.ClientRealm.Length;
// Place the domain after the username
Buffer.ClientRealm.Buffer := Pointer(NativeUInt(Buffer) +
SizeOf(KERB_S4U_LOGON) + Buffer.ClientUpn.Length);
Move(PWideChar(Domain)^, Buffer.ClientRealm.Buffer^,
Buffer.ClientRealm.Length);
OriginName.FromString('S4U');
// Allocate PTokenGroups if necessary
if Length(AdditionalGroups) > 0 then
GroupArray := NtxpAllocGroups2(AdditionalGroups)
else
GroupArray := nil;
// Perform the logon
SubStatus := STATUS_SUCCESS;
Result.Location := 'LsaLogonUser';
Result.Status := LsaLogonUser(LsaHandle, OriginName, LogonTypeNetwork,
AuthPkg, Buffer, BufferSize, GroupArray, TokenSource, ProfileBuffer,
ProfileSize, LogonId, hToken, Quotas, SubStatus);
if Result.IsSuccess then
hxToken := TAutoHandle.Capture(hToken);
// Note: LsaLogonUser returns STATUS_ACCESS_DENIED where it
// should return STATUS_PRIVILEGE_NOT_HELD which is confusing.
if Length(AdditionalGroups) > 0 then
Result.LastCall.ExpectedPrivilege := SE_TCB_PRIVILEGE;
// Prefer a more detailed status
if not NT_SUCCESS(SubStatus) then
Result.Status := SubStatus;
// Clean up
LsaFreeReturnBuffer(ProfileBuffer);
LsaDeregisterLogonProcess(LsaHandle);
if Assigned(GroupArray) then
FreeMem(GroupArray);
FreeMem(Buffer);
end;
end.
|
{
Measurement dll for flexible, sequence-based time-resolved data acquisition
using the time-tagged, time-resolved measurement mode (TTTR2) of PicoQuant
single photon counters, meant to be used in combination with qtlab class
'PQ_measurement_generator.py'
Several sequential measurement sections can be defined by
- type of event to be counted:
start, stop, sync, marker 1-4, or any combination of those
(sync, marker4 only for HydraHarp)
- bin size (base resolution: 1 ps (HydraHarp), 4 ps (PicoHarp))
- offset with respect to section start (in units of bin size)
- duration (in units of bin size)
- measurement mode (time axis, repetition axis, sweep axis,
or any combination of those)
- threshold (minimal valid value, maximal valid value) per section
- threshold mode (use minimum, maximum, both or no thresholds)
- reset event (event to start over data acquisition in current section):
start, stop, sync, marker 1-4, or combination of those
The event to start the next section:
- start, stop, sync, marker 1-4, or any combination of those
The event to abort the measurement:
- start, stop, sync, marker 1-4, or any combination of those, or none
Loop behaviour:
- number of sequence repetitions and number of sweep values can be specified
- sweeps can be repeated, or repetitions can be swept
- for sequence, sweep and repetitions, a reset and an increment event can be
specified: start, stop, sync, marker 1-4, automatic, or any combination
- here, automatic means controlled by inner loop
(e.g. in case of a sequence consisting of 4 sections, the fifth
'start increment event' could automatically reset the sequence and/or
automatically increment the next loop (i.e. increment repetition index or
sweep index)
For high data rates, a special, faster measurement function without
evaluation of thresholds is also provided.
Both Picoharp 300 and Hydraharp 400 are supported as measurement device
(set compile condition in pq_tttr_functions correspondingly as
{$DEFINE HH400} or {$DEFINE PH300}; phlib.dll / hhlib.dll should be
installed in the system dll path, typically 'c:\windows\system32\')
Details about configuring and usage of pq_tttr.dll:
see 'PQ_measurement_generator.py'
Lucio Robledo (lucio.robledo@gmail.com), October 2011
Note: PicoHarp manufacturer driver has a bug, data acquisition in TTTR mode
just starts after two pulses are sent to channel0 (start).
}
library pq_tttr;
uses
SysUtils, pq_tttr_functions;
exports start; // starts data acquisition
exports set_dev; // set device-id of measurement device
exports set_debuglevel; // allows to output additional debug information
exports set_abort_condition; // set condition which aborts data acquisition
exports add_section; // adds a new measurement section
exports clear_sections; // clears previously defined sections
exports TTTR2_universal_measurement; // start processing of data, with
// evaluation of threshold conditions
exports TTTR2_universal_measurement_speedmode_unconditional; // start processing
// of data, without evaluation of threshold
// conditions
begin
end.
|
unit LogView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, xBase;
type
TWatchThread = class(T_Thread)
procedure InvokeExec; override;
public
fTime: cardinal;
oTime: cardinal;
class function ThreadName: string; override;
end;
TLogViewer = class(TForm)
mmView: TMemo;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
fLogName: string;
fThrName: TWatchThread;
procedure SetLogName(const s: string);
public
{ Public declarations }
property LogName: string read fLogName write SetLogName;
end;
var
LogViewer: TLogViewer;
implementation
uses RadIni, Plus, Wizard;
{$R *.dfm}
class function TWatchThread.ThreadName: string;
begin
Result := 'WatchLogsThread';
end;
procedure TWatchThread.InvokeExec;
begin
Sleep(100);
fTime := GetFileTime(LogViewer.fLogName);
if fTime <> oTime then
begin
oTime := fTime;
LogViewer.LogName := LogViewer.LogName;
end;
end;
procedure TLogViewer.SetLogName;
procedure LoadFromFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
mmView.Lines.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
begin
fLogName := s;
LoadFromFile(s);
mmView.Font.Name := IniFile.LoggerFontName;
mmView.Font.Height := IniFile.LoggerFontHeight;
mmView.Perform( EM_LINESCROLL, 0, 32767 );
fThrName.oTime := GetFileTime(s);
fThrName.Suspended := False;
end;
procedure TLogViewer.FormCreate(Sender: TObject);
var
s: string;
begin
LogViewer := self;
fThrName := TWatchThread.Create;
s := IniFile.ReadString('Sizes', 'LogViewer', '');
Left := StrToIntDef(ExtractWord(1, s, [',']), Left);
Top := StrToIntDef(ExtractWord(2, s, [',']), Top);
Width := StrToIntDef(ExtractWord(3, s, [',']), Width);
Height := StrToIntDef(ExtractWord(4, s, [',']), Height);
end;
procedure TLogViewer.FormDestroy(Sender: TObject);
begin
fThrName.Terminated := True;
fThrName.WaitFor;
FreeObject(fThrName);
IniFile.WriteString('Sizes', 'LogViewer',
IntToStr(Left) + ',' +
IntToStr(Top) + ',' +
IntToStr(Width) + ',' +
IntToStr(Height));
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
{/*
* multimirror.c
* Celeste Fowler, 1997
*
* An example of creating multiple reflections (as in a room with
* mirrors on opposite walls.
*
*/}
unit Unit1;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Menus, Controls,
Dialogs, SysUtils, OpenGL, StdCtrls, Math;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC: HDC;
hrc: HGLRC;
procedure SetDCPixelFormat;
procedure draw_scene(passes:GLint; cullFace:GLenum;
stencilVal:GLuint; mirror:GLint);
protected
procedure WMPaint(var Msg: TWMPaint); message WM_PAINT;
end;
var
frmGL: TfrmGL;
time : LongInt;
var
cone, qsphere:GLUquadricObj ;
draw_passes : longint = 8;
headsUp : Boolean = False;
Angle : GLfloat = 0.0;
type
TMirror = record
verts : Array [0..3, 0..2] of GLfloat;
scale : Array [0..2] of GLfloat;
trans : Array [0..2] of GLfloat;
end;
var
mirrors : Array[0..1] of Tmirror;
const
nMirrors : GLint = 2;
implementation
uses DGLUT;
{$R *.DFM}
{==========================================================================}
procedure Init;
const
lightpos:Array[0..3]of GLfloat = (0.5, 0.75, 1.5, 1);
begin
//* mirror on the left wall */
With mirrors [0] do begin
verts [0][0]:= -1.0;
verts [0][1]:= -0.75;
verts [0][2]:= -0.75;
verts [1][0]:= -1.0;
verts [1][1]:= 0.75;
verts [1][2]:= -0.75;
verts [2][0]:= -1.0;
verts [2][1]:= 0.75;
verts [2][2]:= 0.75;
verts [3][0]:= -1.0;
verts [3][1]:= -0.75;
verts [3][2]:= 0.75;
scale [0] := -1;
scale [1] := 1;
scale [2] := 1;
trans [0] := 2;
trans [1] := 0;
trans [2] := 0;
end;
//* mirror on the right wall */
With mirrors [1] do begin
verts [0][0]:= 1.0;
verts [0][1]:= -0.75;
verts [0][2]:= 0.75;
verts [1][0]:= 1.0;
verts [1][1]:= 0.75;
verts [1][2]:= 0.75;
verts [2][0]:= 1.0;
verts [2][1]:= 0.75;
verts [2][2]:= -0.75;
verts [3][0]:= 1.0;
verts [3][1]:= -0.75;
verts [3][2]:= -0.75;
scale [0] := -1;
scale [1] := 1;
scale [2] := 1;
trans [0] := -2;
trans [1] := 0;
trans [2] := 0;
end;
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_POSITION, @lightpos);
glEnable(GL_CULL_FACE);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
cone := gluNewQuadric;
qsphere := gluNewQuadric;
end;
procedure make_viewpoint;
var
localwidth : GLfloat;
localheight : GLfloat;
begin
If headsUp then begin
localwidth:= (1 + 2*(draw_passes/nMirrors)) * 1.25;
localheight := localwidth / tan( (30.0/360.0) * (2.0*PI) ) + 1;
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(60, 1, localheight - 3, localheight + 3);
gluLookAt(0, localheight, 0, 0, 0, 0, 0, 0, 1);
end
else begin
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
gluPerspective(60, 1, 0.01, 4 + 2*(draw_passes / nMirrors));
gluLookAt(-2, 0, 0.75, 0, 0, 0, 0, 1, 0);
end;
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
end;
procedure draw_room;
const
{material for the walls, floor, ceiling }
wall_mat:Array[0..3]of GLfloat = (1.0, 1.0, 1.0, 1.0);
begin
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, @wall_mat);
glBegin(GL_QUADS);
{ floor }
glNormal3f(0, 1, 0);
glVertex3f(-1, -1, 1);
glVertex3f(1, -1, 1);
glVertex3f(1, -1, -1);
glVertex3f(-1, -1, -1);
{ ceiling }
glNormal3f(0, -1, 0);
glVertex3f(-1, 1, -1);
glVertex3f(1, 1, -1);
glVertex3f(1, 1, 1);
glVertex3f(-1, 1, 1);
{ left wall }
glNormal3f(1, 0, 0);
glVertex3f(-1, -1, -1);
glVertex3f(-1, 1, -1);
glVertex3f(-1, 1, 1);
glVertex3f(-1, -1, 1);
{ right wall }
glNormal3f(-1, 0, 0);
glVertex3f(1, -1, 1);
glVertex3f(1, 1, 1);
glVertex3f(1, 1, -1);
glVertex3f(1, -1, -1);
{ far wall }
glNormal3f(0, 0, 1);
glVertex3f(-1, -1, -1);
glVertex3f(1, -1, -1);
glVertex3f(1, 1, -1);
glVertex3f(-1, 1, -1);
{/* back wall */}
glNormal3f(0, 0, -1);
glVertex3f(-1, 1, 1);
glVertex3f(1, 1, 1);
glVertex3f(1, -1, 1);
glVertex3f(-1, -1, 1);
glEnd;
end;
procedure draw_cone;
const
cone_mat:Array[0..3]of GLfloat = (0.0, 0.5, 1.0, 1.0);
begin
glPushMatrix;
glTranslatef(0, -1, 0);
glRotatef(-90, 1, 0, 0);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, @cone_mat);
gluCylinder(cone, 0.3, 0, 1.25, 20, 1);
glPopMatrix;
end;
procedure draw_sphere;
const
sphere_mat:Array[0..3]of GLfloat = (1.0, 0.5, 0.0, 1.0);
begin
glPushMatrix;
glTranslatef(0, -0.3, 0);
glRotatef(Angle, 0, 1, 0);
glTranslatef(0.6, 0, 0);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, @sphere_mat);
gluSphere(qsphere, 0.3, 20, 20);
glPopMatrix;
end;
procedure draw_mirror(m : TMirror);
begin
glBegin(GL_QUADS);
glVertex3fv(@m.verts[0]);
glVertex3fv(@m.verts[1]);
glVertex3fv(@m.verts[2]);
glVertex3fv(@m.verts[3]);
glEnd;
end;
function reflect_through_mirror(m:TMirror ; cullFace:GLenum):GLenum;
var
newCullFace:GLenum;
begin
If cullface = GL_FRONT
then newCullFace := GL_BACK
else newCullFace := GL_FRONT;
glMatrixMode(GL_PROJECTION);
glScalef(m.scale[0], m.scale[1], m.scale[2]);
glTranslatef(m.trans[0], m.trans[1], m.trans[2]);
glMatrixMode(GL_MODELVIEW);
{/* must flip the cull face since reflection reverses the orientation
* of the polygons */}
glCullFace(newCullFace);
Result:=newCullFace;
end;
procedure undo_reflect_through_mirror(m : TMirror ; cullFace : GLenum);
begin
glMatrixMode(GL_PROJECTION);
glTranslatef(-m.trans[0], -m.trans[1], -m.trans[2]);
glScalef(1.0/m.scale[0], 1.0/m.scale[1], 1.0/m.scale[2]);
glMatrixMode(GL_MODELVIEW);
glCullFace(cullFace);
end;
const
stencilmask : longint = $FFFFFFFF;
procedure TfrmGL.draw_scene(passes:GLint; cullFace:GLenum;
stencilVal:GLuint; mirror: GLint);
var
newCullFace : GLenum;
passesPerMirror, passesPerMirrorRem, i : GLint;
curMirror, drawMirrors : GLUint;
begin
{/* one pass to draw the real scene */}
passes := passes - 1;
{/* only draw in my designated locations */}
glStencilFunc(GL_EQUAL, stencilVal, stencilmask);
{/* draw things which may obscure the mirrors first */}
draw_sphere;
draw_cone;
{/* now draw the appropriate number of mirror reflections. for
* best results, we perform a depth-first traversal by allocating
* a number of passes for each of the mirrors. */ }
If mirror <> -1 then begin
passesPerMirror := round(passes / (nMirrors - 1));
passesPerMirrorRem := passes mod (nMirrors - 1);
If passes > nMirrors - 1
then drawMirrors := nMirrors - 1
else drawMirrors := passes;
end
else begin
{/* mirror == -1 means that this is the initial scene (there was no
* mirror) */}
passesPerMirror := round(passes / nMirrors);
passesPerMirrorRem := passes mod nMirrors;
If passes > nMirrors
then drawMirrors := nMirrors
else drawMirrors := passes;
end;
i := 0;
While drawMirrors > 0 do begin
curMirror := i mod nMirrors;
If curMirror <> mirror then begin
drawMirrors := drawMirrors - 1;
{/* draw mirror into stencil buffer but not color or depth buffers */}
glColorMask(False, False, False, False);
glDepthMask(False);
glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
draw_mirror(mirrors[curMirror]);
glColorMask(True, True, True, True);
glDepthMask(True);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
{/* draw reflected scene */}
newCullFace := reflect_through_mirror(mirrors[curMirror], cullFace);
If passesPerMirrorRem<>0 then begin
draw_scene(passesPerMirror + 1, newCullFace, stencilVal + 1, curMirror);
passesPerMirrorRem := passesPerMirrorRem - 1;
end
else draw_scene(passesPerMirror, newCullFace, stencilVal + 1,
curMirror);
undo_reflect_through_mirror(mirrors[curMirror], cullFace);
{/* back to our stencil value */}
glStencilFunc(GL_EQUAL, stencilVal, stencilmask);
end;
inc(i);
end;
draw_room;
end;
{=========================================================================
Рисование картинки}
procedure TfrmGL.WMPaint(var Msg: TWMPaint);
var
ps : TPaintStruct;
begin
BeginPaint(Handle, ps);
glDisable(GL_STENCIL_TEST);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT or GL_STENCIL_BUFFER_BIT);
If not headsUp then glEnable(GL_STENCIL_TEST);
draw_scene(draw_passes, GL_BACK, 0, -1);
glDisable(GL_STENCIL_TEST);
If headsUp then begin
{/* draw a red floor on the original scene */}
glDisable(GL_LIGHTING);
glBegin(GL_QUADS);
glColor3f(1, 0, 0);
glVertex3f(-1, -0.95, 1);
glVertex3f(1, -0.95, 1);
glVertex3f(1, -0.95, -1);
glVertex3f(-1, -0.95, -1);
glEnd;
glEnable(GL_LIGHTING);
end;
SwapBuffers(DC);
EndPaint(Handle, ps);
Angle := Angle + 0.25 * (GetTickCount - time) * 360 / 1000;
If Angle >= 360.0 then Angle := 0.0;
time := GetTickCount;
InvalidateRect(Handle, nil, False);
end;
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
Init;
time := GetTickCount;
end;
{=======================================================================
Изменение размеров окна}
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight );
make_viewpoint;
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC(Handle, DC);
DeleteDC (DC);
end;
{=======================================================================
Обработка нажатия клавиши}
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
If Key = Ord ('H') then begin
headsUp := not headsUp;
make_viewpoint;
end;
If Key = VK_RIGHT then begin
draw_passes := draw_passes + 1;
make_viewpoint;
end;
If Key = VK_LEFT then begin
draw_passes := draw_passes - 1;
If draw_passes < 1 then draw_passes := 1;
make_viewpoint;
end;
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or
PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
end.
|
unit uROR_SelectorGrid;
interface
{$IFNDEF NOTMSPACK}
uses
Forms, Classes, Controls, Buttons, uROR_GridView, Graphics, Types,
uROR_AdvColGrid, uROR_Selector, uROR_CustomSelector, OvcFiler;
type
TCCRResultGrid = class(TCCRAdvColGrid)
protected
procedure DblClick; override;
procedure DragOver(Source: TObject; X, Y: Integer; State: TDragState;
var Accept: Boolean); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
public
procedure DragDrop(Source: TObject; X, Y: Integer); override;
end;
TCCRSelectorGrid = class(TCCRCustomSelector)
private
protected
procedure DoUpdateButtons(var EnableAdd, EnableAddAll,
EnableRemove, EnableRemoveAll: Boolean); override;
function getResultList: TCCRResultGrid;
function getSourceList: TCCRSourceList;
public
constructor Create(anOwner: TComponent); override;
procedure Add; override;
procedure AddAll; override;
procedure AddSelectedItems; virtual;
procedure Clear; override;
function CreateResultList: TWinControl; override;
function CreateSourceList: TWinControl; override;
procedure LoadLayout(aStorage: TOvcAbstractStore; aSection: String = ''); override;
procedure Remove; override;
procedure RemoveAll; override;
procedure RemoveSelectedItems; virtual;
procedure SaveLayout(aStorage: TOvcAbstractStore; aSection: String = ''); override;
published
property Align;
//property Alignment;
property Anchors;
//property AutoSize;
property BevelInner default bvNone;
property BevelOuter default bvNone;
property BevelWidth;
property BiDiMode;
property BorderWidth;
property BorderStyle;
//property Caption;
property Color;
property Constraints;
property Ctl3D;
//property UseDockManager default True;
//property DockSite;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FullRepaint;
property Font;
//property Locked;
property ParentBiDiMode;
{$IFDEF VERSION7}
property ParentBackground;
{$ENDIF}
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnCanResize;
property OnClick;
property OnConstrainedResize;
property OnContextPopup;
//property OnDockDrop;
//property OnDockOver;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
//property OnGetSiteInfo;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
//property OnUnDock;
property AddRemoveMode;
property AutoSort;
property CustomAdd;
property CustomRemove;
property IDField;
property OnAdd;
property OnAddAll;
property OnRemove;
property OnRemoveAll;
property OnSplitterMove;
property OnUpdateButtons;
property SplitPos;
property ResultList: TCCRResultGrid read getResultList;
property SourceList: TCCRSourceList read getSourceList;
end;
{$ENDIF}
implementation
{$IFNDEF NOTMSPACK}
uses
Dialogs, SysUtils, uROR_Resources, ComCtrls, Windows, AdvGrid, Math;
///////////////////////////////// TCCRResultGrid \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
procedure TCCRResultGrid.DblClick;
begin
inherited;
if Assigned(Owner) and (Owner is TCCRCustomSelector) then
TCCRCustomSelector(Owner).Remove;
end;
procedure TCCRResultGrid.DragDrop(Source: TObject; X, Y: Integer);
begin
if Source <> Self then
if (Source is TControl) and (TControl(Source).Owner = Owner) then
if Assigned(Owner) and (Owner is TCCRCustomSelector) then
TCCRCustomSelector(Owner).Add;
end;
procedure TCCRResultGrid.DragOver(Source: TObject; X, Y: Integer;
State: TDragState; var Accept: Boolean);
begin
Accept := False;
if Source <> Self then
if (Source is TControl) and (TControl(Source).Owner = Owner) then
begin
Accept := True;
if Assigned(OnDragOver) then
inherited;
end;
end;
procedure TCCRResultGrid.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited;
if Shift = [] then
if (Key = VK_RETURN) or (Key = Word(' ')) then
if Assigned(Owner) and (Owner is TCCRCustomSelector) then
begin
TCCRCustomSelector(Owner).Remove;
Repaint; // To force repainting the current cell
end;
end;
//////////////////////////////// TCCRSelectorGrid \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
constructor TCCRSelectorGrid.Create(anOwner: TComponent);
begin
inherited;
with ResultList do
begin
DefaultRowHeight := 18;
MouseActions.DisjunctRowSelect := True;
MouseActions.RowSelect := True;
end;
with SourceList do
begin
MultiSelect := True;
ReadOnly := True;
end;
end;
procedure TCCRSelectorGrid.Add;
begin
if Assigned(SourceList.Selected) then
begin
inherited;
//--- Default processing
if not CustomAdd then
AddSelectedItems;
//--- Custom event handler
if Assigned(OnAdd) then
OnAdd(Self);
//--- Common post-processing
ResultChanged := True;
end;
end;
procedure TCCRSelectorGrid.AddAll;
begin
inherited;
//--- Default processing
if not CustomAdd then
begin
SourceList.SelectAll;
AddSelectedItems;
end;
//--- Custom event handler
if Assigned(OnAddAll) then
OnAddAll(Self);
//--- Common post-processing
ResultChanged := True;
end;
procedure TCCRSelectorGrid.AddSelectedItems;
procedure copy_items;
var
srci: TCCRGridItem;
oldCursor: TCursor;
restoreCursor: Boolean;
itemId, rawData: String;
fldLst, rdpLst: array of Integer;
i, n: Integer;
begin
oldCursor := Screen.Cursor;
if SourceList.SelCount > 30 then
begin
Screen.Cursor := crHourGlass;
restoreCursor := True;
end
else
restoreCursor := False;
n := Min(SourceList.Fields.Count, ResultList.AllColCount) - 1;
SetLength(fldLst, n+1);
SetLength(rdpLst, n+1);
for i:=0 to n do
begin
fldLst[i] := i;
rdpLst[i] := i + 1;
end;
ResultList.BeginUpdate;
try
srci := SourceList.Selected;
while Assigned(srci) do
begin
itemId := srci.AsString[IDField];
if itemId <> '' then
i := ResultList.FindString(itemId, IDField)
else
i := -1;
if (itemId = '') or (i < 0) then
begin
rawData := srci.GetRawData(fldLst);
ResultList.AddRow;
ResultList.AssignRawData(ResultList.RowCount-1, rawData, rdpLst);
end;
srci := SourceList.GetNextItem(srci, sdAll, [isSelected]);
end;
if AutoSort then
ResultList.QSort;
finally
ResultList.EndUpdate;
if restoreCursor then
Screen.Cursor := oldCursor;
SetLength(fldLst, 0);
SetLength(rdpLst, 0);
end;
end;
var
next: TCCRGridItem;
begin
if SourceList.SelCount > 0 then
begin
SourceList.Items.BeginUpdate;
try
copy_items;
//--- Find the first item after selection
next := SourceList.Items[SourceList.Items.Count-1];
next := TCCRGridItem(GetListItemFollowingSelection(next));
//--- Remove the selected items from the list or unselect them
if AddRemoveMode = armDefault then
SourceList.DeleteSelected
else
SourceList.ClearSelection;
//--- Select the item
if Assigned(next) then
begin
SourceList.Selected := next;
SourceList.ItemFocused := SourceList.Selected;
end
else if SourceList.Items.Count > 0 then
begin
SourceList.Selected := SourceList.Items[SourceList.Items.Count-1];
SourceList.ItemFocused := SourceList.Selected;
end;
finally
SourceList.Items.EndUpdate;
end;
end;
end;
procedure TCCRSelectorGrid.Clear;
begin
inherited;
SourceList.Clear;
ResultList.RemoveAll;
end;
function TCCRSelectorGrid.CreateResultList: TWinControl;
begin
Result := TCCRResultGrid.Create(Self);
end;
function TCCRSelectorGrid.CreateSourceList: TWinControl;
begin
Result := TCCRSourceList.Create(Self);
end;
procedure TCCRSelectorGrid.DoUpdateButtons(var EnableAdd, EnableAddAll,
EnableRemove, EnableRemoveAll: Boolean);
begin
inherited;
if SourceList.Items.Count > 0 then
begin
EnableAdd := Assigned(SourceList.Selected);
EnableAddAll := True;
end
else
begin
EnableAdd := False;
EnableAddAll := False;
end;
if ResultList.RowCount > ResultList.FixedRows then
begin
EnableRemove := ResultList.RowSelectCount > 0;
EnableRemoveAll := True;
end
else
begin
EnableRemove := False;
EnableRemoveAll := False;
end;
end;
function TCCRSelectorGrid.getResultList: TCCRResultGrid;
begin
Result := TCCRResultGrid(GetResultControl);
end;
function TCCRSelectorGrid.getSourceList: TCCRSourceList;
begin
Result := TCCRSourceList(GetSourceControl);
end;
procedure TCCRSelectorGrid.LoadLayout(aStorage: TOvcAbstractStore; aSection: String);
var
sn: String;
begin
if aSection <> '' then
sn := aSection
else
sn := Name;
try
aStorage.Open;
try
SourceList.LoadLayout(aStorage, sn);
ResultList.LoadLayout(aStorage, sn);
finally
aStorage.Close;
end;
except
end;
end;
procedure TCCRSelectorGrid.Remove;
begin
if ResultList.RowSelectCount > 0 then
begin
inherited;
//--- Default processing
if not CustomRemove then
RemoveSelectedItems;
//--- Custom event handler
if Assigned(OnRemove) then
OnRemove(Self);
//--- Common post-processing
ResultChanged := True;
end;
end;
procedure TCCRSelectorGrid.RemoveAll;
begin
inherited;
//--- Default processing
if not CustomRemove then
begin
with ResultList do
SelectRows(FixedRows, RowCount-FixedRows);
RemoveSelectedItems;
end;
//--- Custom event handler
if Assigned(OnRemoveAll) then
OnRemoveAll(Self);
//--- Common post-processing
ResultChanged := True;
end;
procedure TCCRSelectorGrid.RemoveSelectedItems;
procedure copy_items;
var
oldCursor: TCursor;
restoreCursor: Boolean;
fldLst, rdpLst: array of Integer;
dstRow, i, n: Integer;
itemId, rawData: String;
srci: TCCRGridItem;
begin
oldCursor := Screen.Cursor;
if ResultList.RowSelectCount > 30 then
begin
Screen.Cursor := crHourGlass;
restoreCursor := True;
end
else
restoreCursor := False;
n := Min(SourceList.Fields.Count, ResultList.AllColCount) - 1;
SetLength(fldLst, n+1);
SetLength(rdpLst, n+1);
for i:=0 to n do
begin
fldLst[i] := i;
rdpLst[i] := i + 1;
end;
SourceList.Items.BeginUpdate;
try
n := ResultList.AllRowCount - 1;
with ResultList do
for dstRow:=RealRowIndex(FixedRows) to n do
if RowSelect[DisplRowIndex(dstRow)] then
begin
itemId := AllCells[IDField,dstRow];
if (itemId = '') or (SourceList.FindString(itemId, IDField) = nil) then
begin
rawData := GetRawData(dstRow, fldLst);
srci := SourceList.Items.Add;
srci.AssignRawData(rawData, rdpLst);
end;
end;
if AutoSort then
SourceList.AlphaSort;
finally
SourceList.Items.EndUpdate;
if restoreCursor then
Screen.Cursor := oldCursor;
SetLength(fldLst, 0);
SetLength(rdpLst, 0);
end;
end;
begin
if ResultList.RowSelectCount > 0 then
begin
ResultList.BeginUpdate;
try
if AddRemoveMode = armDefault then
copy_items;
ResultList.RemoveSelectedRows;
finally
ResultList.EndUpdate;
end;
end;
end;
procedure TCCRSelectorGrid.SaveLayout(aStorage: TOvcAbstractStore; aSection: String);
var
sn: String;
begin
if aSection <> '' then
sn := aSection
else
sn := Name;
try
aStorage.Open;
try
SourceList.SaveLayout(aStorage, sn);
ResultList.SaveLayout(aStorage, sn);
finally
aStorage.Close;
end;
except
end;
end;
{$ENDIF}
end.
|
unit SpeakingSQLUnit;
interface
uses
JoanModule,
TestClasses,
SysUtils, Generics.Collections, Classes, Contnrs;
type
TSpeakingData = class
private
public
procedure Insert(Speaking: TSpeaking);
procedure Update(Speaking: TSpeaking);
procedure Delete(QuestionNumber: integer; TestIndex: Integer);
function Select(TestIndex: integer) : TObjectList<TQuiz>;
end;
implementation
{ TSpeakingData }
procedure TSpeakingData.Delete(QuestionNumber: integer; TestIndex: Integer);
begin
with Joan.JoanQuery do
begin
Close;
SQL.Clear;
SQL.Text :=
'DELETE FROM speaking ' +
'WHERE (test_idx = :idx) and (number = :quiznumber);';
ParamByName('idx').AsInteger := TestIndex;
ParamByName('quiznumber').AsInteger := QuestionNumber;
ExecSQL();
end;
end;
procedure TSpeakingData.Insert(Speaking: TSpeaking);
begin
with Joan.JoanQuery do
begin
Close;
SQL.Clear;
SQL.Text :=
'INSERT INTO speaking ' +
'(test_idx, number, quiz, response_time) ' +
'VALUES ' +
'(:idx,:quiznumber,:quiz,:responsetime);';
ParamByName('idx').AsInteger := Speaking.Idx;
ParamByName('quiznumber').AsInteger := Speaking.QuizNumber;
ParamByName('quiz').AsString := Speaking.Quiz;
ParamByName('responsetime').AsInteger := Speaking.ResponseTime;
ExecSQL();
end;
end;
procedure TSpeakingData.Update(Speaking: TSpeaking);
begin
with Joan.JoanQuery do
begin
Close;
SQL.Clear;
SQL.Text :=
'UPDATE speaking SET ' +
'test_idx = :idx, number = :quiznumber, quiz = :quiz, ' +
'response_time = :responsetime ' +
'WHERE (test_idx = :idx) and (number = :quiznumber);';
ParamByName('idx').AsInteger := Speaking.Idx;
ParamByName('quiznumber').AsInteger := Speaking.QuizNumber;
ParamByName('quiz').AsString := Speaking.Quiz;
ParamByName('responsetime').AsInteger := Speaking.ResponseTime;
ExecSQL();
end;
end;
function TSpeakingData.Select(
TestIndex: integer): TObjectList<TQuiz>;
var
Speaking: TSpeaking;
begin
Result := TObjectList<TQuiz>.Create;
Joan.JoanQuery.SQL.Clear;
Joan.JoanQuery.SQL.Text := 'SELECT * FROM speaking WHERE test_idx = :index';
Joan.JoanQuery.ParamByName('index').AsInteger := TestIndex;
Joan.JoanQuery.Open;
while not Joan.JoanQuery.Eof do
begin
begin
Speaking := TSpeaking.Create;
Speaking.Idx := Joan.JoanQuery.FieldByName('test_idx').AsInteger;
Speaking.QuizNumber := Joan.JoanQuery.FieldByName('number').AsInteger;
Speaking.Quiz := Joan.JoanQuery.FieldByName('quiz').AsString;
Result.Add(Speaking);
Joan.JoanQuery.Next;
end;
end;
end;
end.
|
{===============================================================================
Copyright(c) 2013, 北京北研兴电力仪表有限责任公司
All rights reserved.
+ 考卷数据操作类
===============================================================================}
unit xPaperAction;
interface
uses Classes, SysUtils, ADODB, xDBActionBase;
type
/// <summary>
/// 考卷数据操作类
/// </summary>
TPaperAction = class(TDBActionBase)
private
public
/// <summary>
/// 编辑考生分数
/// </summary>
procedure EditStuScore(nPaperID, nStuID : Integer; dScore : Double);
/// <summary>
/// 删除考卷
/// </summary>
procedure DelPaper(nPaperID, nStuID : Integer);
end;
var
APaperAction : TPaperAction;
implementation
{ TPaperAction }
procedure TPaperAction.DelPaper(nPaperID, nStuID: Integer);
const
C_SQL = 'delete from PSTUInfo where PaperID = %d and STUNumber = %d';
C_SQL1 = 'delete from PSTU_ANSWER where PaperID = %d and STUNumber = %d';
C_SQL2 = 'seledt * from PSTUInfo where PaperID = %d and STUNumber = %d';
C_SQL3 = 'delete from PExamInfo where PaperID = %d';
begin
FQuery.SQL.Text := Format(C_SQL, [nPaperID, nStuID]);
ExecSQL;
FQuery.SQL.Text := Format(C_SQL1, [nPaperID, nStuID]);
ExecSQL;
FQuery.Open(Format(C_SQL, [nPaperID, nStuID]));
if FQuery.RecordCount = 0 then
begin
FQuery.Close;
FQuery.SQL.Text := Format(C_SQL3, [nPaperID]);
ExecSQL;
end
else
begin
FQuery.Close;
end;
end;
procedure TPaperAction.EditStuScore(nPaperID, nStuID: Integer; dScore: Double);
const
C_SQL = 'update PSTUInfo set StuScore = %f where PaperID = %d and STUNumber = %d';
begin
FQuery.SQL.Text := Format(C_SQL, [dScore, nPaperID, nStuID]);
ExecSQL;
end;
end.
|
unit Wallet.Core;
interface
uses
System.SysUtils,
System.Generics.Collections,
System.Classes,
Wallet.FileHandler,
Wallet.Types;
type
TWalletCore = class
private
WalletsFile: TWalletsFileHandler;
public
Wallets: TStringList;
CurrentWallet: TWallet;
function OpenWallet(AWalletName: string; APassword: string): boolean;
procedure CloseWallet;
procedure CreateNewWallet(APassword: string; Replace: boolean);
function GetWallets: string;
constructor Create;
destructor Destroy; override;
end;
implementation
{ TWalletCore }
procedure TWalletCore.CloseWallet;
begin
CurrentWallet := Default(TWallet);
end;
constructor TWalletCore.Create;
begin
Wallets := TStringList.Create;
WalletsFile := TWalletsFileHandler.Create(Wallets);
CurrentWallet := Default(TWallet);
end;
procedure TWalletCore.CreateNewWallet(APassword: string; Replace: boolean);
begin
if Replace then
CurrentWallet := WalletsFile.CreateNewWallet(APassword)
else
WalletsFile.CreateNewWallet(APassword);
end;
destructor TWalletCore.Destroy;
begin
Wallets.Destroy;
inherited;
end;
function TWalletCore.GetWallets: string;
begin
Result := Wallets.GetText;
end;
function TWalletCore.OpenWallet(AWalletName, APassword: string): boolean;
begin
Result := False;
CurrentWallet := WalletsFile.TryOpenWallet(AWalletName,APassword);
if CurrentWallet.GetAddress = AWalletName then
Result := True;
end;
end.
|
unit ParametricErrorTable;
interface
uses
CustomErrorTable, Data.DB, System.Classes, System.SysUtils, ExcelDataModule,
DSWrap, FireDAC.Comp.Client, NotifyEvents;
type
TParametricErrorType = (petParamNotFound, petParamDuplicate,
petSubParamNotFound, petSubParamDuplicate, petNotUnique);
TParametricErrorTableW = class(TCustomErrorTableW)
private
FOnFixError: TNotifyEventsEx;
FDescription: TFieldWrap;
FFixed: TFieldWrap;
FErrorType: TFieldWrap;
FParameterID: TFieldWrap;
FParameterName: TFieldWrap;
FStringTreeNodeID: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddErrorMessage(const AParameterName, AMessage: string;
const AErrorType: TParametricErrorType; AStringTreeNodeID: Integer);
procedure FilterFixed;
procedure Fix(AParameterID: Integer);
function LocateByID(AStringTreeNodeID: Integer): Boolean;
property OnFixError: TNotifyEventsEx read FOnFixError;
property Description: TFieldWrap read FDescription;
property Fixed: TFieldWrap read FFixed;
property ErrorType: TFieldWrap read FErrorType;
property ParameterID: TFieldWrap read FParameterID;
property ParameterName: TFieldWrap read FParameterName;
property StringTreeNodeID: TFieldWrap read FStringTreeNodeID;
end;
TParametricErrorTable = class(TCustomErrorTable)
private
FParamDuplicateClone: TFDMemTable;
FW: TParametricErrorTableW;
function GetParamDuplicateClone: TFDMemTable;
protected
function CreateWrap: TCustomErrorTableW; override;
public
constructor Create(AOwner: TComponent); override;
property ParamDuplicateClone: TFDMemTable read GetParamDuplicateClone;
property W: TParametricErrorTableW read FW;
end;
implementation
constructor TParametricErrorTable.Create(AOwner: TComponent);
begin
inherited;
FW := Wrap as TParametricErrorTableW;
FieldDefs.Add(W.ParameterName.FieldName, ftWideString, 100);
FieldDefs.Add(W.Error.FieldName, ftWideString, 50);
FieldDefs.Add(W.Description.FieldName, ftWideString, 150);
FieldDefs.Add(W.StringTreeNodeID.FieldName, ftInteger, 0);
FieldDefs.Add(W.ErrorType.FieldName, ftInteger, 0);
FieldDefs.Add(W.ParameterID.FieldName, ftInteger, 0);
FieldDefs.Add(W.Fixed.FieldName, ftBoolean);
CreateDataSet;
Open;
end;
function TParametricErrorTable.CreateWrap: TCustomErrorTableW;
begin
Result := TParametricErrorTableW.Create(Self);
end;
function TParametricErrorTable.GetParamDuplicateClone: TFDMemTable;
begin
if FParamDuplicateClone = nil then
begin
// Есть ошибки сязанные с дублированием параметра и они не исправлены
FParamDuplicateClone :=
W.AddClone(Format('(%s=%d) and (%s=false)',
[W.ErrorType.FieldName, Integer(petParamDuplicate), W.Fixed.FieldName]));
end;
Result := FParamDuplicateClone;
end;
constructor TParametricErrorTableW.Create(AOwner: TComponent);
begin
inherited;
FFixed := TFieldWrap.Create(Self, 'Fixed');
FDescription := TFieldWrap.Create(Self, 'Description', 'Описание');
FErrorType := TFieldWrap.Create(Self, 'ErrorType');
FParameterID := TFieldWrap.Create(Self, 'ParameterID');
FParameterName := TFieldWrap.Create(Self, 'ParameterName', 'Параметр');
FStringTreeNodeID := TFieldWrap.Create(Self, 'StringTreeNodeID');
FOnFixError := TNotifyEventsEx.Create(Self);
end;
destructor TParametricErrorTableW.Destroy;
begin
inherited;
FreeAndNil(FOnFixError);
end;
procedure TParametricErrorTableW.AddErrorMessage(const AParameterName,
AMessage: string; const AErrorType: TParametricErrorType;
AStringTreeNodeID: Integer);
begin
Assert(Active);
Assert(AStringTreeNodeID > 0);
TryAppend;
ParameterName.F.AsString := AParameterName;
Error.F.AsString := ErrorMessage;
Description.F.AsString := AMessage;
StringTreeNodeID.F.AsInteger := AStringTreeNodeID;
ErrorType.F.AsInteger := Integer(AErrorType);
Fixed.F.AsBoolean := False;
TryPost;
end;
procedure TParametricErrorTableW.FilterFixed;
begin
DataSet.Filter := Format('%s = false', [Fixed.FieldName]);
DataSet.Filtered := True;
end;
procedure TParametricErrorTableW.Fix(AParameterID: Integer);
begin
Assert(AParameterID > 0);
TryEdit;
ParameterID.F.AsInteger := AParameterID;
Fixed.F.AsBoolean := True;
TryPost;
FOnFixError.CallEventHandlers(Self);
end;
function TParametricErrorTableW.LocateByID(AStringTreeNodeID: Integer): Boolean;
begin
Result := FDDataSet.LocateEx(StringTreeNodeID.FieldName,
AStringTreeNodeID, []);
end;
end.
|
{
AD.A.P.T. Library
Copyright (C) 2014-2018, Simon J Stuart, All Rights Reserved
Original Source Location: https://github.com/LaKraven/ADAPT
Subject to original License: https://github.com/LaKraven/ADAPT/blob/master/LICENSE.md
}
unit ADAPT.Intf;
{$I ADAPT.inc}
interface
uses
{$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES}
System.Classes;
{$ELSE}
Classes;
{$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES}
{$I ADAPT_RTTI.inc}
type
/// <summary><c>Defines the present State of a Read/Write Lock.</c></summary>
TADReadWriteLockState = (lsWaiting, lsReading, lsWriting);
/// <summary><c>Defines the Ownership role of a container.</c></summary>
TADOwnership = (oOwnsObjects, oNotOwnsObjects);
/// <summary><c>Defines the direction of an Iteration operation.</c></summary>
TADIterateDirection = (idLeft, idRight);
/// <summary><c>Defines the Sorted State of a Collection.</c></summary>
TADSortedState = (ssUnknown, ssUnsorted, ssSorted);
{$IFDEF ADAPT_FLOAT_SINGLE}
/// <summary><c>Single-Precision Floating Point Type.</c></summary>
ADFloat = Single;
{$ELSE}
{$IFDEF ADAPT_FLOAT_EXTENDED}
/// <summary><c>Extended-Precision Floating Point Type.</c></summary>
ADFloat = Extended;
{$ELSE}
/// <summary><c>Double-Precision Floating Point Type.</c></summary>
ADFloat = Double; // This is our default
{$ENDIF ADAPT_FLOAT_DOUBLE}
{$ENDIF ADAPT_FLOAT_SINGLE}
/// <summary><c>Typedef for an Unbound Parameterless Callback method.</c></summary>
TADCallbackUnbound = procedure;
/// <summary><c>Typedef for an Object-Bound Parameterless Callback method.</c></summary>
TADCallbackOfObject = procedure of object;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c>Typedef for an Anonymous Parameterless Callback method.</c></summary>
TADCallbackAnonymous = reference to procedure;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
/// <summary><c></c></summary>
IADInterface = interface
['{FF2AF334-2A54-414B-AF23-D80EFA93715A}']
function GetInstanceGUID: TGUID;
property InstanceGUID: TGUID read GetInstanceGUID;
end;
/// <summary><c>Multiple-Read, Exclusive Write Locking for Thread-Safety.</c></summary>
IADReadWriteLock = interface(IADInterface)
['{F88991C1-0B3D-4427-9D6D-4A69C187CFAA}']
procedure AcquireRead;
procedure AcquireWrite;
{$IFNDEF ADAPT_LOCK_ALLEXCLUSIVE}
function GetLockState: TADReadWriteLockState;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
procedure ReleaseRead;
procedure ReleaseWrite;
function TryAcquireRead: Boolean;
function TryAcquireWrite: Boolean;
procedure WithRead(const ACallback: TADCallbackUnbound); overload;
procedure WithRead(const ACallback: TADCallbackOfObject); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure WithRead(const ACallback: TADCallbackAnonymous); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
procedure WithWrite(const ACallback: TADCallbackUnbound); overload;
procedure WithWrite(const ACallback: TADCallbackOfObject); overload;
{$IFDEF SUPPORTS_REFERENCETOMETHOD}
procedure WithWrite(const ACallback: TADCallbackAnonymous); overload;
{$ENDIF SUPPORTS_REFERENCETOMETHOD}
{$IFNDEF ADAPT_LOCK_ALLEXCLUSIVE}
property LockState: TADReadWriteLockState read GetLockState;
{$ENDIF ADAPT_LOCK_ALLEXCLUSIVE}
end;
/// <summary><c>A Collection that can Own Objects.</c></summary>
IADObjectOwner = interface(IADInterface)
['{5756A232-26B6-4395-9F1D-CCCC071E5701}']
// Getters
function GetOwnership: TADOwnership;
// Setters
procedure SetOwnership(const AOwnership: TADOwnership);
// Properties
property Ownership: TADOwnership read GetOwnership write SetOwnership;
end;
/// <summary><c>A Generic Object Holder that can Own the Object it Holds.</c></summary>
IADObjectHolder<T: class> = interface(IADObjectOwner)
// Getters
function GetObject: T;
// Properties
property HeldObject: T read GetObject;
end;
/// <summary><c>A Generic Value Holder.</c></summary>
IADValueHolder<T> = interface(IADInterface)
// Getters
function GetValue: T;
// Properties
property Value: T read GetValue;
end;
/// <summary><c>A simple associative Pair consisting of a Key and a Value.</c></summary>
IADKeyValuePair<TKey, TValue> = interface(IADInterface)
// Getters
function GetKey: TKey;
function GetValue: TValue;
// Setters
procedure SetValue(const AValue: TValue);
// Properties
property Key: TKey read GetKey;
property Value: TValue read GetValue write SetValue;
end;
implementation
end.
|
namespace RemObjects.SDK.CodeGen4;
{$HIDE W46}
interface
type
CPlusPlusBuilderRodlCodeGen = public class(DelphiRodlCodeGen)
protected
method _SetLegacyStrings(value: Boolean); override;
method Add_RemObjects_Inc(file: CGCodeUnit; library: RodlLibrary); empty;override;
method cpp_GenerateAsyncAncestorMethodCalls(library: RodlLibrary; entity: RodlService; service: CGTypeDefinition); override;
method cpp_GenerateAncestorMethodCalls(library: RodlLibrary; entity: RodlService; service: CGTypeDefinition; aMode: ModeKind); override;
method cpp_IUnknownSupport(library: RodlLibrary; entity: RodlService; service: CGTypeDefinition); override;
method cpp_Impl_constructor(library: RodlLibrary; entity: RodlService; service: CGTypeDefinition); override;
method cppGenerateProxyCast(aProxy: CGNewInstanceExpression; aInterface: CGNamedTypeReference):List<CGStatement>;override;
method cpp_GenerateProxyConstructors(library: RodlLibrary; entity: RodlService; service: CGTypeDefinition); override;
method cpp_generateInheritedBody(aMethod: CGMethodDefinition);
method cpp_generateDoLoginNeeded(aType: CGClassTypeDefinition);override;
method cpp_pragmalink(file: CGCodeUnit; aUnitName: String); override;
method cpp_ClassId(anExpression: CGExpression): CGExpression; override;
method cpp_Pointer(value: CGExpression): CGExpression;override;
method cpp_AddressOf(value: CGExpression): CGExpression;override;
method CapitalizeString(aValue: String):String;override;
method cpp_GenerateArrayDestructor(anArray: CGTypeDefinition); override;
method cpp_smartInit(file: CGCodeUnit); override;
method cpp_DefaultNamespace:CGExpression; override;
method cpp_GetNamespaceForUses(aUse: RodlUse):String;override;
method cpp_GlobalCondition_ns:CGConditionalDefine;override;
method cpp_GlobalCondition_ns_name: String; override;
method cpp_GetTROAsyncCallbackType: String; override;
method cpp_GetTROAsyncCallbackMethodType: String; override;
protected
property PureDelphi: Boolean read False; override;
property CanUseNameSpace: Boolean := True; override;
method Array_SetLength(anArray, aValue: CGExpression): CGExpression; override;
method Array_GetLength(anArray: CGExpression): CGExpression; override;
method RaiseError(aMessage:CGExpression; aParams:List<CGExpression>): CGExpression;override;
method ResolveDataTypeToTypeRefFullQualified(library: RodlLibrary; dataType: String; aDefaultUnitName: String; aOrigDataType: String := '';aCapitalize: Boolean := True): CGTypeReference; override;
method ResolveInterfaceTypeRef(library: RodlLibrary; dataType: String; aDefaultUnitName: String; aOrigDataType: String := ''; aCapitalize: Boolean := True): CGNamedTypeReference; override;
method InterfaceCast(aSource, aType, aDest: CGExpression): CGExpression; override;
method GenerateTypeInfoCall(library: RodlLibrary; aTypeInfo: CGTypeReference): CGExpression; override;
method cppGenerateEnumTypeInfo(file: CGCodeUnit; library: RodlLibrary; entity: RodlEnum); override;
method GlobalsConst_GenerateServerGuid(file: CGCodeUnit; library: RodlLibrary; entity: RodlService); override;
method AddMessageDirective(aMessage: String): CGStatement; override;
method Impl_GenerateDFMInclude(file: CGCodeUnit);override;
method Impl_CreateClassFactory(&library: RodlLibrary; entity: RodlService; lvar: CGExpression): List<CGStatement>;override;
method Impl_GenerateCreateService(aMethod: CGMethodDefinition;aCreator: CGNewInstanceExpression);override;
method AddDynamicArrayParameter(aMethod:CGMethodCallExpression; aDynamicArrayParam: CGExpression); override;
method GenerateCGImport(aName: String; aNamespace : String := '';aExt: String := 'hpp'):CGImport; override;
method Invk_GetDefaultServiceRoles(&method: CGMethodDefinition;roles: CGArrayLiteralExpression); override;
method Invk_CheckRoles(&method: CGMethodDefinition;roles: CGArrayLiteralExpression); override;
public
property DelphiXE2Mode: State := State.On; override;
property FPCMode: State read State.Off; override;
property CodeFirstMode: State read State.Off; override;
property GenericArrayMode: State read State.Off; override;
constructor;
end;
implementation
constructor CPlusPlusBuilderRodlCodeGen;
begin
fLegacyStrings := False;
IncludeUnitNameForOwnTypes := true;
IncludeUnitNameForOtherTypes := true;
PredefinedTypes.Add(CGPredefinedTypeKind.String,new CGNamedTypeReference("UnicodeString") &namespace(new CGNamespaceReference("System")) isClasstype(False));
CodeGenTypes.RemoveAll;
CodeGenTypes.Add("integer", ResolveStdtypes(CGPredefinedTypeReference.Int32));
CodeGenTypes.Add("datetime", new CGNamedTypeReference("TDateTime") isClasstype(False));
CodeGenTypes.Add("double", ResolveStdtypes(CGPredefinedTypeReference.Double));
CodeGenTypes.Add("currency", new CGNamedTypeReference("Currency") isClasstype(False));
CodeGenTypes.Add("widestring", new CGNamedTypeReference("UnicodeString") &namespace(new CGNamespaceReference("System")) isClasstype(False));
CodeGenTypes.Add("ansistring", new CGNamedTypeReference("String") &namespace(new CGNamespaceReference("System")) isClasstype(False));
CodeGenTypes.Add("int64", ResolveStdtypes(CGPredefinedTypeReference.Int64));
CodeGenTypes.Add("boolean", ResolveStdtypes(CGPredefinedTypeReference.Boolean));
CodeGenTypes.Add("variant", new CGNamedTypeReference("Variant") isClasstype(False));
CodeGenTypes.Add("binary", new CGNamedTypeReference("Binary") isClasstype(True));
CodeGenTypes.Add("xml", ResolveInterfaceTypeRef(nil,'IXMLNode','',''));
CodeGenTypes.Add("guid", new CGNamedTypeReference("TGuidString") isClasstype(False));
CodeGenTypes.Add("decimal", new CGNamedTypeReference("TDecimalVariant") isClasstype(False));
CodeGenTypes.Add("utf8string", new CGNamedTypeReference("String") &namespace(new CGNamespaceReference("System")) isClasstype(False));
CodeGenTypes.Add("xsdatetime", new CGNamedTypeReference("XsDateTime") isClasstype(True));
// from
// http://docwiki.embarcadero.com/RADStudio/XE8/en/Keywords,_Alphabetical_Listing_Index
// http://en.cppreference.com/w/cpp/keyword
ReservedWords.RemoveAll;
ReservedWords.Add([
"__asm", "__automated", "__cdecl", "__classid", "__classmethod", "__closure", "__declspec", "__delphirtti", "__dispid",
"__except", "__export", "__fastcall", "__finally", "__import", "__inline", "__int16", "__int32", "__int64", "__int8",
"__msfastcall", "__msreturn", "__pascal", "__property", "__published", "__rtti", "__stdcall", "__thread", "__try",
"_asm", "_Bool", "_cdecl", "_Complex", "_export", "_fastcall", "_Imaginary", "_import", "_pascal", "_stdcall", "alignas",
"alignof", "and", "and_eq", "asm", "auto", "axiom", "bitand", "bitor", "bool", "break", "case", "catch", "cdecl", "char",
"char16_t", "char32_t", "class", "compl", "concept", "concept_map", "const", "const_cast", "constexpr", "continue",
"decltype", "default", "delete", "deprecated", "do", "double", "Dynamic cast", "dynamic_cast", "else", "enum", "explicit",
"export", "extern", "false", "final", "float", "for", "friend", "goto", "if", "inline", "int", "late_check", "long",
"mutable", "namespace", "new", "noexcept", "noreturn", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "pascal",
"private", "protected", "public", "register", "reinterpret_cast", "requires", "restrict", "return", "short", "signed",
"sizeof", "static", "static_assert", "static_cast", "struct", "switch", "template", "this", "thread_local", "throw",
"true", "try", "typedef", "typeid", "typename", "typeof", "union", "unsigned", "using", "uuidof", "virtual", "void",
"volatile", "wchar_t", "while", "xor", "xor_eq"]);
end;
method CPlusPlusBuilderRodlCodeGen.Array_SetLength(anArray: CGExpression; aValue: CGExpression): CGExpression;
begin
exit new CGMethodCallExpression(anArray,"set_length",[aValue.AsCallParameter].ToList, CallSiteKind := CGCallSiteKind.Instance);
end;
method CPlusPlusBuilderRodlCodeGen.Array_GetLength(anArray: CGExpression): CGExpression;
begin
exit new CGFieldAccessExpression(anArray,"Length", CallSiteKind := CGCallSiteKind.Instance);
end;
method CPlusPlusBuilderRodlCodeGen.RaiseError(aMessage: CGExpression; aParams: List<CGExpression>): CGExpression;
begin
var lres := new CGMethodCallExpression(CapitalizeString('uROClasses').AsNamedIdentifierExpression,'RaiseError',CallSiteKind := CGCallSiteKind.Static);
if aMessage is CGNamedIdentifierExpression then begin
aMessage:= ('_'+CGNamedIdentifierExpression(aMessage).Name).AsNamedIdentifierExpression;
lres.Parameters.Add(new CGMethodCallExpression(nil, 'LoadResourceString',[new CGCallParameter(aMessage, Modifier := CGParameterModifierKind.Var)]).AsCallParameter)
end
else
lres.Parameters.Add(aMessage.AsCallParameter);
if aParams <> nil then
lres.Parameters.Add(new CGArrayLiteralExpression(aParams).AsCallParameter);
exit lres;
end;
method CPlusPlusBuilderRodlCodeGen.cpp_GenerateAncestorMethodCalls(library: RodlLibrary; entity: RodlService; service: CGTypeDefinition; aMode: ModeKind);
begin
if not assigned(entity.AncestorEntity) then exit;
if not (entity.AncestorEntity is RodlService) then exit;
var lentity := RodlService(entity.AncestorEntity);
case aMode of
ModeKind.Plain: begin
for lmem in lentity.DefaultInterface.Items do begin
{$REGION service methods}
var mem := new CGMethodDefinition(lmem.Name,
Virtuality := CGMemberVirtualityKind.Override,
Visibility := CGMemberVisibilityKind.Protected,
CallingConvention := CGCallingConventionKind.Register);
for lmemparam in lmem.Items do begin
if lmemparam.ParamFlag <> ParamFlags.Result then begin
var lparam := new CGParameterDefinition(lmemparam.Name,
ResolveDataTypeToTypeRefFullQualified(library,lmemparam.DataType, Intf_name));
if isComplex(library, lmemparam.DataType) and (lmemparam.ParamFlag = ParamFlags.In) then
lparam.Type := new CGConstantTypeReference(lparam.Type)
else
lparam.Modifier := RODLParamFlagToCodegenFlag(lmemparam.ParamFlag);
mem.Parameters.Add(lparam);
end;
end;
if assigned(lmem.Result) then mem.ReturnType := ResolveDataTypeToTypeRefFullQualified(library,lmem.Result.DataType, Intf_name);
cpp_generateInheritedBody(mem);
service.Members.Add(mem);
{$ENDREGION}
end;
end;
ModeKind.Async: begin
{$REGION Invoke_%service_method%}
for lmem in lentity.DefaultInterface.Items do begin
var lm := Intf_GenerateAsyncInvoke(library, lentity, lmem, false);
lm.Virtuality := CGMemberVirtualityKind.Override;
cpp_generateInheritedBody(lm);
service.Members.Add(lm);
end;
{$ENDREGION}
{$REGION Retrieve_%service_method%}
for lmem in lentity.DefaultInterface.Items do
if NeedsAsyncRetrieveOperationDefinition(lmem) then begin
var lm := Intf_GenerateAsyncRetrieve(library, lentity, lmem, false);
lm.Virtuality := CGMemberVirtualityKind.Override;
cpp_generateInheritedBody(lm);
service.Members.Add(lm);
end;
{$ENDREGION}
end;
ModeKind.AsyncEx: begin
{$REGION Begin%service_method%}
for lmem in lentity.DefaultInterface.Items do begin
var lm := Intf_GenerateAsyncExBegin(library, lentity, lmem, false, false);
lm.Virtuality := CGMemberVirtualityKind.Override;
cpp_generateInheritedBody(lm);
service.Members.Add(lm);
lm := Intf_GenerateAsyncExBegin(library, lentity, lmem, false, true);
lm.Virtuality := CGMemberVirtualityKind.Override;
cpp_generateInheritedBody(lm);
service.Members.Add(lm);
end;
{$ENDREGION}
{$REGION End%service_method%}
for lmem in lentity.DefaultInterface.Items do begin
var lm := Intf_GenerateAsyncExEnd(library, lentity, lmem, false);
lm.Virtuality := CGMemberVirtualityKind.Override;
cpp_generateInheritedBody(lm);
service.Members.Add(lm);
end;
{$ENDREGION}
end;
end;
cpp_GenerateAncestorMethodCalls(library, lentity, service, aMode);
end;
method CPlusPlusBuilderRodlCodeGen.cpp_IUnknownSupport(library: RodlLibrary; entity: RodlService; service: CGTypeDefinition);
begin
var lm := new CGMethodDefinition('QueryInterface',
[new CGMethodCallExpression(CGInheritedExpression.Inherited,
'cppQueryInterface',
['IID'.AsNamedIdentifierExpression.AsCallParameter,
new CGTypeCastExpression('Obj'.AsNamedIdentifierExpression, CGPointerTypeReference.VoidPointer).AsCallParameter].ToList,
CallSiteKind := CGCallSiteKind.Static).AsReturnStatement],
Parameters := [new CGParameterDefinition('IID', new CGPointerTypeReference(new CGNamedTypeReference('GUID') isClasstype(False)) &reference(true), Modifier := CGParameterModifierKind.Const),
new CGParameterDefinition('Obj', new CGPointerTypeReference(new CGPointerTypeReference(CGPredefinedTypeReference.Void)))].ToList(),
Virtuality := CGMemberVirtualityKind.Override,
Visibility := CGMemberVisibilityKind.Protected,
ReturnType := new CGNamedTypeReference('HRESULT') isClasstype(False),
CallingConvention := CGCallingConventionKind.StdCall);
service.Members.Add(lm);
lm := new CGMethodDefinition('AddRef',
[new CGMethodCallExpression(CGInheritedExpression.Inherited,
'_AddRef',
CallSiteKind := CGCallSiteKind.Static).AsReturnStatement],
Virtuality := CGMemberVirtualityKind.Override,
Visibility := CGMemberVisibilityKind.Protected,
ReturnType := new CGNamedTypeReference('ULONG') isClasstype(False),
CallingConvention := CGCallingConventionKind.StdCall);
service.Members.Add(lm);
lm := new CGMethodDefinition('Release',
[new CGMethodCallExpression(CGInheritedExpression.Inherited,
'_Release',
CallSiteKind := CGCallSiteKind.Static).AsReturnStatement],
Virtuality := CGMemberVirtualityKind.Override,
Visibility := CGMemberVisibilityKind.Protected,
ReturnType := new CGNamedTypeReference('ULONG') isClasstype(False),
CallingConvention := CGCallingConventionKind.StdCall);
service.Members.Add(lm);
end;
method CPlusPlusBuilderRodlCodeGen.cpp_Impl_constructor(library: RodlLibrary; entity: RodlService; service: CGTypeDefinition);
begin
var ctor := new CGConstructorDefinition(Visibility := CGMemberVisibilityKind.Public,
CallingConvention := CGCallingConventionKind.Register);
if isDFMNeeded then
ctor.Parameters.Add(new CGParameterDefinition('aOwner', new CGNamedTypeReference('Classes::TComponent')));
service.Members.Add(ctor);
end;
method CPlusPlusBuilderRodlCodeGen.ResolveInterfaceTypeRef(library: RodlLibrary; dataType: String; aDefaultUnitName: String; aOrigDataType: String; aCapitalize: Boolean): CGNamedTypeReference;
begin
var lLower := dataType.ToLowerInvariant();
if CodeGenTypes.ContainsKey(lLower) then
exit CGNamedTypeReference(CodeGenTypes[lLower]) // hack, only possibly type is IXMLNode
else begin
if assigned(library) then begin
var namesp := ResolveNamespace(library,dataType,aDefaultUnitName,aOrigDataType);
if String.IsNullOrEmpty(namesp) then
exit new CGNamedTypeReference('_di_'+dataType) isClassType(false)
else
exit new CGNamedTypeReference('_di_'+dataType)
&namespace(new CGNamespaceReference(namesp))
isClassType(false);
end
else begin
if String.IsNullOrEmpty(aDefaultUnitName) then
exit new CGNamedTypeReference('_di_'+dataType) isClassType(false)
else begin
var lns := iif(aCapitalize and (aDefaultUnitName <> targetNamespace) ,CapitalizeString(aDefaultUnitName), aDefaultUnitName);
exit new CGNamedTypeReference('_di_'+dataType)
&namespace(new CGNamespaceReference(lns))
isClassType(false);
end;
end;
end;
end;
method CPlusPlusBuilderRodlCodeGen.InterfaceCast(aSource: CGExpression; aType: CGExpression; aDest: CGExpression): CGExpression;
begin
exit new CGMethodCallExpression(aSource,'Supports',[aDest.AsCallParameter], CallSiteKind := CGCallSiteKind.Reference);
end;
method CPlusPlusBuilderRodlCodeGen.GenerateTypeInfoCall(library: RodlLibrary; aTypeInfo: CGTypeReference): CGExpression;
begin
if aTypeInfo is CGPredefinedTypeReference then begin
var l_method: String;
case CGPredefinedTypeReference(aTypeInfo).Kind of
CGPredefinedTypeKind.Int32: l_method := 'GetTypeInfo_int';
CGPredefinedTypeKind.Double: l_method := 'GetTypeInfo_double';
CGPredefinedTypeKind.Int64: l_method := 'GetTypeInfo_int64';
CGPredefinedTypeKind.Boolean:l_method := 'GetTypeInfo_bool';
else
raise new Exception(String.Format('GenerateTypeInfoCall: Unsupported predefined type: {0}',[CGPredefinedTypeReference(aTypeInfo).Kind.ToString]))
end;
exit new CGMethodCallExpression('Urotypes'.AsNamedIdentifierExpression, l_method, CallSiteKind := CGCallSiteKind.Static);
end;
if aTypeInfo is CGNamedTypeReference then begin
var l_method: String;
var l_name := CGNamedTypeReference(aTypeInfo).Name;
case l_name of
'TDateTime': l_method := 'GetTypeInfo_TDateTime';
'Currency': l_method := 'GetTypeInfo_Currency';
'UnicodeString': l_method := 'GetTypeInfo_UnicodeString';
'AnsiString': l_method := 'GetTypeInfo_AnsiString';
'Variant': l_method := 'GetTypeInfo_Variant';
'TGuidString': l_method := 'GetTypeInfo_TGuidString';
'TDecimalVariant': l_method := 'GetTypeInfo_TDecimalVariant';
'UTF8String': l_method := 'GetTypeInfo_UTF8String';
'String': l_method := 'GetTypeInfo_String';
'_di_IXMLNode': l_method := 'GetTypeInfo_Xml';
else
end;
if not String.IsNullOrEmpty(l_method) then
exit new CGMethodCallExpression('Urotypes'.AsNamedIdentifierExpression, l_method, CallSiteKind := CGCallSiteKind.Static);
if isComplex(library, l_name) then
exit new CGMethodCallExpression(nil,'__typeinfo',[l_name.AsNamedIdentifierExpression.AsCallParameter]);
if isEnum(library, l_name) then begin
var lnamespace: CGExpression := nil;
if assigned(CGNamedTypeReference(aTypeInfo).Namespace)then lnamespace := CGNamedTypeReference(aTypeInfo).Namespace.Name.AsNamedIdentifierExpression;
exit new CGMethodCallExpression(lnamespace, 'GetTypeInfo_'+l_name, CallSiteKind := CGCallSiteKind.Static);
end;
raise new Exception(String.Format('GenerateTypeInfoCall: Unsupported datatype: {0}',[l_name]));
end;
raise new Exception(String.Format('GenerateTypeInfoCall: Unsupported type reference: {0}',[aTypeInfo.ToString]));
end;
method CPlusPlusBuilderRodlCodeGen.cppGenerateEnumTypeInfo(file: CGCodeUnit; library: RodlLibrary; entity: RodlEnum);
begin
var lenum_typeref := new CGNamedTypeReference(entity.Name) isclasstype(false);
var lenum := new CGClassTypeDefinition(entity.Name+'TypeHolder','TPersistent'.AsTypeReference,
Visibility := CGTypeVisibilityKind.Public);
lenum.Members.Add(new CGConstructorDefinition(Visibility := CGMemberVisibilityKind.Public,
CallingConvention := CGCallingConventionKind.Register));
lenum.Members.Add(new CGFieldDefinition('fHolderField',lenum_typeref, Visibility := CGMemberVisibilityKind.Private));
lenum.Members.Add(new CGPropertyDefinition('HolderField',lenum_typeref,
Visibility := CGMemberVisibilityKind.Published,
GetExpression := 'fHolderField'.AsNamedIdentifierExpression,
SetExpression := 'fHolderField'.AsNamedIdentifierExpression));
file.Types.Add(lenum);
file.Globals.Add(new CGMethodDefinition('GetTypeInfo_'+entity.Name,
[new CGPointerDereferenceExpression(new CGFieldAccessExpression(
new CGMethodCallExpression(nil, 'GetPropInfo',
[new CGMethodCallExpression(nil, '__typeinfo',[lenum.Name.AsNamedIdentifierExpression.AsCallParameter]).AsCallParameter,
'HolderField'.AsLiteralExpression.AsCallParameter]),
'PropType',
CallSiteKind := CGCallSiteKind.Reference
)).AsReturnStatement],
ReturnType := ResolveDataTypeToTypeRefFullQualified(nil,'PTypeInfo',''),
CallingConvention := CGCallingConventionKind.Register,
Visibility := CGMemberVisibilityKind.Public
).AsGlobal);
end;
method CPlusPlusBuilderRodlCodeGen.GlobalsConst_GenerateServerGuid(file: CGCodeUnit; library: RodlLibrary; entity: RodlService);
begin
var lname := entity.Name;
file.Globals.Add(new CGFieldDefinition(String.Format("I{0}_IID",[lname]),
new CGNamedTypeReference('GUID') isClasstype(false),
Constant := true,
Visibility := CGMemberVisibilityKind.Public,
Initializer := new CGMethodCallExpression(
'Sysutils'.AsNamedIdentifierExpression,
'StringToGUID',
[('{'+String(entity.DefaultInterface.EntityID.ToString).ToUpperInvariant+'}').AsLiteralExpression.AsCallParameter],
CallSiteKind := CGCallSiteKind.Static)
).AsGlobal);
end;
method CPlusPlusBuilderRodlCodeGen.cppGenerateProxyCast(aProxy: CGNewInstanceExpression; aInterface: CGNamedTypeReference): List<CGStatement>;
begin
result := new List<CGStatement>;
result.Add(new CGVariableDeclarationStatement('lresult',aInterface));
result.Add(new CGVariableDeclarationStatement('lproxy',CGTypeReferenceExpression(aProxy.Type).Type,aProxy));
var lresult := new CGLocalVariableAccessExpression('lresult');
var lproxy := 'lproxy'.AsNamedIdentifierExpression;
var lQuery := new CGMethodCallExpression(lproxy, 'GetInterface',
[lresult.AsCallParameter],
CallSiteKind := CGCallSiteKind.Reference);
result.Add(new CGIfThenElseStatement( new CGUnaryOperatorExpression(lQuery,CGUnaryOperatorKind.Not),
new CGBeginEndBlockStatement(
[ GenerateDestroyExpression(lproxy),
new CGThrowExpression(new CGNewInstanceExpression('EIntfCastError'.AsNamedIdentifierExpression,
[String.Format('{0} interface not supported',[aInterface.Name]).AsLiteralExpression.AsCallParameter]))
]),
lresult.AsReturnStatement));
// _di_INewService result;
// TNewService_Proxy* proxy = new TNewService_Proxy(aMessage, aTransportChannel);
// if (proxy->QueryInterface(INewService_IID, reinterpret_cast<void**>(&result)) != S_OK)
// {
// delete proxy;
// throw EIntfCastError::EIntfCastError("INewService not supported");
// }
// return result;
end;
method CPlusPlusBuilderRodlCodeGen.cpp_GenerateProxyConstructors(library: RodlLibrary; entity: RodlService; service: CGTypeDefinition);
begin
{$REGION public class function Create(const aMessage: IROMessage; aTransportChannel: IROTransportChannel): I%service%; overload;}
var lmember_ct:= new CGConstructorDefinition(Overloaded := true,
Visibility := CGMemberVisibilityKind.Public,
Virtuality := CGMemberVirtualityKind.Virtual,
CallingConvention := CGCallingConventionKind.Register);
lmember_ct.Parameters.Add(new CGParameterDefinition('aMessage',IROMessage_typeref, Modifier := CGParameterModifierKind.Const));
lmember_ct.Parameters.Add(new CGParameterDefinition('aTransportChannel',IROTransportChannel_typeref, Modifier := CGParameterModifierKind.Const));
service.Members.Add(lmember_ct);
{$ENDREGION}
{$REGION public class function Create(const aUri: TROUri; aDefaultNamespaces: string = ''): I%service%; overload;}
lmember_ct:= new CGConstructorDefinition(Overloaded := true,
Visibility := CGMemberVisibilityKind.Public,
Virtuality := CGMemberVirtualityKind.Virtual,
CallingConvention := CGCallingConventionKind.Register);
lmember_ct.Parameters.Add(new CGParameterDefinition('aUri', new CGConstantTypeReference('TROUri'.AsTypeReference)));
lmember_ct.Parameters.Add(new CGParameterDefinition('aDefaultNamespaces',ResolveStdtypes(CGPredefinedTypeReference.String), DefaultValue := ''.AsLiteralExpression));
service.Members.Add(lmember_ct);
{$ENDREGION}
{$REGION public class function Create(const aUrl: string; aDefaultNamespaces: string = ''): I%service%; overload;}
lmember_ct:= new CGConstructorDefinition(Overloaded := true,
Visibility := CGMemberVisibilityKind.Public,
Virtuality := CGMemberVirtualityKind.Virtual,
CallingConvention := CGCallingConventionKind.Register);
lmember_ct.Parameters.Add(new CGParameterDefinition('aUrl',ResolveStdtypes(CGPredefinedTypeReference.String), Modifier := CGParameterModifierKind.Const));
lmember_ct.Parameters.Add(new CGParameterDefinition('aDefaultNamespaces',ResolveStdtypes(CGPredefinedTypeReference.String), DefaultValue := ''.AsLiteralExpression));
service.Members.Add(lmember_ct);
{$ENDREGION}
end;
method CPlusPlusBuilderRodlCodeGen.cpp_generateInheritedBody(aMethod: CGMethodDefinition);
begin
var ls :=new CGMethodCallExpression(CGInheritedExpression.Inherited, aMethod.Name);
for p in aMethod.Parameters do
ls.Parameters.Add(p.Name.AsNamedIdentifierExpression.AsCallParameter);
if assigned(aMethod.ReturnType)then
aMethod.Statements.Add(ls.AsReturnStatement)
else
aMethod.Statements.Add(ls);
end;
method CPlusPlusBuilderRodlCodeGen.AddMessageDirective(aMessage: String): CGStatement;
begin
exit new CGRawStatement('#pragma message("'+aMessage+'")');
end;
method CPlusPlusBuilderRodlCodeGen.Impl_GenerateDFMInclude(file: CGCodeUnit);
begin
file.ImplementationDirectives.Add(new CGCompilerDirective('#pragma resource "*.dfm"'));
end;
method CPlusPlusBuilderRodlCodeGen.Impl_CreateClassFactory(&library: RodlLibrary; entity: RodlService; lvar: CGExpression): List<CGStatement>;
begin
var r := new List<CGStatement>;
var l_EntityName := entity.Name;
var l_TInvoker := 'T'+l_EntityName+'_Invoker';
var l_methodName := 'Create_'+l_EntityName;
var l_creator:= new CGNewInstanceExpression('TROClassFactory'.AsTypeReference,
[l_EntityName.AsLiteralExpression.AsCallParameter,
l_methodName.AsNamedIdentifierExpression.AsCallParameter,
cpp_ClassId(l_TInvoker.AsNamedIdentifierExpression).AsCallParameter]);
r.Add(new CGVariableDeclarationStatement('lfactory','TROClassFactory'.AsTypeReference,l_creator));
r.Add(new CGMethodCallExpression('lfactory'.AsNamedIdentifierExpression,'GetInterface',
[lvar.AsCallParameter],
CallSiteKind := CGCallSiteKind.Reference));
exit r;
//new TROClassFactory("NewService", Create_NewService, __classid(TNewService_Invoker));
end;
method CPlusPlusBuilderRodlCodeGen.Impl_GenerateCreateService(aMethod: CGMethodDefinition; aCreator: CGNewInstanceExpression);
begin
aMethod.Statements.Add(new CGVariableDeclarationStatement('lservice', CGTypeReferenceExpression(aCreator.Type).Type, aCreator));
aMethod.Statements.Add(new CGMethodCallExpression('lservice'.AsNamedIdentifierExpression,'GetInterface',
['anInstance'.AsNamedIdentifierExpression.AsCallParameter],
CallSiteKind := CGCallSiteKind.Reference));
end;
method CPlusPlusBuilderRodlCodeGen.cpp_pragmalink(file: CGCodeUnit; aUnitName: String);
begin
file.ImplementationDirectives.Add(new CGCompilerDirective('#pragma link "'+aUnitName+'"'));
end;
method CPlusPlusBuilderRodlCodeGen.AddDynamicArrayParameter(aMethod: CGMethodCallExpression; aDynamicArrayParam: CGExpression);
begin
aMethod.Parameters.Add(cpp_AddressOf(new CGArrayElementAccessExpression(aDynamicArrayParam,[new CGIntegerLiteralExpression(0)])).AsCallParameter);
aMethod.Parameters.Add(new CGFieldAccessExpression(aDynamicArrayParam,'Length', CallSiteKind := CGCallSiteKind.Instance).AsCallParameter);
end;
method CPlusPlusBuilderRodlCodeGen.ResolveDataTypeToTypeRefFullQualified(library: RodlLibrary; dataType: String; aDefaultUnitName: String; aOrigDataType: String; aCapitalize: Boolean): CGTypeReference;
begin
exit inherited ResolveDataTypeToTypeRefFullQualified(library, dataType, aDefaultUnitName, aOrigDataType, aCapitalize and (aDefaultUnitName <> targetNamespace));
end;
method CPlusPlusBuilderRodlCodeGen.GenerateCGImport(aName: String;aNamespace : String; aExt: String): CGImport;
begin
var lns := aName+'.'+aExt;
if aExt in ['h', 'hpp'] then begin
if String.IsNullOrEmpty(aNamespace) then
exit new CGImport(CapitalizeString(lns))
else
exit new CGImport(new CGNamedTypeReference(aNamespace+'.'+lns))
end
else
exit new CGImport(new CGNamespaceReference(iif(String.IsNullOrEmpty(aNamespace), '',aNamespace+'.')+lns))
end;
method CPlusPlusBuilderRodlCodeGen.Invk_GetDefaultServiceRoles(&method: CGMethodDefinition; roles: CGArrayLiteralExpression);
begin
&method.Statements.Add(new CGVariableDeclarationStatement('ltemp',new CGNamedTypeReference('TStringArray') isclasstype(false),new CGMethodCallExpression(CGInheritedExpression.Inherited,'GetDefaultServiceRoles',CallSiteKind:= CGCallSiteKind.Static)));
var ltemp := new CGLocalVariableAccessExpression('ltemp');
if roles.Elements.Count > 0 then begin
var ltemp_len := new CGFieldAccessExpression(ltemp,'Length', CallSiteKind := CGCallSiteKind.Instance);
&method.Statements.Add(new CGVariableDeclarationStatement('llen',ResolveStdtypes(CGPredefinedTypeReference.Int), ltemp_len));
&method.Statements.Add(new CGAssignmentStatement(ltemp_len, new CGBinaryOperatorExpression(ltemp_len, new CGIntegerLiteralExpression(roles.Elements.Count), CGBinaryOperatorKind.Addition)));
var llen :=new CGLocalVariableAccessExpression('llen');
for i: Integer := 0 to roles.Elements.Count-1 do begin
var lind: CGExpression := llen;
if i > 0 then lind := new CGBinaryOperatorExpression(lind, new CGIntegerLiteralExpression(i), CGBinaryOperatorKind.Addition);
&method.Statements.Add(new CGAssignmentStatement(new CGArrayElementAccessExpression(ltemp,[lind]),roles.Elements[i]));
end;
end;
&method.Statements.Add(ltemp.AsReturnStatement);
end;
method CPlusPlusBuilderRodlCodeGen.Invk_CheckRoles(&method: CGMethodDefinition; roles: CGArrayLiteralExpression);
begin
var l__Instance := '__Instance'.AsNamedIdentifierExpression;
&method.Statements.Add(new CGVariableDeclarationStatement('ltemp',new CGNamedTypeReference('TStringArray') isclasstype(false),new CGMethodCallExpression(nil, 'GetDefaultServiceRoles')));
var ltemp := new CGLocalVariableAccessExpression('ltemp');
var ltemp_len := new CGFieldAccessExpression(ltemp,'Length', CallSiteKind := CGCallSiteKind.Instance);
if roles.Elements.Count > 0 then begin
&method.Statements.Add(new CGVariableDeclarationStatement('llen',ResolveStdtypes(CGPredefinedTypeReference.Int), ltemp_len));
&method.Statements.Add(new CGAssignmentStatement(ltemp_len, new CGBinaryOperatorExpression(ltemp_len, new CGIntegerLiteralExpression(roles.Elements.Count), CGBinaryOperatorKind.Addition)));
var llen :=new CGLocalVariableAccessExpression('llen');
for i: Integer := 0 to roles.Elements.Count-1 do begin
var lind: CGExpression := llen;
if i > 0 then lind := new CGBinaryOperatorExpression(lind, new CGIntegerLiteralExpression(i), CGBinaryOperatorKind.Addition);
&method.Statements.Add(new CGAssignmentStatement(new CGArrayElementAccessExpression(ltemp,[lind]),roles.Elements[i]));
end;
end;
var zero := new CGIntegerLiteralExpression(0);
&method.Statements.Add(
new CGIfThenElseStatement(
new CGBinaryOperatorExpression(ltemp_len, zero,CGBinaryOperatorKind.GreaterThan),
new CGMethodCallExpression(nil,'CheckRoles',
[l__Instance.AsCallParameter,
new CGCallParameter( new CGArrayElementAccessExpression(ltemp,[zero]), Modifier := CGParameterModifierKind.Var),
ltemp_len.AsCallParameter ].ToList)
));
end;
method CPlusPlusBuilderRodlCodeGen.cpp_generateDoLoginNeeded(aType: CGClassTypeDefinition);
begin
//virtual void __fastcall DoLoginNeeded(Uroclientintf::_di_IROMessage aMessage, System::Sysutils::Exception* anException, bool &aRetry);
aType.Members.Add(new CGMethodDefinition('DoLoginNeeded',
[new CGMethodCallExpression(CGInheritedExpression.Inherited,'DoLoginNeeded',
['aMessage'.AsNamedIdentifierExpression.AsCallParameter,
'anException'.AsNamedIdentifierExpression.AsCallParameter,
'aRetry'.AsNamedIdentifierExpression.AsCallParameter],
CallSiteKind := CGCallSiteKind.Static).AsReturnStatement],
Parameters := [new CGParameterDefinition('aMessage', IROMessage_typeref),
new CGParameterDefinition('anException', new CGNamedTypeReference('Exception') &namespace(new CGNamespaceReference('System::Sysutils')) isclasstype(true)),
new CGParameterDefinition('aRetry', ResolveStdtypes(CGPredefinedTypeReference.Boolean), Modifier := CGParameterModifierKind.Var)].ToList,
CallingConvention := CGCallingConventionKind.Register,
Visibility := CGMemberVisibilityKind.Public,
Virtuality := CGMemberVirtualityKind.Virtual));
end;
method CPlusPlusBuilderRodlCodeGen.cpp_ClassId(anExpression: CGExpression): CGExpression;
begin
exit new CGMethodCallExpression(nil, '__classid',[anExpression.AsCallParameter])
end;
method CPlusPlusBuilderRodlCodeGen.cpp_Pointer(value: CGExpression): CGExpression;
begin
exit new CGPointerDereferenceExpression(value);
end;
method CPlusPlusBuilderRodlCodeGen.cpp_AddressOf(value: CGExpression): CGExpression;
begin
exit new CGUnaryOperatorExpression(value, CGUnaryOperatorKind.AddressOf);
end;
method CPlusPlusBuilderRodlCodeGen.cpp_GenerateAsyncAncestorMethodCalls(library: RodlLibrary; entity: RodlService; service: CGTypeDefinition);
begin
//bool __fastcall GetBusy(void);
service.Members.Add(new CGMethodDefinition('GetBusy',
[new CGMethodCallExpression(CGInheritedExpression.Inherited, 'GetBusy', CallSiteKind := CGCallSiteKind.Static).AsReturnStatement],
ReturnType := ResolveStdtypes(CGPredefinedTypeReference.Boolean),
Virtuality := CGMemberVirtualityKind.Override,
CallingConvention := CGCallingConventionKind.Register,
Visibility := CGMemberVisibilityKind.Protected));
//System::UnicodeString __fastcall GetMessageID(void);
service.Members.Add(new CGMethodDefinition('GetMessageID',
[new CGMethodCallExpression(CGInheritedExpression.Inherited, 'GetMessageID',CallSiteKind := CGCallSiteKind.Static).AsReturnStatement],
ReturnType := ResolveStdtypes(CGPredefinedTypeReference.String),
Virtuality := CGMemberVirtualityKind.Override,
CallingConvention := CGCallingConventionKind.Register,
Visibility := CGMemberVisibilityKind.Protected));
// void __fastcall SetMessageID(System::UnicodeString aMessageID);
service.Members.Add(new CGMethodDefinition('SetMessageID',
[new CGMethodCallExpression(CGInheritedExpression.Inherited, 'SetMessageID',
['aMessageID'.AsNamedIdentifierExpression.AsCallParameter],
CallSiteKind := CGCallSiteKind.Static)],
Parameters := [new CGParameterDefinition('aMessageID',ResolveStdtypes(CGPredefinedTypeReference.String))].ToList,
Virtuality := CGMemberVirtualityKind.Override,
CallingConvention := CGCallingConventionKind.Register,
Visibility := CGMemberVisibilityKind.Protected));
// System::Syncobjs::TEvent* __fastcall GetAnswerReceivedEvent(void);
service.Members.Add(new CGMethodDefinition('GetAnswerReceivedEvent',
[new CGMethodCallExpression(CGInheritedExpression.Inherited, 'GetAnswerReceivedEvent',CallSiteKind := CGCallSiteKind.Static).AsReturnStatement],
ReturnType := new CGNamedTypeReference('TEvent') &namespace(new CGNamespaceReference('System::Syncobjs')) isClasstype(true),
Virtuality := CGMemberVirtualityKind.Override,
CallingConvention := CGCallingConventionKind.Register,
Visibility := CGMemberVisibilityKind.Protected));
//bool __fastcall GetAnswerReceived(void);
service.Members.Add(new CGMethodDefinition('GetAnswerReceived',
[new CGMethodCallExpression(CGInheritedExpression.Inherited, 'GetAnswerReceived', CallSiteKind := CGCallSiteKind.Static).AsReturnStatement],
ReturnType := ResolveStdtypes(CGPredefinedTypeReference.Boolean),
Virtuality := CGMemberVirtualityKind.Override,
CallingConvention := CGCallingConventionKind.Register,
Visibility := CGMemberVisibilityKind.Protected));
end;
method CPlusPlusBuilderRodlCodeGen.CapitalizeString(aValue: String): String;
begin
if String.IsNullOrEmpty(aValue) then
exit aValue
else
exit aValue.Substring(0,1).ToUpperInvariant+aValue.Substring(1).ToLowerInvariant
end;
method CPlusPlusBuilderRodlCodeGen.cpp_GenerateArrayDestructor(anArray: CGTypeDefinition);
begin
anArray.Members.Add(new CGDestructorDefinition('',
[new CGMethodCallExpression(CGSelfExpression.Self,'Clear',CallSiteKind:= CGCallSiteKind.Reference)],
Virtuality := CGMemberVirtualityKind.Virtual,
Visibility := CGMemberVisibilityKind.Public,
CallingConvention := CGCallingConventionKind.Register));
end;
method CPlusPlusBuilderRodlCodeGen.cpp_smartInit(file: CGCodeUnit);
begin
file.ImplementationDirectives.Add(new CGCompilerDirective('#pragma package(smart_init)'));
end;
method CPlusPlusBuilderRodlCodeGen._SetLegacyStrings(value: Boolean);
begin
if fLegacyStrings <> value then begin
fLegacyStrings := value;
if fLegacyStrings then begin
CodeGenTypes.Item["ansistring"] := new CGNamedTypeReference("AnsiString") &namespace(new CGNamespaceReference("System")) isClasstype(False);
CodeGenTypes.Item["utf8string"] := new CGNamedTypeReference("UTF8String") isClasstype(False);
end
else begin
CodeGenTypes.Item["ansistring"] := new CGNamedTypeReference("String") &namespace(new CGNamespaceReference("System")) isClasstype(False);
CodeGenTypes.Item["utf8string"] := new CGNamedTypeReference("String") &namespace(new CGNamespaceReference("System")) isClasstype(False);
end;
end;
end;
method CPlusPlusBuilderRodlCodeGen.cpp_DefaultNamespace:CGExpression;
begin
exit new CGFieldAccessExpression(targetNamespace.AsNamedIdentifierExpression, 'DefaultNamespace', CallSiteKind := CGCallSiteKind.Static);
end;
method CPlusPlusBuilderRodlCodeGen.cpp_GetNamespaceForUses(aUse: RodlUse): String;
begin
if not String.IsNullOrEmpty(aUse.Includes:DelphiModule) then
exit aUse.Includes:DelphiModule + '_Intf' // std RODL like DA, DA_simple => delphi mode
else if not String.IsNullOrEmpty(aUse.Namespace) then
exit aUse.Namespace
else
exit aUse.Name;
end;
method CPlusPlusBuilderRodlCodeGen.cpp_GlobalCondition_ns: CGConditionalDefine;
begin
exit new CGConditionalDefine(cpp_GlobalCondition_ns_name) inverted(true);
end;
method CPlusPlusBuilderRodlCodeGen.cpp_GlobalCondition_ns_name: String;
begin
exit targetNamespace+'_define';
end;
method CPlusPlusBuilderRodlCodeGen.cpp_GetTROAsyncCallbackType: String;
begin
result := '_di_'+inherited cpp_GetTROAsyncCallbackType;
end;
method CPlusPlusBuilderRodlCodeGen.cpp_GetTROAsyncCallbackMethodType: String;
begin
result := inherited cpp_GetTROAsyncCallbackMethodType;
end;
end. |
unit Model.Order;
interface
uses
Model.OrderItem, System.Generics.Collections, iORM.Attributes, Model.Customer;
type
[ioEntity('Orders')]
TOrder = class
private
FID: Integer;
FCustomer: TCustomer;
FNote: String;
FOrderItems: TObjectList<TOrderItem>;
function GetGrandTotal: Currency;
function GetListViewDetail: String;
function GetListViewText: String;
public
constructor Create;
destructor Destroy; override;
property ID: Integer read FID write FID;
property Note: String read FNote write FNote;
[ioBelongsTo(TCustomer)]
property Customer: TCustomer read FCustomer write FCustomer;
[ioHasMany(TOrderItem, 'OrderID')]
property OrderItems: TObjectList<TOrderItem> read FOrderItems write FOrderItems;
[ioSkip]
property GrandTotal: Currency read GetGrandTotal;
[ioSkip]
property ListViewText: String read GetListViewText;
[ioSkip]
property ListViewDetail: String read GetListViewDetail;
end;
implementation
uses
System.SysUtils, iORM;
{ TOrder }
constructor TOrder.Create;
begin
FOrderItems := TObjectList<TOrderItem>.Create;
end;
destructor TOrder.Destroy;
begin
FOrderItems.Free;
inherited;
end;
function TOrder.GetGrandTotal: Currency;
var
LOrderItem: TOrderItem;
begin
Result := 0;
for LOrderItem in FOrderItems do
Result := Result + LOrderItem.Total;
end;
function TOrder.GetListViewDetail: String;
begin
Result := Format('%m - %s', [GrandTotal, FNote]);
end;
function TOrder.GetListViewText: String;
begin
if Assigned(FCustomer) then
Result := FCustomer.FullName
else
Result := '- - -';
end;
end.
|
(* WordCountHashProbing: Max Mitter, 2020-03-13 *)
(* ------ *)
(* A Program that counts how often a word is contained in a certain text using Hash-Probing *)
(* ========================================================================= *)
PROGRAM WordCountHashProbing;
USES WinCrt, Timer, WordReader, HashProbing;
var w: Word;
n: longint;
table: HashTable;
c: NodePtr;
BEGIN (* WordCountHashProbing *)
WriteLn('Starting Wordcounter with Hash Probing...');
OpenFile('Kafka.txt', toLower);
StartTimer;
n := 0;
ReadWord(w);
InitHashTable(table);
while w <> '' do begin
n := n + 1;
(* INSERT *)
Insert(table, w);
ReadWord(w);
end;
StopTimer;
CloseFile;
WriteLn('Ending Wordcounter with Hash Probing.');
WriteLn('Number of words read: ', n);
WriteLn('Elapsed Time: ', ElapsedTime);
c := GetHighestCount(table);
WriteLn('Most Common Word: ', c^.val, ', ', c^.count, ' times.');
END. (* WordCountHashProbing *) |
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_DetourPathQueue;
interface
uses RN_DetourNavMesh, RN_DetourNavMeshHelper, RN_DetourNavMeshQuery, RN_DetourStatus;
const DT_PATHQ_INVALID = 0;
type
TdtPathQueueRef = Cardinal;
TdtPathQueue = class
private
type
PPathQuery = ^TPathQuery;
TPathQuery = record
ref: TdtPathQueueRef;
/// Path find start and end location.
startPos, endPos: array [0..2] of Single;
startRef, endRef: TdtPolyRef;
/// Result.
path: PdtPolyRef;
npath: Integer;
/// State.
status: TdtStatus;
keepAlive: Integer;
filter: TdtQueryFilter; ///< TODO: This is potentially dangerous!
end;
const MAX_QUEUE = 8;
var
m_queue: array [0..MAX_QUEUE-1] of TPathQuery;
m_nextHandle: TdtPathQueueRef;
m_maxPathSize: Integer;
m_queueHead: Integer;
m_navquery: TdtNavMeshQuery;
procedure purge();
public
constructor Create;
destructor Destroy; override;
function init(const maxPathSize, maxSearchNodeCount: Integer; nav: TdtNavMesh): Boolean;
procedure update(const maxIters: Integer);
function request(startRef, endRef: TdtPolyRef;
const startPos, endPos: PSingle;
const filter: TdtQueryFilter): TdtPathQueueRef;
function getRequestStatus(ref: TdtPathQueueRef): TdtStatus;
function getPathResult(ref: TdtPathQueueRef; path: PdtPolyRef; pathSize: PInteger; const maxPath: Integer): TdtStatus;
function getNavQuery(): TdtNavMeshQuery; { return m_navquery; }
end;
implementation
uses RN_DetourCommon;
constructor TdtPathQueue.Create;
var i: Integer;
begin
inherited;
m_nextHandle := 1;
m_maxPathSize := 0;
m_queueHead := 0;
m_navquery := nil;
for i := 0 to MAX_QUEUE - 1 do
m_queue[i].path := nil;
end;
destructor TdtPathQueue.Destroy;
begin
purge();
inherited;
end;
procedure TdtPathQueue.purge();
var i: Integer;
begin
dtFreeNavMeshQuery(m_navquery);
m_navquery := nil;
for i := 0 to MAX_QUEUE - 1 do
begin
FreeMem(m_queue[i].path);
m_queue[i].path := nil;
end;
end;
function TdtPathQueue.init(const maxPathSize, maxSearchNodeCount: Integer; nav: TdtNavMesh): Boolean;
var i: Integer;
begin
purge();
m_navquery := dtAllocNavMeshQuery();
if (m_navquery = nil) then
Exit(false);
if (dtStatusFailed(m_navquery.init(nav, maxSearchNodeCount))) then
Exit(false);
m_maxPathSize := maxPathSize;
for i := 0 to MAX_QUEUE - 1 do
begin
m_queue[i].ref := DT_PATHQ_INVALID;
GetMem(m_queue[i].path, sizeof(TdtPolyRef)*m_maxPathSize);
if (m_queue[i].path = nil) then
Exit(false);
end;
m_queueHead := 0;
Result := true;
end;
procedure TdtPathQueue.update(const maxIters: Integer);
const MAX_KEEP_ALIVE = 2; // in update ticks.
var iterCount, i, iters: Integer; q: PPathQuery;
begin
// Update path request until there is nothing to update
// or upto maxIters pathfinder iterations has been consumed.
iterCount := maxIters;
for i := 0 to MAX_QUEUE - 1 do
begin
q := @m_queue[m_queueHead mod MAX_QUEUE];
// Skip inactive requests.
if (q.ref = DT_PATHQ_INVALID) then
begin
Inc(m_queueHead);
continue;
end;
// Handle completed request.
if (dtStatusSucceed(q.status) or dtStatusFailed(q.status)) then
begin
// If the path result has not been read in few frames, free the slot.
Inc(q.keepAlive);
if (q.keepAlive > MAX_KEEP_ALIVE) then
begin
q.ref := DT_PATHQ_INVALID;
q.status := 0;
end;
Inc(m_queueHead);
continue;
end;
// Handle query start.
if (q.status = 0) then
begin
q.status := m_navquery.initSlicedFindPath(q.startRef, q.endRef, @q.startPos[0], @q.endPos[0], q.filter);
end;
// Handle query in progress.
if (dtStatusInProgress(q.status)) then
begin
iters := 0;
q.status := m_navquery.updateSlicedFindPath(iterCount, @iters);
Dec(iterCount, iters);
end;
if (dtStatusSucceed(q.status)) then
begin
q.status := m_navquery.finalizeSlicedFindPath(q.path, @q.npath, m_maxPathSize);
end;
if (iterCount <= 0) then
break;
Inc(m_queueHead);
end;
end;
function TdtPathQueue.request(startRef, endRef: TdtPolyRef;
const startPos, endPos: PSingle;
const filter: TdtQueryFilter): TdtPathQueueRef;
var slot, i: Integer; ref: TdtPathQueueRef; q: PPathQuery;
begin
// Find empty slot
slot := -1;
for i := 0 to MAX_QUEUE - 1 do
begin
if (m_queue[i].ref = DT_PATHQ_INVALID) then
begin
slot := i;
break;
end;
end;
// Could not find slot.
if (slot = -1) then
Exit(DT_PATHQ_INVALID);
ref := m_nextHandle;
Inc(m_nextHandle);
if (m_nextHandle = DT_PATHQ_INVALID) then Inc(m_nextHandle);
q := @m_queue[slot];
q.ref := ref;
dtVcopy(@q.startPos[0], startPos);
q.startRef := startRef;
dtVcopy(@q.endPos[0], endPos);
q.endRef := endRef;
q.status := 0;
q.npath := 0;
q.filter := filter;
q.keepAlive := 0;
Result := ref;
end;
function TdtPathQueue.getRequestStatus(ref: TdtPathQueueRef): TdtStatus;
var i: Integer;
begin
for i := 0 to MAX_QUEUE - 1 do
begin
if (m_queue[i].ref = ref) then
Exit(m_queue[i].status);
end;
Result := DT_FAILURE;
end;
function TdtPathQueue.getPathResult(ref: TdtPathQueueRef; path: PdtPolyRef; pathSize: PInteger; const maxPath: Integer): TdtStatus;
var i, n: Integer; q: PPathQuery; details: TdtStatus;
begin
for i := 0 to MAX_QUEUE - 1 do
begin
if (m_queue[i].ref = ref) then
begin
q := @m_queue[i];
details := q.status and DT_STATUS_DETAIL_MASK;
// Free request for reuse.
q.ref := DT_PATHQ_INVALID;
q.status := 0;
// Copy path
n := dtMin(q.npath, maxPath);
Move(q.path^, path^, sizeof(TdtPolyRef)*n);
pathSize^ := n;
Exit(details or DT_SUCCESS);
end;
end;
Result := DT_FAILURE;
end;
function TdtPathQueue.getNavQuery(): TdtNavMeshQuery; begin Result := m_navquery; end;
end. |
unit fpeStrConsts;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
interface
uses
Classes, SysUtils;
resourcestring
// *** Error messages ***
rsCannotSaveToUnknownFileFormat = 'The metadata structure cannot be saved because '+
'the file format of the receiving file is not known or not supported.';
rsFileNotFoundError = 'File "%s" not found.';
rsImageDataFileNotExisting = 'File "%s" providing the image data does not exist.';
rsImageDataFileNotSpecified = 'The metadata structure is not linked to an image. '+
'Specify the name of the file providing the image data.';
rsImageFormatNotSupported = 'Image format not supported.';
rsImageResourceNameTooLong = 'Image resource name "%s" too long.';
rsIncompleteJpegSegmentHeader = 'Defective JPEG structure: Incomplete segment header';
rsIncorrectFileStructure = 'Incorrect file structure';
rsIncorrectTagType = 'Incorrect tag type %d: Index=%d, TagID=$%.04x, File:"%s"';
rsIptcDataExpected = 'IPTC data expected, but not found.';
rsIptcExtendedDataSizeNotSupported = 'Data size %d not supported for an IPTC extended dataset.';
rsJpegCompressedDataWriting = 'Writing error of compressed data.';
rsJpegSegmentMarkerExpected = 'Defective JPEG structure: Segment marker ($FF) expected.';
rsJpegReadWriteErrorInSegment = 'Read/write error in segment $FF%.2x';
rsMoreThumbnailTagsThanExpected = 'More thumbnail tags than expected.';
rsNoValidIptcFile = 'No valid IPTC file';
rsNoValidIptcSignature = 'No valid IPTC signature';
rsRangeCheckError = 'Range check error.';
rsReadIncompleteIFDRecord = 'Read incomplete IFD record at stream position %d.';
rsTagTypeNotSupported = 'Tag "%s" has an unsupported type.';
rsUnknownImageFormat = 'Unknown image format.';
rsWritingNotImplemented = 'Writing of %s files not yet implemented.';
// general lookup values
rsAutoManual = '0:Auto,1:Manual';
rsEconomyNormalFine = '0:Economy,1:Normal,2:Fine';
rsEconomyNormalFine1 = '1:Economy,2:Normal,3:Fine';
rsLowNormalHigh = '0:Low,1:Normal,2:High';
rsNormalLowHigh = '0:Normal,1:Low,2:High';
rsNormalSoftHard = '0:Normal,1:Soft,2:Hard';
rsNoYes = '0:No,1:Yes';
rsOffOn = '0:Off,1:On';
rsSingleContinuous = '0:Single,1:Continuous';
// *** EXIF tags ***
rsAcceleration = 'Acceleration';
// rsActionAdvised = 'Action advised';
rsAperturevalue = 'Aperture value';
rsArtist = 'Artist';
rsBitsPerSample = 'Bits per sample';
rsBrightnessValue = 'Brightness value';
// rsByLine = 'By-line';
// rsByLineTitle = 'By-line title';
rsCameraElevationAngle = 'Camera elevation angle';
// rsCategory = 'Category';
rsCellHeight = 'Cell height';
rsCellWidth = 'Cell width';
rsCFAPattern = 'CFA pattern';
// rsCity = 'City';
// rsCodedCharacterSet = 'Coded character set';
rsColorSpace = 'Color space';
rsColorSpaceLkup = '0:sBW,1:sRGB,2:Adobe RGB,65533:Wide Gamut RGB,65534:ICC Profile,65535:Uncalibrated';
rsComponentsConfig = 'Components configuration';
rsCompressedBitsPerPixel = 'Compressed bits per pixel';
rsCompression = 'Compression';
rsCompressionLkup = '1:Uncompressed,2:CCITT 1D,3:T4/Group 3 Fax,'+
'4:T6/Group 4 Fax,5:LZW,6:JPEG (old-style),7:JPEG,8:Adobe Deflate,'+
'9:JBIG B&W,10:JBIG Color,99:JPEG,262:Kodak 262,32766:Next,'+
'32767:Sony ARW Compressed,32769:Packed RAW,32770:Samsung SRW Compressed,'+
'32771:CCIRLEW,32772:Samsung SRW Compressed 2,32773:PackBits,'+
'32809:Thunderscan,32867:Kodak KDC Compressed,32895:IT8CTPAD,'+
'32896:IT8LW,32897:IT8MP,32898:IT8BL,32908:PixarFilm,32909:PixarLog,'+
'32946:Deflate,32947:DCS,34661:JBIG,34676:SGILog,34677:SGILog24,'+
'34712:JPEG 2000,34713:Nikon NEF Compressed,34715:JBIG2 TIFF FX,'+
'34718:Microsoft Document Imaging (MDI) Binary Level Codec,'+
'34719:Microsoft Document Imaging (MDI) Progressive Transform Codec,'+
'34720:Microsoft Document Imaging (MDI) Vector,34892:Lossy JPEG,'+
'65000:Kodak DCR Compressed,65535:Pentax PEF Compressed';
// rsContact = 'Contact';
// rsContentLocCode = 'Content location code';
// rsContentLocName = 'Content location name';
rsContrast = 'Contrast';
rsCopyright = 'Copyright';
rsCustomRendered = 'Custom rendered';
rsCustomRenderedLkup = '0:Normal,1:Custom';
// rsDateCreated = 'Date created';
rsDateTime = 'Date/time';
rsDateTimeOriginal = 'Date/time original';
rsDateTimeDigitized = 'Date/time digitized';
rsDeviceSettingDescription = 'Device setting description';
rsDigitalZoom = 'Digital zoom';
rsDigitalZoomRatio = 'Digital zoom ratio';
rsDigitizeDate = 'Digital creation date';
rsDigitizeTime = 'Digital creation time';
rsDocumentName = 'Document name';
// rsEditorialUpdate = 'Editorial update';
// rsEditStatus = 'Edit status';
rsExifImageHeight = 'EXIF image height';
rsExifImageWidth = 'EXIF image width';
rsExifOffset = 'EXIF offset';
rsExifVersion = 'EXIF version';
// rsExpireDate = 'Expiration date';
// rsExpireTime = 'Expiration time';
rsExposureBiasValue = 'Exposure bias value';
rsExposureIndex = 'Exposure index';
rsExposureMode = 'Exposure mode';
rsExposureModeLkup = '0:Auto,1:Manual,2:Auto bracket';
rsExposureProgram = 'Exposure program';
rsExposureProgramLkup = '0:Not defined,1:Manual,2:Program AE,3:Aperture-priority AE,'+
'4:Shutter speed priority AE,5:Creative (slow speed),6:Action (high speed),'+
'7:Portrait,8:Landscape;9:Bulb';
rsExposureTime = 'Exposure time';
rsExtensibleMetadataPlatform = 'Extensible metadata platform';
rsFileSource = 'File source';
rsFileSourceLkup = '0:Unknown,1:Film scanner,2:Reflection print scanner,3:Digital camera';
rsFillOrder = 'Fill order';
rsFillOrderLkup = '1:Normal,2:Reversed';
// rsFixtureID = 'Fixture ID';
rsFlash = 'Flash';
rsFlashEnergy = 'Flash energy';
rsFlashLkup = '0:No flash,1:Fired,5:Fired; return not detected,'+
'7:Fired; return detected,8:On; did not fire,9:On; fired,'+
'13:On; return not detected,15:On; return detected,16:Off; did not fire,'+
'20:Off; did not fire, return not detected,24:Auto; did not fire,'+
'25:Auto; fired;29:Auto; fired; return not detected,31:Auto; fired; return detected,'+
'32:No flash function,48:Off, no flash function,65:Fired; red-eye reduction,'+
'69:Fired; red-eye reduction; return not detected,'+
'71:Fired; red-eye reduction; return detected,73:On; red-eye reduction,'+
'77:On; red-eye reduction, return not detected,'+
'79:On, red-eye reduction, return detected,80:Off; red-eye reduction,'+
'88:Auto; did not fire; red-eye reduction,89:Auto; fired; red-eye reduction,'+
'93:Auto; fired; red-eye reduction; return not detected,'+
'95:Auto; fired; red-eye reduction, return detected';
rsFlashPixVersion = 'FlashPix version';
rsFNumber = 'F number';
rsFocalLength = 'Focal length';
rsFocalLengthIn35mm = 'Focal length in 35 mm film';
rsFocalPlaneResUnit = 'Focal plane resolution unit';
rsFocalPlaneResUnitLkup = '1:None,2:inches,3:cm,4:mm,5:um';
rsFocalPlaneXRes = 'Focal plane x resolution';
rsFocalPlaneYRes = 'Focal plane y resolution';
rsGainControl = 'Gain control';
rsGainControlLkup = '0:None,1:Low gain up,2:High gain up,3:Low gain down,4:High gain down';
rsGamma = 'Gamma';
rsGPSAltitude = 'GPS altitude';
rsGPSAltitudeRef = 'GPS altitude reference';
rsGPSAltitudeRefLkup = '0: Above sea level,1:Below sea level';
rsGPSAreaInformation = 'Area information';
rsGPSDateDifferential = 'GPS date differential';
rsGPSDateDifferentialLkup = '0:No correction,1:Differential corrected';
rsGPSDateStamp = 'GPS date stamp';
rsGPSDestBearing = 'GPS destination bearing';
rsGPSDestBearingRef = 'GPS destination bearing reference';
rsGPSDestDistance = 'GPS destination distance';
rsGPSDestDistanceRef = 'GPS destination distance reference';
rsGPSDestLatitude = 'GPS destination latitude';
rsGPSDestLatitudeRef = 'GPS destination latitude reference';
rsGPSDestLongitude = 'GPS destination longitude';
rsGPSDestLongitudeRef = 'GPS destination longitude reference';
rsGPSDistanceRefLkup = 'K:Kilometers,M:Miles,N:Nautical miles';
rsGPSDOP = 'GPS DOP';
rsGPSHPositioningError = 'GPS H positioning error';
rsGPSImageDirection = 'GPS image direction';
rsGPSImageDirectionRef = 'GPS image direction reference';
rsGPSInfo = 'GPS info';
rsGPSLatitude = 'GPS latitude';
rsGPSLatitudeRef = 'GPS latitude reference';
rsGPSLatitudeRefLkup = 'N:North,S:South';
rsGPSLongitude = 'GPS longitude';
rsGPSLongitudeRef = 'GPS longitude reference';
rsGPSLongitudeRefLkup = 'E:East,W:West';
rsGPSMapDatum = 'GPS map datum';
rsGPSMeasureMode = 'GPS measurement mode';
rsGPSMeasureModeLkup = '2:2-Dimensional Measurement,3:3-Dimensional Measurement';
rsGPSProcessingMode = 'GPS processing mode';
rsGPSSatellites = 'GPS satellites';
rsGPSSpeed = 'GPS speed';
rsGPSSpeedRef = 'GPS speed reference';
rsGPSSpeedRefLkup = 'K:km/h,M:mph,N:knots';
rsGPSStatus = 'GPS status';
rsGPSTimeStamp = 'GPS time stamp';
rsGPSTrack = 'GPS track';
rsGPSTrackRef = 'GPS track reference';
rsGPSTrackRefLkup = 'M:Magnetic north,T:True north';
rsGPSVersionID = 'GPS version ID';
rsHalftoneHints = 'Half-tone hints';
rsHostComputer = 'Host computer';
rsHumidity = 'Humidity';
// rsImageCaption = 'Image caption';
// rsImageCaptionWriter = 'Image caption writer';
// rsImageCredit = 'Image credit';
rsImageDescr = 'Image description';
// rsImageHeadline = 'Image headline';
rsImageHeight = 'Image height';
rsImageHistory = 'Image history';
rsImageNumber = 'Image number';
// rsImageType = 'Image type';
rsImageUniqueID = 'Unique image ID';
rsImageWidth = 'Image width';
rsInkSet = 'Ink set';
rsInkSetLkup = '1:CMYK,2:Not CMYK';
rsInteropIndex = 'Interoperabiliy index';
rsInteropOffset = 'Interoperability offset';
rsInteropVersion = 'Interoperability version';
rsIPTCNAA = 'IPTC/NAA';
rsISOSpeed = 'ISO speed';
rsISOSpeedLatitudeYYY = 'ISO latitude yyy';
rsISOSpeedLatitudeZZZ = 'ISO speed latitude zzz';
rsISO = 'ISO';
rsLensInfo = 'Lens info';
rsLensMake = 'Lens make';
rsLensModel = 'Lens model';
rsLensSerialNumber = 'Lens serial number';
rsLightSource = 'Light source';
rsLightSourceLkup = '0:Unknown,1:Daylight,2:Fluorescent,3:Tungsten (incandescent),'+
'4:Flash,9:Fine weather,10:Cloudy,11:Shade,12:Daylight fluorescent,'+
'13:Day white fluorescent,14:Cool white fluorescent,15:White fluorescent,'+
'16:Warm white fluorescent,17:Standard light A, 18:Standard light B,'+
'19:Standard light C,20:D55,21:D65,22:D74,23:D50,24:ISO Studio tungsten,'+
'255:Other';
rsMacro = 'Macro';
rsMake = 'Make';
rsMakerNote = 'Maker note';
rsMaxApertureValue = 'Max aperture value';
rsMaxSampleValue = 'Max sample value';
rsMeteringMode = 'Metering mode';
rsMeteringModeLkup = '0:Unknown,1:Average,2:Center-weighted average,'+
'3:Spot,4:Multi-spot,5:Multi-segment,6:Partial,255:Other';
rsMinSampleValue = 'Min sample value';
rsModel = 'Model';
rsOffsetTime = 'Time zone for date/time';
rsOffsetTimeOriginal = 'Time zone for date/time original';
rsOffsetTimeDigitized = 'Time zone for date/time digitized';
rsOrientation = 'Orientation';
rsOrientationLkup = '1:Horizontal (normal),2:Mirror horizontal,3:Rotate 180,'+
'4:Mirror vertical,5:Mirror horizontal and rotate 270 CW,6:Rotate 90 CW,'+
'7:Mirror horizontal and rotate 90 CW,8:Rotate 270 CW';
rsOwnerName = 'Owner name';
rsPageName = 'Page name';
rsPageNumber = 'Page number';
rsPhotometricInt = 'Photometric interpretation';
rsPhotometricIntLkup = '0:White is zero,1:Black is zero,2:RGB,3:RGB palette,'+
'4:Transparency mask,5:CMYK,6:YCbCr,8:CIELab,9:ICCLab,10:ITULab,'+
'32803:Color filter array,32844:Pixar LogL,32845:Pixar LogLuv,34892:Linear Raw';
rsPlanarConfiguration = 'Planar configuration';
rsPlanarConfigurationLkup = '1:Chunky,2:Planar';
rsPredictor = 'Predictor';
rsPredictorLkup = '1:None,2:Horizontal differencing';
rsPressure = 'Pressure';
rsPrimaryChromaticities = 'Primary chromaticities';
rsQuality = 'Quality';
rsRecExpIndex = 'Recommended exposure index';
rsRefBlackWhite = 'Reference black & white';
rsRelatedImageFileFormat = 'Related image file format';
rsRelatedImageHeight = 'Related image height';
rsRelatedImageWidth = 'Related image width';
rsRelatedSoundFile = 'Related sound file';
rsResolutionUnit = 'Resolution unit';
rsResolutionUnitLkup = '1:None,2:inches,3:cm';
rsRowsPerStrip = 'Rows per strip';
rsSamplesPerPixel = 'Samples per pixel';
rsSaturation = 'Saturation';
rsSceneCaptureType = 'Scene capture type';
rsSceneCaptureTypeLkup = '0:Standard,1:Landscape,2:Portrait,3:Night';
rsSceneType = 'Scene type';
rsSceneTypeLkup = '0:Unknown,1:Directly photographed';
rsSecurityClassification = 'Security classification';
rsSelfTimerMode = 'Self-timer mode';
rsSEMInfo = 'SEM info';
rsSensingMethod = 'Sensing method';
rsSensingMethodLkup = '1:Not defined,2:One-chip color area,3:Two-chip color area,'+
'4:Three-chip color area,5:Color sequential area,7:Trilinear,8:Color sequential linear';
rsSensitivityType = 'Sensitivity type';
rsSensitivityTypeLkup = '0:Unknown,1:Standard Output Sensitivity'+
'2:Recommended exposure index,3:ISO speed,'+
'4:Standard output sensitivity and recommended exposure index,'+
'5:Standard output sensitivity and ISO Speed,6:Recommended exposure index and ISO speed,'+
'7:Standard output sensitivity, recommended exposure index and ISO speed';
rsSerialNumber = 'Serial number';
rsSharpness = 'Sharpness';
rsShutterSpeedValue = 'Shutter speed value';
rsSoftware = 'Software';
rsSpatialFrequResponse = 'Spatial frequency response';
rsSpectralSensitivity = 'Spectral sensitivity';
rsStdOutputSens = 'Standard output sensitivity';
rsStripByteCounts = 'Strip byte counts';
rsStripOffsets = 'Strip offsets';
rsSubfileTypeLkup =
'0:Full-resolution image,'+
'1:Reduced-resolution image,'+
'2:Single page of multi-page image,'+
'3:Single page of multi-page reduced-resolution image,'+
'4:Transparency mask,'+
'5:Transparency mask of reduced-resolution image,'+
'6:Transparency mask of multi-page image,'+
'7:Transparency mask of reduced-resolution multi-page image';
rsSubjectArea = 'Subject area';
rsSubjectDistance = 'Subject distance';
rsSubjectDistanceRange = 'Subject distance range';
rsSubjectDistanceRangeLkup = '0:Unknown,1:Macro,2:Close,3:Distant';
rsSubjectLocation = 'Subject location';
rsSubSecTime = 'Fractional seconds of date/time';
rsSubSecTimeOriginal = 'Fractional seconds of date/time original';
rsSubSecTimeDigitized = 'Fractional seconds of date/time digitized';
rsTargetPrinter = 'Target printer';
rsTemperature = 'Temperature';
rsThresholding = 'Thresholding';
rsThresholdingLkup = '1:No dithering or halftoning,2:Ordered dither or halftone,'+
'3:Randomized dither';
rsThumbnailHeight = 'Thumbnail height';
rsThumbnailOffset = 'Thumbnail offset';
rsThumbnailSize = 'Thumbnail size';
rsThumbnailWidth = 'Thumbnail width';
rsTileLength = 'Tile length';
rsTileWidth = 'Tile width';
rsTimeZoneOffset = 'Time zone offset';
rsTransferFunction = 'Transfer function';
rsTransmissionRef = 'Original transmission reference';
rsUserComment = 'User comment';
rsWhiteBalance = 'White balance';
rsWaterDepth = 'Water depth';
rsWhitePoint = 'White point';
rsXPosition = 'X position';
rsXResolution = 'X resolution';
rsYCbCrCoefficients = 'YCbCr coefficients';
rsYCbCrPositioning = 'YCbCr positioning';
rsYCbCrPosLkup = '1:Centered,2:Co-sited';
rsYCbCrSubsampling = 'YCbCr subsampling';
rsYPosition = 'Y position';
rsYResolution = 'Y resolution';
// *** IPTC tags ***
rsActionAdvised = 'Action advised';
rsByLine = 'ByLine';
rsByLineTitle = 'ByLine title';
rsCategory = 'Category';
rsCity = 'City';
rsCodedCharSet = 'Coded character set';
rsContact = 'Contact';
// rsCopyright = 'Copyright notice';
rsContentLocCode = 'Content location code';
rsContentLocName = 'Content location name';
rsDateCreated = 'Date created';
// rsDigitizeDate = 'Digital creation date';
// rsDigitizeTime = 'Digital creation time';
rsEditorialUpdate = 'Editorial update';
rsEditStatus = 'Edit status';
rsExpireDate = 'Expiration date';
rsExpireTime = 'Expiration time';
rsFixtureID = 'Fixture ID';
rsImgCaption = 'Image caption';
rsImgCaptionWriter = 'Image caption writer';
rsImgCredit = 'Image credit';
rsImgHeadline = 'Image headline';
rsImgType = 'Image type';
rsIptcOrientationLkup = 'P:Portrait,L:Landscape,S:Square';
rsKeywords = 'Keywords';
rsLangID = 'Language ID';
rsLocationCode = 'Country/primary location code';
rsLocationName = 'Country/primary location name';
rsObjectAttr = 'Object attribute reference';
rsObjectCycle = 'Object cycle';
rsObjectCycleLkup = 'a:morning,p:evening,b:both';
rsObjectName = 'Object name';
rsObjectType = 'Object type reference';
// rsOrientation = 'Image orientation';
rsOriginatingProg = 'Originating program';
rsProgVersion = 'Program version';
rsRecordVersion = 'Record version';
rsRefDate = 'Reference date';
rsRefNumber = 'Reference number';
rsRefService = 'Reference service';
rsReleaseDate = 'Release date';
rsReleaseTime = 'Release time';
rsSource = 'Source';
rsSpecialInstruct = 'Special instructions';
rsState = 'Province/State';
rsSubjectRef = 'Subject reference';
rsSubfile = 'Subfile';
rsSubLocation = 'Sublocation';
rsSuppCategory = 'Supplemental category';
rsTimeCreated = 'Time created';
rsUrgency = 'Urgency';
rsUrgencyLkup = '0:reserved,1:most urgent,5:normal,8:least urgent,9:reserved';
implementation
end.
|
type
TExtractInfo = record
Status: (eisERROR, eisOK, eisSKIP);
MD5: String;
LocalFileName: String;
SourceLine: String;
end;
///// <summary>
///// Извлечь информацию о файле, из файла с контрольными суммами
///// </summary>
//procedure ExtractHashInfo(const SourceLine: String; out EInfo: TExtractInfo);
//var
// Index: Integer;
// Ch: Char;
// S: String;
//begin
// S := SourceLine.Trim;
// //
// EInfo.SourceLine := S;
// EInfo.Status := eisERROR;
// EInfo.MD5 := '';
// EInfo.LocalFileName := '';
// // Формат ДОЛЖЕН БЫТЬ такой:
// // A) - пустая строка - пропускаем
// // B) - строка, начинающаяся с "#" - комментарий - пропускаем
// // C) - контрольная сумма + имя файла:
// // 0) SPACES
// // 1) 16 символов 0..9, a..f, A..F
// // 2) SPACES
// // 3) * (двоичный файл) - если есть, просто пропускаем
// // 4) имя файла (возможно, в кавычках, если в конце имени файла пробелы)
//
// // Пустая строка ?
// if StringIsEmpty(S) then
// begin
// EInfo.Status := eisSKIP;
// Exit;
// end;
//
// // Строка-комментарий ?
// if S.StartsWith('#') then
// begin
// EInfo.Status := eisSKIP;
// Exit;
// end;
//
// // ВНИМАНИЕ!!
// // Если дошли до этого места, то Exit(FALSE) означает
// // ошибку в формате имени файла!!!
//{ DONE :Обработать exit(FALSE) как ошибку форматирования
//в файле с контрольными суммами = сделан возврат статуса разбора строки в .Status }
//
//{ DONE : А если в строке будут пробелы, а затем контрольная сумма?
//=в формате md5 строгий формат, никаких пробелов.
//}
// // Разделяем на контрольную сумму и имя файла
// Index := S.IndexOf(' ');
// if Index < 0 then
// begin
// EInfo.Status := eisERROR;
// Exit;
// end;
// // Готовим имя файла
// EInfo.LocalFileName := S.Substring(Index).TrimLeft;
//
// // Определяем ТИП файла
// // "*" - двоичный файл
// // " " - текстовый файл
// if EInfo.LocalFileName.StartsWith('*') then
// begin
// EInfo.LocalFileName := EInfo.LocalFileName.Substring(1);
// end;
// // Получаем путь к файлу (относительно BASE - локальный)
// EInfo.LocalFileName := EInfo.LocalFileName.DequotedString.Replace('/', '\');
// // Определяем, что за контрольная сумма используется
// // Она отделяется от имени файла так:
// // ?sha1*fielname.ext
//
// // Готовим контрольную сумму
// EInfo.MD5 := S.Substring(0, Index);
// if Length(EInfo.MD5) <> 32 then
// begin
// EInfo.Status := eisERROR;
// Exit;
// end;
// //
// for Ch in EInfo.MD5 do
// begin
// if NOT CharInSet(Ch, ['0'..'9', 'A'..'F', 'a'..'f']) then
// begin
// EInfo.Status := eisERROR;
// Exit;
// end;
// end;
// //
// EInfo.Status := eisOK;
//end;
|
{*******************************************************}
{ TeeChart PNG Graphic Format }
{ Copyright (c) 2000-2004 by David Berneda }
{ All Rights Reserved }
{ }
{ Windows systems: }
{ The LPng.DLL is required in \Windows\System folder }
{*******************************************************}
unit TeePNG;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
{$IFDEF CLX}
QComCtrls, QStdCtrls, QControls, QGraphics, QForms, Qt,
{$ELSE}
Forms, Graphics, ComCtrls, Controls, StdCtrls,
{$ENDIF}
SysUtils, Classes, TeeProcs, TeeExport, TeCanvas;
type
TPNGExportFormat=class;
TTeePNGOptions = class(TForm)
Label1: TLabel;
Edit1: TEdit;
UpDown1: TUpDown;
procedure FormCreate(Sender: TObject);
procedure Edit1Change(Sender: TObject);
private
{ Private declarations }
IFormat : TPNGExportFormat;
public
{ Public declarations }
end;
{$IFNDEF CLR}
{$IFNDEF LINUX}
TPicData = record
Stream : TMemoryStream;
APtr : Pointer;
BLineWidth,
LineWidth,
Width,
Height : Integer;
end;
{$ENDIF}
{$ENDIF}
TPNGExportFormat=class(TTeeExportFormat)
private
FCompression : Integer;
FPixel : TPixelFormat;
{$IFNDEF LINUX}
{$IFNDEF CLR}
PicData : TPicData;
RowPtrs : PByte;
SaveBuf : Array[0..8192] of Byte;
{$ENDIF}
{$ENDIF}
Procedure CheckProperties;
Procedure SetCompression(const Value:Integer);
protected
FProperties: TTeePNGOptions;
Procedure DoCopyToClipboard; override;
public
Constructor Create; override;
Function Bitmap:TBitmap;
property Compression:Integer read FCompression write SetCompression;
function Description:String; override;
function FileExtension:String; override;
function FileFilter:String; override;
Function Options(Check:Boolean=True):TForm; override;
property PixelFormat:TPixelFormat read FPixel write FPixel;
procedure SaveToStream(AStream:TStream); override;
procedure SaveToStreamCompression(AStream:TStream; CompressionLevel:Integer);
end;
Procedure TeeSaveToPNG( APanel:TCustomTeePanel;
Const AFileName: WideString;
AWidth:Integer=0;
AHeight:Integer=0);
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses {$IFDEF CLX}
QClipbrd,
{$ELSE}
Clipbrd,
{$ENDIF}
{$IFDEF TEEOCX}
SyncObjs,
{$ENDIF}
TeeConst;
Procedure TeeSaveToPNG( APanel:TCustomTeePanel;
Const AFileName: WideString;
AWidth:Integer=0;
AHeight:Integer=0);
begin
with TPNGExportFormat.Create do
try
Panel:=APanel;
if AWidth=0 then Width:=Panel.Width
else Width:=AWidth;
if AHeight=0 then Height:=Panel.Height
else Height:=AHeight;
SaveToFile(AFileName);
finally
Free;
end;
end;
Const TeePNG_DefaultCompressionLevel=9;
{$IFDEF TEEOCX}
var PNGSection : TCriticalSection;
{$ENDIF}
{$IFNDEF LINUX}
{$IFNDEF CLR}
type
TPng_Row_Info=record
width : Cardinal;
rowbytes : Cardinal;
color_type : Byte;
bit_depth : Byte;
channels : Byte;
pixel_depth : Byte;
end;
PPng_Row_Info=^TPng_Row_Info;
TPng_Color=record
red : Byte;
green : Byte;
blue : Byte;
end;
PPng_Color=^TPng_Color;
TPng_Color_16=record
index: Byte;
red: Word;
green: Word;
blue: Word;
gray: Word;
end;
PPng_Color_16=^TPng_Color_16;
PPWord = ^PWord;
TPng_Color_8=record
red: Byte;
green: Byte;
blue: Byte;
gray: Byte;
alpha: Byte;
end;
PPng_Color_8 = ^TPng_Color_8;
TPng_Struct=record
jmpbuf : Array[0..10] of Integer;
error_fn : Pointer;
warning_fn : Pointer;
error_ptr : Pointer;
write_data_fn : Pointer;
read_data_fn : Pointer;
read_user_transform_fn: Pointer;
write_user_transform_fn: Pointer;
io_ptr : Integer;
mode : Cardinal;
flags : Cardinal;
transformations : Cardinal;
zstream : Pointer;
zbuf : PByte;
zbuf_size : Integer;
zlib_level : Integer;
zlib_method : Integer;
zlib_window_bits : Integer;
zlib_mem_level : Integer;
zlib_strategy : Integer;
width : Cardinal;
height : Cardinal;
num_rows : Cardinal;
usr_width : Cardinal;
rowbytes : Cardinal;
irowbytes : Cardinal;
iwidth : Cardinal;
row_number : Cardinal;
prev_row : PByte;
row_buf : PByte;
sub_row : PByte;
up_row : PByte;
avg_row : PByte;
paeth_row : PByte;
row_info : TPng_Row_Info;
idat_size : Cardinal;
crc : Cardinal;
palette : PPng_Color;
num_palette : Word;
num_trans : Word;
chunk_name : Array[0..4] of Byte;
compression : Byte;
filter : Byte;
interlaced : Byte;
pass : Byte;
do_filter : Byte;
color_type : Byte;
bit_depth : Byte;
usr_bit_depth : Byte;
pixel_depth : Byte;
channels : Byte;
usr_channels : Byte;
sig_bytes : Byte;
filler : Byte;
background_gamma_type: Byte;
background_gamma : Single;
background : TPng_Color_16;
background_1 : TPng_Color_16;
output_flush_fn : Pointer;
flush_dist : Cardinal;
flush_rows : Cardinal;
gamma_shift : Integer;
gamma : Single;
screen_gamma : Single;
gamma_table : PByte;
gamma_from_1 : PByte;
gamma_to_1 : PByte;
gamma_16_table : PPWord;
gamma_16_from_1 : PPWord;
gamma_16_to_1 : PPWord;
sig_bit : TPng_Color_8;
shift : TPng_Color_8;
trans : PByte;
trans_values : TPng_Color_16;
read_row_fn : Pointer;
write_row_fn : Pointer;
info_fn : Pointer;
row_fn : Pointer;
end_fn : Pointer;
save_buffer_ptr : PByte;
save_buffer : PByte;
current_buffer_ptr: PByte;
current_buffer : PByte;
push_length : Cardinal;
skip_length : Cardinal;
save_buffer_size : Integer;
save_buffer_max : Integer;
buffer_size : Integer;
current_buffer_size: Integer;
process_mode : Integer;
cur_palette : Integer;
current_text_size: Integer;
current_text_left: Integer;
current_text : PByte;
current_text_ptr : PByte;
palette_lookup : PByte;
dither_index : PByte;
hist : PWord;
heuristic_method : Byte;
num_prev_filters : Byte;
prev_filters : PByte;
filter_weights : PWord;
inv_filter_weights: PWord;
filter_costs : PWord;
inv_filter_costs : PWord;
time_buffer : PByte;
end;
PPng_Struct = ^TPng_Struct;
PPPng_Struct = ^PPng_Struct;
TPng_Text = record
compression: Integer;
key: PChar;
text: PChar;
text_length: Integer;
end;
PPng_Text = ^TPng_Text;
TPng_Time = record
year: Word;
month: Byte;
day: Byte;
hour: Byte;
minute: Byte;
second: Byte;
end;
PPng_Time = ^TPng_Time;
PPChar = ^PChar;
TPng_Info = record
width: Cardinal;
height: Cardinal;
valid: Cardinal;
rowbytes: Cardinal;
palette: PPng_Color;
num_palette: Word;
num_trans: Word;
bit_depth: Byte;
color_type: Byte;
compression_type: Byte;
filter_type: Byte;
interlace_type: Byte;
channels: Byte;
pixel_depth: Byte;
spare_byte: Byte;
signature: array[0..7] of Byte;
gamma: Single;
srgb_intent: Byte;
num_text: Integer;
max_text: Integer;
text: PPng_Text;
mod_time: TPng_Time;
sig_bit: TPng_Color_8;
trans: PByte;
trans_values: TPng_Color_16;
background: TPng_Color_16;
x_offset: Cardinal;
y_offset: Cardinal;
offset_unit_type: Byte;
x_pixels_per_unit: Cardinal;
y_pixels_per_unit: Cardinal;
phys_unit_type: Byte;
hist: PWord;
x_white: Single;
y_white: Single;
x_red: Single;
y_red: Single;
x_green: Single;
y_green: Single;
x_blue: Single;
y_blue: Single;
pcal_purpose: PChar;
pcal_X0: Integer;
pcal_X1: Integer;
pcal_units: PChar;
pcal_params: PPChar;
pcal_type: Byte;
pcal_nparams: Byte;
end;
PPng_Info = ^TPng_Info;
PPPng_Info = ^PPng_Info;
PPByte = ^PByte;
png_rw_ptr = procedure(png_ptr: Pointer; var Data: Pointer; Length: Cardinal); stdcall;
png_flush_ptr = procedure(png_ptr: Pointer); stdcall;
Var png_create_write_struct: function(user_png_ver: PChar;
error_ptr, error_fn, warn_fn: Pointer): PPng_Struct; stdcall;
png_create_info_struct : function(png_ptr: PPng_Struct): PPng_Info; stdcall;
png_set_compression_level:procedure(png_ptr: Ppng_struct; Level: Integer); stdcall;
png_set_write_fn : procedure(png_ptr: PPng_Struct;
io_ptr: Pointer; write_data_fn: png_rw_ptr;
output_flush_fn: png_flush_ptr); stdcall;
png_set_write_status_fn: procedure(png_ptr: PPng_Struct;
write_row_fn: Pointer); stdcall;
png_set_IHDR : procedure(png_ptr: PPng_Struct; info_ptr: PPng_Info;
width, height: Cardinal; bit_depth, color_type, interlace_type,
compression_type, filter_type: Integer); stdcall;
png_write_info : procedure(png_ptr: PPng_Struct; info_ptr: PPng_Info); stdcall;
png_write_image : procedure(png_ptr: PPng_Struct; image: PPByte); stdcall;
png_write_end : procedure(png_ptr: PPng_Struct; info_ptr: PPng_Info); stdcall;
png_write_flush : procedure(png_ptr: PPng_Struct); stdcall;
png_destroy_write_struct : procedure(png_ptr_ptr: PPPng_Struct;
info_ptr_ptr: PPPng_Info); stdcall;
PngLib : HINST=0;
const PNG_LIBPNG_VER_STRING = '1.0.1';
PNG_COLOR_TYPE_RGB: Integer = 2;
PNG_INTERLACE_NONE: Integer = 0;
PNG_COMPRESSION_TYPE_DEFAULT: Integer = 0;
PNG_FILTER_TYPE_DEFAULT: Integer = 0;
var IStream : TStream;
procedure LoadProcs;
begin
png_create_write_struct :=GetProcAddress(PngLib,'png_create_write_struct');
png_create_info_struct :=GetProcAddress(PngLib,'png_create_info_struct');
png_set_compression_level:=GetProcAddress(PngLib,'png_set_compression_level');
png_set_write_fn :=GetProcAddress(PngLib,'png_set_write_fn');
png_set_write_status_fn :=GetProcAddress(PngLib,'png_set_write_status_fn');
png_set_IHDR :=GetProcAddress(PngLib,'png_set_IHDR');
png_write_info :=GetProcAddress(PngLib,'png_write_info');
png_write_image :=GetProcAddress(PngLib,'png_write_image');
png_write_end :=GetProcAddress(PngLib,'png_write_end');
png_write_flush :=GetProcAddress(PngLib,'png_write_flush');
png_destroy_write_struct:=GetProcAddress(PngLib,'png_destroy_write_struct');
end;
{$ENDIF}
{$ENDIF}
Constructor TPNGExportFormat.Create;
begin
inherited;
FCompression:=TeePNG_DefaultCompressionLevel;
FPixel:={$IFDEF CLX}pf32Bit{$ELSE}pfDevice{$ENDIF};
end;
function TPNGExportFormat.Description:String;
begin
result:=TeeMsg_AsPNG;
end;
function TPNGExportFormat.FileFilter:String;
begin
result:=TeeMsg_PNGFilter;
end;
function TPNGExportFormat.FileExtension:String;
begin
result:='PNG';
end;
Function TPNGExportFormat.Bitmap:TBitmap;
begin
result:=Panel.TeeCreateBitmap(Panel.Color,TeeRect(0,0,Width,Height),FPixel);
end;
procedure TPNGExportFormat.DoCopyToClipboard;
var tmp : TBitmap;
begin
tmp:=Bitmap;
try
Clipboard.Assign(tmp);
finally
tmp.Free;
end;
end;
Procedure TPNGExportFormat.CheckProperties;
begin
if not Assigned(FProperties) then
begin
FProperties:=TTeePNGOptions.Create(nil);
FProperties.IFormat:=Self;
FProperties.UpDown1.Position:=FCompression;
end;
end;
Procedure TPNGExportFormat.SetCompression(const Value:Integer);
begin
FCompression:=Value;
if Assigned(FProperties) then
FProperties.UpDown1.Position:=FCompression;
end;
Function TPNGExportFormat.Options(Check:Boolean=True):TForm;
begin
if Check then CheckProperties;
result:=FProperties;
end;
{$IFNDEF LINUX}
{$IFNDEF CLR}
Const PNGDLL='LPng.dll';
Procedure InitPngLib;
begin
PngLib:=TeeLoadLibrary(PNGDll);
if PngLib=0 then raise Exception.Create('Library '+PNGDLL+' cannot be loaded.');
end;
procedure WriteImageStream(png_ptr: Pointer; var Data: Pointer; Length: Cardinal); stdcall;
begin
IStream.WriteBuffer(Data,Length);
end;
procedure FlushImageStream(png_ptr: Pointer); stdcall;
begin
end;
procedure TPNGExportFormat.SaveToStreamCompression(AStream:TStream; CompressionLevel:Integer);
var Data : PByte;
FBytesPerPixel: Integer;
Procedure SetBitmapStream(Bitmap:TBitmap; var PicData:TPicData);
var DC : HDC;
begin
PicData.Stream.Clear;
PicData.Stream.SetSize(SizeOf(TBITMAPINFOHEADER)+ Bitmap.Height*(Bitmap.Width+4)*3);
With TBITMAPINFOHEADER(PicData.Stream.Memory^) do
Begin
biSize := SizeOf(TBITMAPINFOHEADER);
biWidth := Bitmap.Width;
biHeight := Bitmap.Height;
biPlanes := 1;
biBitCount := 24;
biCompression := bi_RGB;
biSizeImage := 0;
biXPelsPerMeter :=1;
biYPelsPerMeter :=1;
biClrUsed :=0;
biClrImportant :=0;
end;
PicData.Aptr:=Pchar(PicData.Stream.Memory)+SizeOf(TBITMAPINFOHEADER);
DC:=GetDC(0);
try
GetDIBits(DC, {$IFDEF CLX}QPixmap_hbm{$ENDIF}(Bitmap.Handle), 0, Bitmap.Height, PicData.Aptr,
TBITMAPINFO(PicData.Stream.Memory^), dib_RGB_Colors);
finally
ReleaseDC(0,DC);
end;
With PicData do
begin
Width :=Bitmap.Width;
Height :=Bitmap.Height;
LineWidth :=Bitmap.Width*3;
LineWidth :=((LineWidth+3) div 4)*4;
BLineWidth :=Bitmap.Height*3;
BLineWidth :=((BLineWidth+3) div 4)*4;
end;
end;
procedure Init;
type PCardinal = ^Cardinal;
var CValuep : PCardinal;
y : Integer;
begin
CValuep:=Pointer(RowPtrs);
for y:=0 to PicData.Height-1 do
begin
CValuep^:=Cardinal(Data)+Cardinal(PicData.Width*FBytesPerPixel*y);
Inc(CValuep);
end;
end;
Procedure CopyImage;
var x : Integer;
y : Integer;
AktPicP,
AktP : PChar;
begin
for y:=0 to PicData.Height-1 do
for x:=0 to PicData.Width-1 do
begin
AktPicP:=PChar(PicData.Aptr) + y*PicData.LineWidth + x*3;
AktP:=PChar(Data) + (PicData.Height-1-y)*(FBytesPerPixel*PicData.Width) + x*FBytesPerPixel;
BYTE((AktP+0)^):=BYTE((AktPicP+2)^);
BYTE((AktP+1)^):=BYTE((AktPicP+1)^);
BYTE((AktP+2)^):=BYTE((AktPicP+0)^);
end;
end;
Procedure GetMemory;
begin
GetMem(Data,PicData.Height*PicData.Width*FBytesPerPixel);
GetMem(RowPtrs, SizeOf(Pointer)*PicData.Height);
end;
Procedure FreeMemory;
begin
if Assigned(Data) then FreeMem(Data);
if Assigned(RowPtrs) then FreeMem(RowPtrs);
end;
Procedure DoSaveToStream;
var png : PPng_Struct;
pnginfo : PPng_Info;
tmp : Array[0..32] of Char;
begin
IStream:=AStream;
tmp:=PNG_LIBPNG_VER_STRING;
png:=png_create_write_struct(tmp, nil, nil, nil);
if Assigned(png) then
try
pnginfo:=png_create_info_struct(png);
png_set_write_fn(png, @SaveBuf, WriteImageStream, FlushImageStream);
png_set_write_status_fn(png, nil);
png_set_IHDR(png, pnginfo, PicData.Width, PicData.Height, 8,
PNG_COLOR_TYPE_RGB,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_write_info(png, pnginfo);
{$IFNDEF TEEOCX}
if CompressionLevel=-1 then
CompressionLevel:=FProperties.UpDown1.Position;
{$ENDIF}
png_set_compression_level(png,CompressionLevel);
png_write_image(png, PPByte(RowPtrs));
png_write_end(png, pnginfo);
png_write_flush(png);
finally
png_destroy_write_struct(@png, @pnginfo);
end;
IStream:=nil;
end;
var tmpBitmap : TBitmap;
begin
{ delayed load of LPNG.DLL procedure addresses }
if PngLib=0 then InitPngLib;
if not Assigned(png_create_write_struct) then LoadProcs;
CheckSize;
PicData.Stream:=TMemoryStream.Create;
try
tmpBitmap:=Bitmap;
try
SetBitmapStream(tmpBitmap,PicData); { 5.01 }
FBytesPerPixel:=3;
GetMemory;
try
Init;
CopyImage;
{$IFDEF TEEOCX}
PNGSection.Enter;
{$ENDIF}
DoSaveToStream;
{$IFDEF TEEOCX}
PNGSection.Leave;
{$ENDIF}
finally
FreeMemory;
end;
finally
tmpBitmap.Free;
end;
finally
PicData.Stream.Free;
end;
end;
procedure ClearProcs;
begin
png_create_write_struct :=nil;
png_create_info_struct :=nil;
png_set_compression_level:=nil;
png_set_write_fn :=nil;
png_set_write_status_fn :=nil;
png_set_IHDR :=nil;
png_write_info :=nil;
png_write_image :=nil;
png_write_end :=nil;
png_write_flush :=nil;
png_destroy_write_struct:=nil;
end;
{$ELSE}
// CLR DOTNET
procedure TPNGExportFormat.SaveToStreamCompression(AStream:TStream; CompressionLevel:Integer);
var tmpBitmap : TBitmap;
begin
CheckSize;
tmpBitmap:=Bitmap;
try
tmpBitmap.SaveToStream(AStream); { pending: convert to PNG }
finally
tmpBitmap.Free;
end;
end;
{$ENDIF}
{$ELSE}
// LINUX:
procedure TPNGExportFormat.SaveToStreamCompression(AStream:TStream; CompressionLevel:Integer);
var tmpBitmap : TBitmap;
begin
CheckSize;
tmpBitmap:=Bitmap;
try
tmpBitmap.SaveToStream(AStream); { pending: convert to PNG }
finally
tmpBitmap.Free;
end;
end;
{$ENDIF}
procedure TPNGExportFormat.SaveToStream(AStream:TStream);
begin
CheckProperties;
SaveToStreamCompression(AStream,FProperties.UpDown1.Position);
end;
procedure TTeePNGOptions.FormCreate(Sender: TObject);
begin
UpDown1.Position:=TeePNG_DefaultCompressionLevel;
end;
{$IFNDEF LINUX}
{$IFNDEF CLR}
Function FileInPath(Const FileName:String):Boolean;
var tmp : array[0..4095] of Char;
begin
result:=(GetEnvironmentVariable('PATH',tmp,SizeOf(tmp))>0) and
(FileSearch(FileName,tmp)<>'');
end;
{$ENDIF}
{$ENDIF}
procedure TTeePNGOptions.Edit1Change(Sender: TObject);
begin
if Assigned(IFormat) then
IFormat.FCompression:=UpDown1.Position;
end;
initialization
{$IFNDEF LINUX}
{$IFNDEF CLR}
{$IFDEF TEEOCX}
if not Assigned(PNGSection) then
PNGSection:=TCriticalSection.Create;
{$ENDIF}
if FileInPath(PNGDLL) then
{$ENDIF}
{$ENDIF}
RegisterTeeExportFormat(TPNGExportFormat);
finalization
UnRegisterTeeExportFormat(TPNGExportFormat);
{$IFNDEF LINUX}
{$IFNDEF CLR}
{$IFDEF TEEOCX}
if Assigned(PNGSection) then PNGSection.Free;
{$ENDIF}
if PngLib>0 then
begin
TeeFreeLibrary(PngLib);
PngLib:=0;
ClearProcs;
end;
{$ENDIF}
{$ENDIF}
end.
|
unit main;
interface
uses
DDDK;
const
DEV_NAME = '\Device\MyDriver';
SYM_NAME = '\DosDevices\MyDriver';
IOCTL_START = $222000; // CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS)
IOCTL_STOP = $222004; // CTL_CODE(FILE_DEVICE_UNKNOWN, 0x801, METHOD_BUFFERED, FILE_ANY_ACCESS)
function _DriverEntry(pOurDriver:PDriverObject; pOurRegistry:PUnicodeString):NTSTATUS; stdcall;
implementation
var
bExit: ULONG;
pThread: Handle;
procedure MyThread(pParam:Pointer); stdcall;
var
ps: Pointer;
tt: LARGE_INTEGER;
begin
tt.HighPart:= tt.HighPart or -1;
tt.LowPart:= ULONG(-10000000);
ps:= IoGetCurrentProcess();
ps:= Pointer(Integer(ps) + $174);
DbgPrint('Current process: %s', [ps]);
while Integer(bExit) = 0 do
begin
KeDelayExecutionThread(KernelMode, FALSE, @tt);
DbgPrint('Sleep 1s', []);
end;
DbgPrint('Exit MyThread', []);
PsTerminateSystemThread(STATUS_SUCCESS);
end;
function IrpOpen(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall;
begin
DbgPrint('IRP_MJ_CREATE', []);
Result:= STATUS_SUCCESS;
pIrp^.IoStatus.Information:= 0;
pIrp^.IoStatus.Status:= Result;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
end;
function IrpClose(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall;
begin
DbgPrint('IRP_MJ_CLOSE', []);
Result:= STATUS_SUCCESS;
pIrp^.IoStatus.Information:= 0;
pIrp^.IoStatus.Status:= Result;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
end;
function IrpIOCTL(pOurDevice:PDeviceObject; pIrp:PIrp):NTSTATUS; stdcall;
var
code: ULONG;
hThread: Handle;
status: NTSTATUS;
psk: PIoStackLocation;
begin
psk:= IoGetCurrentIrpStackLocation(pIrp);
code:= psk^.Parameters.DeviceIoControl.IoControlCode;
case code of
IOCTL_START:begin
DbgPrint('IOCTL_START', []);
bExit:= 0;
status:= PsCreateSystemThread(@hThread, THREAD_ALL_ACCESS, Nil, Handle(-1), Nil, MyThread, pOurDevice);
if NT_SUCCESS(status) then
begin
ObReferenceObjectByHandle(hThread, THREAD_ALL_ACCESS, Nil, KernelMode, @pThread, Nil);
ZwClose(hThread);
end;
end;
IOCTL_STOP:begin
DbgPrint('IOCTL_STOP', []);
bExit:= 1;
KeWaitForSingleObject(Pointer(pThread), Executive, KernelMode, False, Nil);
ObDereferenceObject(pThread);
end;
end;
Result:= STATUS_SUCCESS;
pIrp^.IoStatus.Information:= 0;
pIrp^.IoStatus.Status:= Result;
IoCompleteRequest(pIrp, IO_NO_INCREMENT);
end;
procedure Unload(pOurDriver:PDriverObject); stdcall;
var
szSymName: TUnicodeString;
begin
RtlInitUnicodeString(@szSymName, SYM_NAME);
IoDeleteSymbolicLink(@szSymName);
IoDeleteDevice(pOurDriver^.DeviceObject);
end;
function _DriverEntry(pOurDriver:PDriverObject; pOurRegistry:PUnicodeString):NTSTATUS; stdcall;
var
suDevName: TUnicodeString;
szSymName: TUnicodeString;
pOurDevice: PDeviceObject;
begin
RtlInitUnicodeString(@suDevName, DEV_NAME);
RtlInitUnicodeString(@szSymName, SYM_NAME);
Result:= IoCreateDevice(pOurDriver, 0, @suDevName, FILE_DEVICE_UNKNOWN, 0, FALSE, pOurDevice);
if NT_SUCCESS(Result) then
begin
pOurDriver^.MajorFunction[IRP_MJ_CREATE]:= @IrpOpen;
pOurDriver^.MajorFunction[IRP_MJ_CLOSE] := @IrpClose;
pOurDriver^.MajorFunction[IRP_MJ_DEVICE_CONTROL] := @IrpIOCTL;
pOurDriver^.DriverUnload := @Unload;
pOurDevice^.Flags:= pOurDevice^.Flags or DO_BUFFERED_IO;
pOurDevice^.Flags:= pOurDevice^.Flags and not DO_DEVICE_INITIALIZING;
Result:= IoCreateSymbolicLink(@szSymName, @suDevName);
end;
end;
end.
|
unit uRSAss;
{
ResourceString: Dario 13/03/13
Nada para fazer
}
interface
uses SysUtils, Variants;
type
TAssinatura = record
prDescr : String[200];
prValor : Currency;
prMeses : Byte;
end;
TDadosEmissaoBol = record
deNome : String[100];
deCNPJ : String[19];
deEnd : String[100];
deCidade : String[50];
deUF : String[2];
deCedente: String[50];
end;
TDadosBoleto = record
dbVenc : TDateTime;
dbLanc : TDateTime;
dbNum : Integer;
dbDescr : String[100];
dbValor : Currency;
dbPagoEm : TDateTime;
dbCanceladoEm : TDateTime;
dbBaixou : Boolean;
end;
TArrayAssinatura = Array of TAssinatura;
TArrayBoleto = Array of TDadosBoleto;
procedure VariantToAssinatura(V: Variant; var A: TAssinatura);
procedure VariantToArrayAssinatura(V: Variant; var A: TArrayAssinatura);
function AssinaturaToVariant(var A: TAssinatura): Variant;
function ArrayAssinaturaToVariant(var A: TArrayAssinatura): Variant;
procedure VariantToBoleto(V: Variant; var B: TDadosBoleto);
procedure VariantToArrayBoleto(V: Variant; var A: TArrayBoleto);
function BoletoToVariant(var B: TDadosBoleto): Variant;
function ArrayBoletoToVariant(var A: TArrayBoleto): Variant;
procedure VariantToDadosEmissaoBol(V: Variant; var D: TDadosEmissaoBol);
function DadosEmissaoBolToVariant(var D: TDadosEmissaoBol): Variant;
implementation
procedure VariantToAssinatura(V: Variant; var A: TAssinatura);
begin
A.prDescr := V[0];
A.prValor := V[1];
A.prMeses := V[2];
end;
procedure VariantToArrayAssinatura(V: Variant; var A: TArrayAssinatura);
var I : Integer;
begin
if VarIsNull(V) then
SetLength(A, 0)
else begin
SetLength(A, VarArrayHighBound(V, 1)+1);
for I := 0 to High(A) do begin
A[i].prDescr := V[I][0];
A[i].prValor := V[I][1];
A[i].prMeses := V[I][2];
end;
end;
end;
function AssinaturaToVariant(var A: TAssinatura): Variant;
begin
Result := VarArrayOf([A.prDescr, A.prValor, A.prMeses]);
end;
function ArrayAssinaturaToVariant(var A: TArrayAssinatura): Variant;
var I : Integer;
begin
Result := VarArrayCreate([0, High(A)], VarVariant);
for I := 0 to High(A) do
Result[I] := AssinaturaToVariant(A[I]);
end;
procedure VariantToBoleto(V: Variant; var B: TDadosBoleto);
begin
B.dbVenc := V[0];
B.dbLanc := V[1];
B.dbNum := V[2];
B.dbValor := V[3];
B.dbDescr := V[4];
B.dbPagoEm := V[5];
B.dbCanceladoEm := V[6];
B.dbBaixou := V[7];
end;
procedure VariantToArrayBoleto(V: Variant; var A: TArrayBoleto);
var I : Integer;
begin
if VarIsNull(V) then
SetLength(A, 0)
else begin
SetLength(A, VarArrayHighBound(V, 1)+1);
for I := 0 to High(A) do begin
A[I].dbVenc := V[I][0];
A[I].dbLanc := V[I][1];
A[I].dbNum := V[I][2];
A[I].dbValor := V[I][3];
A[I].dbDescr := V[I][4];
A[I].dbPagoEm := V[I][5];
A[I].dbCanceladoEm := V[I][6];
A[I].dbBaixou := V[I][7];
end;
end;
end;
function BoletoToVariant(var B: TDadosBoleto): Variant;
begin
Result := VarArrayOf([B.dbVenc, B.dbLanc, B.dbNum, B.dbValor, B.dbDescr, B.dbPagoEm, B.dbCanceladoEm, B.dbBaixou]);
end;
function ArrayBoletoToVariant(var A: TArrayBoleto): Variant;
var I : Integer;
begin
Result := VarArrayCreate([0, High(A)], VarVariant);
for I := 0 to High(A) do
Result[I] := BoletoToVariant(A[I]);
end;
procedure VariantToDadosEmissaoBol(V: Variant; var D: TDadosEmissaoBol);
begin
D.deNome := V[0];
D.deCNPJ := V[1];
D.deEnd := V[2];
D.deCidade := V[3];
D.deUF := V[4];
D.deCedente := V[5];
end;
function DadosEmissaoBolToVariant(var D: TDadosEmissaoBol): Variant;
begin
Result := VarArrayOf([D.deNome, D.deCNPJ, D.deEnd, D.deCidade, D.deUF, D.deCedente]);
end;
end.
|
unit SmallClaimsAddDialogUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, wwdblook, Db, DBTables, ExtCtrls, ComCtrls;
type
TSmallClaimsAddDialog = class(TForm)
OKButton: TBitBtn;
CancelButton: TBitBtn;
LawyerCodeTable: TTable;
GroupBox1: TGroupBox;
Label2: TLabel;
LawyerCodeLookupCombo: TwwDBLookupCombo;
Label1: TLabel;
GroupBox2: TGroupBox;
Label3: TLabel;
Label4: TLabel;
SmallClaimsTable: TTable;
EditIndexNumber: TEdit;
CheckForGrievanceTimer: TTimer;
GrievanceTable: TTable;
ProgressBar: TProgressBar;
SwisCodeTable: TTable;
HistorySwisCodeTable: TTable;
PriorAssessmentTable: TTable;
CurrentAssessmentTable: TTable;
PriorSwisCodeTable: TTable;
ParcelTable: TTable;
SmallClaimsExemptionsAskedTable: TTable;
SmallClaimsExemptionsTable: TTable;
CurrentSalesTable: TTable;
CurrentExemptionsTable: TTable;
SmallClaimsSpecialDistrictsTable: TTable;
CurrentSpecialDistrictsTable: TTable;
SmallClaimsSalesTable: TTable;
GrievanceExemptionsAskedTable: TTable;
GrievanceYearGroupBox: TGroupBox;
Label5: TLabel;
Label6: TLabel;
EditSmallClaimsYear: TEdit;
GrievanceDispositionCodeTable: TTable;
GrievanceResultsTable: TTable;
NewLawyerButton: TBitBtn;
procedure OKButtonClick(Sender: TObject);
procedure LawyerCodeLookupComboNotInList(Sender: TObject;
LookupTable: TDataSet; NewValue: String; var Accept: Boolean);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CheckForGrievanceTimerTimer(Sender: TObject);
procedure NewLawyerButtonClick(Sender: TObject);
procedure EditSmallClaimsYearExit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
LawyerCode : String;
SmallClaimsYear,
PriorYear, SwisSBLKey : String;
GrievanceNumber,
SmallClaimsCopyType,
TotalParcelsWithThisGrievance,
IndexNumber : LongInt;
AlreadyCopied : Boolean;
SmallClaimsProcessingType,
PriorProcessingType : Integer;
Function OpenTables(SmallClaimsProcessingType : Integer;
PriorProcessingType : Integer) : Boolean;
end;
var
SmallClaimsAddDialog: TSmallClaimsAddDialog;
implementation
{$R *.DFM}
uses Cert_Or_SmallClaimsDuplicatesDialogUnit, GrievanceUtilitys, WinUtils,
PASUtils, PASTypes, GlblCnst, GlblVars, Utilitys, NewLawyerDialog;
const
ctNone = 0;
ctThisParcel = 1;
ctAllParcels = 2;
{===============================================================}
Procedure TSmallClaimsAddDialog.CheckForGrievanceTimerTimer(Sender: TObject);
var
iGrievanceNumber : Integer;
begin
CheckForGrievanceTimer.Enabled := False;
SmallClaimsCopyType := ctNone;
GrievanceTable.IndexName := 'BYSWISSBLKEY_TAXROLLYR_GREVNUM';
SetRangeOld(GrievanceTable, ['SwisSBLKey', 'TaxRollYr', 'GrievanceNumber'],
[SwisSBLKey, SmallClaimsYear, '0'],
[SwisSBLKey, SmallClaimsYear, '9999']);
If (GrievanceTable.RecordCount > 0)
then
If (GrievanceTable.RecordCount > 1)
then MessageDlg('The grievance information can not be copied to the small claims system because' + #13 +
'there is more than 1 grievance entered for this assessment year.' + #13 +
'Please enter the small claims information by hand.', mtWarning, [mbOK], 0)
else
begin
{Check to see if this grievance number is on more than 1 parcel.}
iGrievanceNumber := GrievanceTable.FieldByName('GrievanceNumber').AsInteger;
GrievanceTable.IndexName := 'BYTAXROLLYR_GREVNUM';
SetRangeOld(GrievanceTable, ['TaxRollYr', 'GrievanceNumber'],
[SmallClaimsYear, IntToStr(iGrievanceNumber)],
[SmallClaimsYear, IntToStr(iGrievanceNumber)]);
If (GrievanceTable.RecordCount = 1)
then
begin
If (MessageDlg('Do you want to copy the grievance information already entered for this parcel ' +
'to this new small claims?', mtConfirmation, [mbYes, mbNo], 0) = idYes)
then SmallClaimsCopyType := ctThisParcel;
end
else
If (MessageDlg('The grievance that is already on this parcel is also on ' +
IntToStr(GrievanceTable.RecordCount - 1) + ' other parcels.' + #13 +
'Do you want to create small claims on all parcels with this grievance number?',
mtConfirmation, [mbYes, mbNo], 0) = idYes)
then
begin
SmallClaimsCopyType := ctAllParcels;
TotalParcelsWithThisGrievance := GrievanceTable.RecordCount;
end
else
If (MessageDlg('Do you want to copy the grievance information already entered for this parcel ' +
'to this new small claims?', mtConfirmation, [mbYes, mbNo], 0) = idYes)
then SmallClaimsCopyType := ctThisParcel;
{FXX10142009-2(2.20.1.20)[I6595]: Reaccess the grievance with the grievance # and the SBL.}
GrievanceTable.IndexName := 'BYSWISSBLKEY_TAXROLLYR_GREVNUM';
SetRangeOld(GrievanceTable, ['SwisSBLKey', 'TaxRollYr', 'GrievanceNumber'],
[SwisSBLKey, SmallClaimsYear, '0'],
[SwisSBLKey, SmallClaimsYear, '9999']);
end; {else of If (GrievanceTable.RecordCount > 1)}
If (SmallClaimsCopyType <> ctNone)
then
begin
If (SmallClaimsCopyType = ctAllParcels)
then GrievanceTable.First;
LawyerCodeLookupCombo.Text := GrievanceTable.FieldByName('LawyerCode').Text;
end; {If (SmallClaimsCopyType <> ctNone)}
end; {CheckForGrievanceTimerTimer}
{===============================================================}
Function TSmallClaimsAddDialog.OpenTables(SmallClaimsProcessingType : Integer;
PriorProcessingType : Integer) : Boolean;
begin
Result := False;
OpenTableForProcessingType(SwisCodeTable, SwisCodeTableName,
SmallClaimsProcessingType, Result);
OpenTableForProcessingType(CurrentAssessmentTable, AssessmentTableName,
SmallClaimsProcessingType, Result);
OpenTableForProcessingType(PriorSwisCodeTable, SwisCodeTableName,
PriorProcessingType, Result);
OpenTableForProcessingType(PriorAssessmentTable, AssessmentTableName,
PriorProcessingType, Result);
OpenTableForProcessingType(CurrentExemptionsTable, ExemptionsTableName,
SmallClaimsProcessingType, Result);
OpenTableForProcessingType(CurrentSpecialDistrictsTable, SpecialDistrictTableName,
SmallClaimsProcessingType, Result);
end; {OpenTables}
{===============================================================}
Procedure TSmallClaimsAddDialog.FormShow(Sender: TObject);
var
SBLRec : SBLRecord;
begin
AlreadyCopied := False;
EditSmallClaimsYear.Text := SmallClaimsYear;
OpenTablesForForm(Self, SmallClaimsProcessingType);
{First let's find this parcel in the parcel table.}
SBLRec := ExtractSwisSBLFromSwisSBLKey(SwisSBLKey);
with SBLRec do
FindKeyOld(ParcelTable,
['TaxRollYr', 'SwisCode', 'Section',
'Subsection', 'Block', 'Lot', 'Sublot', 'Suffix'],
[SmallClaimsYear, SwisCode, Section,
SubSection, Block, Lot, Sublot, Suffix]);
GrievanceTable.IndexName := 'BYSWISSBLKEY_TAXROLLYR_GREVNUM';
SetRangeOld(GrievanceTable, ['SwisSBLKey', 'TaxRollYr', 'GrievanceNumber'],
[SwisSBLKey, SmallClaimsYear, '0'],
[SwisSBLKey, SmallClaimsYear, '9999']);
GrievanceNumber := GrievanceTable.FieldByName('GrievanceNumber').AsInteger;
OpenTables(SmallClaimsProcessingType, PriorProcessingType);
CheckForGrievanceTimer.Enabled := True;
end; {FormShow}
{===============================================================}
Procedure TSmallClaimsAddDialog.EditSmallClaimsYearExit(Sender: TObject);
{Check to see if we can copy a grievance based on the year they entered if the
year is other than the ThisYear.}
begin
If _Compare(EditSmallClaimsYear.Text, GlblThisYear, coNotEqual)
then
begin
SmallClaimsYear := EditSmallClaimsYear.Text;
CheckForGrievanceTimer.Enabled := True;
end;
end; {EditSmallClaimsYearExit}
{===============================================================}
Procedure TSmallClaimsAddDialog.OKButtonClick(Sender: TObject);
var
FirstTimeThrough, Done, Continue : Boolean;
NumParcelsCopiedTo : Integer;
ThisSwisSBLKey : String;
begin
Continue := True;
LawyerCode := LawyerCodeLookupCombo.Text;
SmallClaimsYear := EditSmallClaimsYear.Text;
{FXX10122009-2(2.20.1.20): Make sure to adjust the prior year.}
PriorYear := IntToStr(StrToInt(SmallClaimsYear) - 1);
try
IndexNumber := StrToInt(EditIndexNumber.Text);
except
Continue := False;
MessageDlg('Sorry, ' + EditIndexNumber.Text + ' is not a valid SmallClaims number.' + #13 +
'Please correct it.', mtError, [mbOK], 0);
EditIndexNumber.SetFocus;
end;
{See if there are other parcels already with this SmallClaims number.
If so, warn them, but let them continue.}
If Continue
then
begin
SetRangeOld(SmallClaimsTable, ['TaxRollYr', 'IndexNumber'],
[SmallClaimsYear, IntToStr(IndexNumber)],
[SmallClaimsYear, IntToSTr(IndexNumber)]);
SmallClaimsTable.First;
If not SmallClaimsTable.EOF
then
try
Cert_Or_SmallClaimsDuplicatesDialog := TCert_Or_SmallClaimsDuplicatesDialog.Create(nil);
Cert_Or_SmallClaimsDuplicatesDialog.IndexNumber := IndexNumber;
Cert_Or_SmallClaimsDuplicatesDialog.CurrentYear := SmallClaimsYear;
Cert_Or_SmallClaimsDuplicatesDialog.AskForConfirmation := True;
Cert_Or_SmallClaimsDuplicatesDialog.Source := 'S';
If (Cert_Or_SmallClaimsDuplicatesDialog.ShowModal = idNo)
then Continue := False;
finally
Cert_Or_SmallClaimsDuplicatesDialog.Free;
end;
end; {If Continue}
If Continue
then
begin
{FXX10142009-1(2.20.1.20)[D1562]: Need to set the processing types based on the
year entered.}
SmallClaimsProcessingType := GetProcessingTypeForTaxRollYear(SmallClaimsYear);
case SmallClaimsProcessingType of
NextYear : PriorProcessingType := ThisYear;
ThisYear : PriorProcessingType := History;
History : PriorProcessingType := History;
end;
OpenTables(SmallClaimsProcessingType, PriorProcessingType);
FindKeyOld(LawyerCodeTable, ['Code'],
[LawyerCode]);
case SmallClaimsCopyType of
ctThisParcel :
begin
AlreadyCopied := True;
CopyGrievanceToCert_Or_SmallClaim(IndexNumber,
GrievanceNumber,
SmallClaimsYear,
PriorYear,
SwisSBLKey,
LawyerCode, 1,
GrievanceTable,
SmallClaimsTable,
LawyerCodeTable,
ParcelTable,
CurrentAssessmentTable,
PriorAssessmentTable,
SwisCodeTable,
PriorSwisCodeTable,
CurrentExemptionsTable,
SmallClaimsExemptionsTable,
CurrentSpecialDistrictsTable,
SmallClaimsSpecialDistrictsTable,
CurrentSalesTable,
SmallClaimsSalesTable,
GrievanceExemptionsAskedTable,
SmallClaimsExemptionsAskedTable,
GrievanceResultsTable,
GrievanceDispositionCodeTable, 'S');
end; {ctThisParcel}
ctAllParcels :
begin
AlreadyCopied := True;
NumParcelsCopiedTo := 0;
ProgressBar.Visible := True;
ProgressBar.Max := TotalParcelsWithThisGrievance;
GrievanceTable.IndexName := 'BYTAXROLLYR_GREVNUM';
FirstTimeThrough := True;
Done := False;
SetRangeOld(GrievanceTable, ['TaxRollYr', 'GrievanceNumber'],
[SmallClaimsYear, IntToStr(GrievanceNumber)],
[SmallClaimsYear, IntToStr(GrievanceNumber)]);
GrievanceTable.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else GrievanceTable.Next;
If GrievanceTable.EOF
then Done := True;
If not Done
then
begin
NumParcelsCopiedTo := NumParcelsCopiedTo + 1;
ProgressBar.Position := NumParcelsCopiedTo;
Application.ProcessMessages;
ThisSwisSBLKey := GrievanceTable.FieldByName('SwisSBLKey').Text;
CopyGrievanceToCert_Or_SmallClaim(IndexNumber,
GrievanceNumber,
SmallClaimsYear,
PriorYear,
ThisSwisSBLKey,
LawyerCode,
TotalParcelsWithThisGrievance,
GrievanceTable,
SmallClaimsTable,
LawyerCodeTable,
ParcelTable,
CurrentAssessmentTable,
PriorAssessmentTable,
SwisCodeTable,
PriorSwisCodeTable,
CurrentExemptionsTable,
SmallClaimsExemptionsTable,
CurrentSpecialDistrictsTable,
SmallClaimsSpecialDistrictsTable,
CurrentSalesTable,
SmallClaimsSalesTable,
GrievanceExemptionsAskedTable,
SmallClaimsExemptionsAskedTable,
GrievanceResultsTable,
GrievanceDispositionCodeTable, 'S');
end; {If not Done}
until Done;
MessageDlg('The small claims was copied to ' +
IntToStr(TotalParcelsWithThisGrievance) +
' parcels (including this one).', mtInformation, [mbOK], 0);
end; {ctAllParcels}
end; {case SmallClaimsCopyType of}
ModalResult := mrOK;
end; {If Continue}
end; {OKButtonClick}
{===============================================================}
Procedure TSmallClaimsAddDialog.NewLawyerButtonClick(Sender: TObject);
{CHG01262004-1(2.07l1): Let them create a new representative right from the add screen.}
begin
try
NewLawyerForm := TNewLawyerForm.Create(nil);
NewLawyerForm.InitializeForm;
If (NewLawyerForm.ShowModal = idOK)
then
begin
LawyerCodeLookupCombo.Text := NewLawyerForm.LawyerSelected;
FindKeyOld(LawyerCodeTable, ['Code'], [NewLawyerForm.LawyerSelected]);
end;
finally
NewLawyerForm.Free;
end;
end; {NewLawyerButtonClick}
{===============================================================}
Procedure TSmallClaimsAddDialog.LawyerCodeLookupComboNotInList( Sender: TObject;
LookupTable: TDataSet;
NewValue: String;
var Accept: Boolean);
begin
If (NewValue = '')
then Accept := True;
end; {LawyerCodeLookupComboNotInList}
{======================================================}
Procedure TSmallClaimsAddDialog.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
CloseTablesForForm(Self);
Action := caFree;
end;
end.
|
{*
FrameStringGridBase.pas/dfm
---------------------------
Begin: 2005/10/21
Last revision: $Date: 2011-10-12 19:42:49 $ $Author: rhupalo $
Version number: $Revision: 1.25 $
Project: APHI General Purpose Delphi Libary
Website: http://www.naadsm.org/opensource/delphi/
Author: Aaron Reeves <aaron.reeves@naadsm.org>
--------------------------------------------------
Copyright (C) 2005 - 2010 Colorado State University
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
--------------------------------------------------
Frame for tabular output forms to display, print, and manage numeric output in a grid of cells.
}
(*
Documentation generation tags begin with {* or ///
Replacing these with (* or // foils the documentation generator
*)
unit FrameStringGridBase;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
Grids,
ExtCtrls,
ARSyncGrid
;
// From a demonstration written by Nilesh N Shah.
// See http://www.delphipages.com/tips/thread.cfm?ID=102
type
/// Record for printing the contents of a grid
RRecPrintStrGrid = Record
PrCanvas : TCanvas; /// Printer or PaintBox Canvas
sGrid: TARSyncGrid; /// StringGrid containing data
sTitle: String; /// Title of document
bPrintFlag : Boolean; /// Print if True
ptXYOffset : TPoint; /// Left and Top margins
ftTitleFont : TFont; /// Font for Title
ftHeadingFont : TFont; /// Font for Heading row
ftDataFont : TFont; /// Font for Data
bBorderFlag : Boolean; /// Print border if True
// variables above are the original and the ones below are needed for Teixeira and Pacheco's approach
lineHeight: Integer; /// line height based on text height using the currently rendered font
amountPrinted: integer; /// keeps track of vertical space in pixels, printed on a page
tenthsOfInchPixelsY: integer; /// number of pixels in 1/10 of an inch, used for line spacing
end
;
type
/// Frame containing the string grid (TARSyncGrid) and methods to manage it.
TFrameStringGridBase = class( TFrame )
stgGrid: TARSyncGrid; /// the grid of cells, holding either captions or data
pnlSpacer: TPanel; /// panel component for implementing the rightSpace property
procedure stgGridSelectCell( Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean );
procedure stgGridEnter(Sender: TObject);
protected
function getOptions(): TGridOptions;
function getCell( ACol, ARow: integer ): string;
procedure setCell( ACol, ARow: integer; val: string );
procedure setColCount( const val: integer );
procedure setRowCount( const val: integer );
procedure setColWidth( ACol: longint; val: integer );
procedure setRowHeight( ARow: longint; val: integer );
procedure setFixedCols( const val: integer );
procedure setFixedRows( const val: integer );
function getColCount(): integer;
function getRowCount(): integer;
function getColWidth( ACol: longint ): integer;
function getRowHeight( ARow: longint ): integer;
function getFixedCols(): integer;
function getFixedRows(): integer;
procedure setRightSpace( const val: integer );
function getRightSpace(): integer;
public
constructor create( AOwner: TComponent ); override;
destructor destroy(); override;
procedure printGrid( pageTitle: string = ''; reportHeader: string = '' );
procedure printGrid2( pageTitle: string = '' );
function csvText(): string; virtual;
function saveToFile( const fileName: string; header: string = '' ): boolean;
procedure clearColumn( const i: integer );
procedure clearGrid( clearFixedCells: boolean = false );
/// read-only access to the grid option settings
property options: TGridOptions read getOptions;
/// Access to the grid cell at column i, row j
property Cells[ACol, ARow: Integer]: string read getCell write setCell;
/// Access for reading or setting the number of columns
property colCount: integer read getColCount write setColCount;
/// Access for reading or setting the number of rows
property rowCount: integer read getRowCount write setRowCount;
/// Access for reading or setting a column width
property colWidths[ACol: longint]: integer read getColWidth write setColWidth;
/// Access for reading or setting a row heights
property rowHeights[ARow: longint]: integer read getRowHeight write setRowHeight;
/// Access for reading or setting the number of fixed columns
property fixedCols: integer read getFixedCols write setFixedCols;
/// Access for reading or setting the number of fixed rows
property fixedRows: integer read getFixedRows write setFixedRows;
/// Access to reading or setting the amount of empty space between the right edge of the grid and the right edge of the frame
property rightSpace: integer read getRightSpace write setRightSpace;
end
;
const
DBFRAMESTRINGGRIDBASE: boolean = false; /// Set to true to enable debugging message for this unit
implementation
{$R *.dfm}
uses
Math,
Printers,
StrUtils,
CStringList,
MyStrUtils,
DebugWindow,
I88n
;
{*
Creates an empty grid, that is, one without cells
@param AOwner the form that owns this instance of the frame
}
constructor TFrameStringGridBase.create( AOwner: TComponent );
begin
inherited create( AOwner );
dbcout( 'Creating TFrameStringGridBase', DBFRAMESTRINGGRIDBASE );
stgGrid.SyncGrid := nil;
dbcout( 'Done creating TFrameStringGridBase', DBFRAMESTRINGGRIDBASE );
end
;
/// Destroys the frame and frees memory
destructor TFrameStringGridBase.destroy();
begin
dbcout( 'Destroying TFrameStringGridBase', DBFRAMESTRINGGRIDBASE );
inherited destroy();
end
;
{*
Get method for property options, returning the option settings for stgGrid
@return a set of TGridOption enumerated values
}
function TFrameStringGridBase.getOptions(): TGridOptions;
begin
result := stgGrid.options;
end
;
{*
Get method for property cells, returning the contents of a cell
@param ACol column index, zero-based and should include any fixed columns
@param ARow row index, zero-based and should include any fixed rows
@return the contents of cell ACol,ARow or an empty string if the cell does not exist
}
function TFrameStringGridBase.getCell( ACol, ARow: integer ): string;
begin
result := stgGrid.Cells[ACol, ARow];
end
;
{*
Set method for property cells, setting the contents of a cell
@param ACol column index, zero-based and should include any fixed columns
@param ARow row index, zero-based and should include any fixed rows
@param val the value for cell ACol,ARow
}
procedure TFrameStringGridBase.setCell( ACol, ARow: integer; val: string );
begin
stgGrid.Cells[ACol, ARow] := val;
end
;
{*
Set method for property colCount, setting the number of columns of stgGrid to val
}
procedure TFrameStringGridBase.setColCount( const val: integer );
begin
stgGrid.ColCount := val;
end
;
{*
Set method for property rowCount, setting the number of rows of stgGrid to val
}
procedure TFrameStringGridBase.setRowCount( const val: integer );
begin
stgGrid.RowCount := val;
end
;
{*
Set method for property fixedCols, setting the number of fixed columns of stgGrid to val
@comment Fixed columns often contain a descriptive term/name for the column, not data.
}
procedure TFrameStringGridBase.setFixedCols( const val: integer );
begin
stgGrid.FixedCols := val;
end
;
{*
Set method for property fixedRows, setting the number of fixed rows of stgGrid to val
@comment Fixed rows often contain a descriptive term/name for the row, not data.
}
procedure TFrameStringGridBase.setFixedRows( const val: integer );
begin
stgGrid.FixedRows := val;
end
;
/// Get method for property fixedCols, returning the number of fixed columns in stgGrid
function TFrameStringGridBase.getColCount(): integer;
begin
result := stgGrid.ColCount;
end
;
/// Get method for property rowCount, returning the number of rows in stgGrid
function TFrameStringGridBase.getRowCount(): integer;
begin
result := stgGrid.RowCount;
end
;
/// Get method for property colCount, returning the number of columns in stgGrid
function TFrameStringGridBase.getFixedCols(): integer;
begin
result := stgGrid.FixedCols;
end
;
/// Get method for property fixedRows, returning the number of fixed rows in stgGrid
function TFrameStringGridBase.getFixedRows(): integer;
begin
result := stgGrid.FixedRows;
end
;
/// Set method for property colWidths, setting the width of column ACol to val
procedure TFrameStringGridBase.setColWidth( ACol: longint; val: integer );
begin
stgGrid.ColWidths[ACol] := val;
end
;
/// Get method for property colWidths, returning the width of column ACol
function TFrameStringGridBase.getColWidth( ACol: longint ): integer;
begin
result := stgGrid.ColWidths[ACol];
end
;
/// Set method for property rowHeights, setting the height of row ARow to val
procedure TFrameStringGridBase.setRowHeight( ARow: longint; val: integer );
begin
stgGrid.RowHeights[ARow] := val;
end
;
/// Get method for property rowHeights, returning the height of row ARow
function TFrameStringGridBase.getRowHeight( ARow: longint ): integer;
begin
result := stgGrid.RowHeights[ARow];
end
;
{*
Deletes any data from the grid and optionally deletes values in the fixed cells
@param clearFixedCells if true the cell contents of fixed rows and colummns are also cleared
}
procedure TFrameStringGridBase.clearGrid( clearFixedCells: boolean = false );
var
c, r: integer;
sc, sr: integer;
begin
if( clearFixedCells ) then
begin
sc := 0;
sr := 0;
end
else
begin
sc := stgGrid.fixedCols;
sr := stgGrid.FixedRows;
end
;
for c := sc to stgGrid.colCount - 1 do
begin
for r := sr to stgGrid.rowCount - 1 do
stgGrid.cells[c,r] := ''
;
end
;
end
;
/// Set method for property rightSpace, setting the width of space on the right of the grid to val pixels
procedure TFrameStringGridBase.setRightSpace( const val: integer );
begin
pnlSpacer.Width := val;
end
;
/// Get method for property rightSpace, returning the width of space on the right of the grid
function TFrameStringGridBase.getRightSpace(): integer;
begin
result := pnlSpacer.Width;
end
;
/// Helper method for saveToFile(), returning a CSV formatted tabular string of the data and fixed cell values
function TFrameStringGridBase.csvText(): string;
var
s, s2: string;
c, r: integer;
begin
result := '';
for r := 0 to stgGrid.RowCount - 1 do
begin
s := '';
for c := 0 to stgGrid.ColCount - 1 do
begin
s2 := stgGrid.Cells[ c, r ];
if( not( isNan( uiStrToFloat( s2, NaN ) ) ) ) then
s2 := ansiReplaceStr( s2, SysUtils.DecimalSeparator, csvDecPt )
;
s := s + s2;
if( stgGrid.ColCount - 1 > c ) then
s := s + csvListSep + ' '
else
s := s + endl
;
end
;
result := result + s;
end
;
end
;
{*
Saves the contents of the grid (data and fixed cell values) to a CVS formatted file
@param fileName directory path and file name for the file to created
@param header metadata concerning the file contents, each line should start with ##
@return true if the file is written to disk, else false
@comment If a file already exists named fileName it will be overwritten.
}
function TFrameStringGridBase.saveToFile( const fileName: string; header: string = '' ): boolean;
var
outFile: TextFile;
begin
try
assignFile( outFile, fileName );
rewrite( outFile );
writeln( outFile, header );
writeln( outFile, csvText() );
closeFile( outFile );
result := true;
except
result := false;
end;
end
;
/// Clears the contents of column i, including any fixed cells
procedure TFrameStringGridBase.clearColumn( const i: integer );
var
j: integer;
begin
for j := 0 to stgGrid.RowCount -1 do
stgGrid.cells[i, j] := ''
;
end
;
//rbh20111012: Deprecated, Teixeira and Pacheco's method (printgrid()) seems better
// Based on a demonstration written by Nilesh N Shah.
// See http://www.delphipages.com/tips/thread.cfm?ID=102
{*
Outputs the grid contents to the default printer
@param pageTitle text to print as the page title, optional
}
procedure TFrameStringGridBase.printGrid2( pageTitle: string = '' );
var
recPrintStrGrid: RRecPrintStrGrid;
iX1, iX2, iY0, iY1, iY2, iY3, iTmp: integer;
//iWd: Integer;
iLoop, jLoop: integer;
trTextRect: TRect;
colWidth: array of integer;
//titleLines: TCStringList;
//line: string;
const
COLSPACER: integer = 100;
ROWSPACER: integer = 10;
begin
// Set up print options
with recPrintStrGrid do
begin
PrCanvas := printer.Canvas;
sGrid := self.stgGrid;
sTitle := pageTitle;
bPrintFlag := true;
ptXYOffset.X := 10;
ptXYOffset.Y := 100;
ftTitleFont := TFont.Create();
with ftTitleFont do
begin
Name := 'Arial';
Style := [];
Size := 10;
end
;
ftHeadingFont := TFont.Create();
with ftHeadingFont do
begin
Name := 'Arial';
Style := [fsBold];
Size := 9;
end
;
ftDataFont := TFont.Create();
with ftDataFont do
begin
Name := 'Arial';
Style := [];
Size := 9;
end
;
bBorderFlag := True;
end
;
recPrintStrGrid.PrCanvas.Font := recPrintStrGrid.ftDataFont;
// Determine the maximum width of each column in the grid
setLength( colWidth, recPrintStrGrid.sGrid.ColCount );
for iLoop := 0 to recPrintStrGrid.sGrid.ColCount - 1 do
colWidth[iLoop] := COLSPACER
;
for iLoop := 0 to recPrintStrGrid.sGrid.ColCount - 1 do
begin
for jLoop := 0 to recPrintStrGrid.sGrid.RowCount -1 do
begin
if( recPrintStrGrid.PrCanvas.textWidth( recPrintStrGrid.sGrid.Cells[iLoop, jLoop] ) > colWidth[iLoop] ) then
colWidth[iLoop] := recPrintStrGrid.PrCanvas.textWidth( recPrintStrGrid.sGrid.Cells[iLoop, jLoop] ) + COLSPACER
;
end
;
end
;
(*
// Calculate total width of the grid, based on the widest member of each column
iWd := 0;
for iLoop := 0 to recPrintStrGrid.sGrid.ColCount - 1 do
iWd := iWd + colWidth[iLoop]
;
*)
with recPrintStrGrid, PrCanvas do
begin
//Initialize Printer
if bPrintFlag then
begin
Printer.Title := sTitle;
Printer.BeginDoc;
end
;
iY0 := ptXYOffset.Y;
// FIX ME: title printing doesn't work well at all.
(*
//Output Title
if( '' <> sTitle ) then
begin
Pen.Color := clBlack;
Font := ftTitleFont;
titleLines := TCStringList.create( sTitle, #10 );
for iLoop := 0 to titleLines.Count do
begin
TextOut(
ptXYOffset.X, // Left-aligned, instead of centered //((iWd Div 2) - (TextWidth(sTitle) Div 2))},
iY0,
trim( titleLines.at(iLoop) )
);
iY0 := iY0 + (TextHeight('Ag') + ROWSPACER);
end
;
titleLines.Free();
end
;
*)
//Output Column Data
for iLoop := 0 to sGrid.ColCount-1 do
begin
Font := ftHeadingFont;
iX1 := ptXYOffset.X;
iY1 := iY0;
for iTmp := 0 to (iLoop-1) do
iX1 := iX1 + colWidth[iTmp]
;
iY1 := iY1 + ((TextHeight('Ag') + ROWSPACER) * 2);
iX2 := ptXYOffset.X;
for iTmp := 0 to iLoop do
ix2 := ix2 + colWidth[iTmp]
;
iY2 := iY1 + TextHeight('Ag');
trTextRect := Rect(iX1, iY1, iX2, iY2);
dbcout( 'iX1: ' + intToStr( iX1 ) + ', iX2: ' + intToStr( iX2 ), DBFRAMESTRINGGRIDBASE );
dbcout( 'ColWidth: ' + intToSTr( colWidth[iLoop] ), DBFRAMESTRINGGRIDBASE );
TextRect(trTextRect, trTextRect.Left + (COLSPACER div 2), trTextRect.Top+3, sGrid.Cells[iLoop, 0] );
Brush.Color := clBlack;
if bBorderFlag then FrameRect(trTextRect);
Brush.Style := bsClear;
//Output Row Data
Font := ftDataFont;
iY1 := iY2;
iY3 := TextHeight('Ag') + ROWSPACER;
for iTmp := 1 to sGrid.RowCount-1 do
begin
iY2 := iY1 + iY3;
trTextRect := Rect(iX1, iY1, iX2, iY2);
TextRect(trTextRect, trTextRect.Left + 5, trTextRect.Top+3, sGrid.Cells[iLoop, iTmp]);
Brush.Color := clBlack;
if bBorderFlag then FrameRect(trTextRect);
Brush.Style := bsClear;
iY1 := iY1 + iY3;
end
;
end
;
if bPrintFlag then Printer.EndDoc;
end // with ArecPrintStrGrid, prCanvas
;
//clean up
setLength( colWidth, 0 );
recPrintStrGrid.ftTitleFont.free();
recPrintStrGrid.ftHeadingFont.free();
recPrintStrGrid.ftDataFont.free();
end
;
// Based on Chapter 10 Delphi 5 Developer's Guide (Teixeira and Pacheco, 2000)
{*
Outputs the grid contents to the default printer
@param pageTitle text to print as the page title, optional
@param reportHeader output from FormOutputStats.textHeader(), optional
@Comment bBorderFlag is not currently implement, Aaron please see Fix Me below.
}
procedure TFrameStringGridBase.printGrid( pageTitle: string = ''; reportHeader: string = '' );
// inline proc (recPrintStrGrid HAS to be passed in by reference, not value)
procedure PrintRow(var Items: TStringList; var recPrintStrGrid: RRecPrintStrGrid);
var
OutRect: TRect;
i: integer;
begin
// First position the print rect on the print canvas
OutRect.Left := 0;
OutRect.Top := recPrintStrGrid.AmountPrinted;
OutRect.Bottom := OutRect.Top + recPrintStrGrid.lineHeight;
for i := 0 to Items.Count - 1 do
begin
// Determine Right edge
OutRect.Right := OutRect.Left + longint(Items.Objects[i]);
// Print the line
recPrintStrGrid.PrCanvas.TextRect(OutRect, OutRect.Left, OutRect.Top, Items[i]);
// Adjust right edge
OutRect.Left := OutRect.Right;
// The code below prints vertical column lines but does leaves a space between lines of print, ugly
//recPrintStrGrid.PrCanvas.Brush.Color := clBlack;
//if recPrintStrGrid.bBorderFlag then recPrintStrGrid.PrCanvas.FrameRect(OutRect);
//recPrintStrGrid.PrCanvas.Brush.Style := bsClear;
end
;
//As each line prints, AmountPrinted must increase to reflect how much of a page has been printed
//recPrintStrGrid.AmountPrinted := recPrintStrGrid.AmountPrinted + (recPrintStrGrid.tenthsOfInchPixelsY * 2);
recPrintStrGrid.amountPrinted := recPrintStrGrid.amountPrinted + recPrintStrGrid.lineHeight + recPrintStrGrid.tenthsOfInchPixelsY;
end
;
// inline proc
procedure PrintTitle(var recPrintStrGrid: RRecPrintStrGrid; title: string);
begin
if (title = '') then exit;
recPrintStrGrid.PrCanvas.Font := recPrintStrGrid.ftTitleFont;
recPrintStrGrid.PrCanvas.TextOut((Printer.PageWidth div 2) -
(recPrintStrGrid.PrCanvas.TextWidth(title) div 2),0,title);
recPrintStrGrid.PrCanvas.Font := recPrintStrGrid.ftDataFont;
// Increment amount printed
recPrintStrGrid.amountPrinted := recPrintStrGrid.amountPrinted + recPrintStrGrid.lineHeight + recPrintStrGrid.tenthsOfInchPixelsY;
end
;
// inline proc
procedure PrintReportHeader(var recPrintStrGrid: RRecPrintStrGrid; header: string);
var
headerLines: TCStringList;
i: integer;
abbrevFilePath: string;
begin
// expecting header to be a endl-delimited string created by TFormOutputStats.textHeader()
if (header = '') then exit;
headerLines := TCStringList.Create();
recPrintStrGrid.PrCanvas.Font := recPrintStrGrid.ftDataFont; // no special formatting
try
headerLines.explode(header, #13); // the #10 of endl(#13#10) is trimmed away by explode
for i := 0 to headerLines.Count-1 do
begin
// The path and file name can exceed the printer page width, and the file name would be lost
if ( pos('## Scenario file:', headerLines.Strings[i]) > 0 ) then
begin
if (100 > length(headerLines.Strings[i])) then // not sure how many characters to consider is best
recPrintStrGrid.PrCanvas.TextOut(0,recPrintStrGrid.amountPrinted,headerLines.Strings[i])
else
begin
abbrevFilePath := leftstr(headerLines.Strings[i], 17) + ' ... ' + rightstr(headerLines.Strings[i],78);
recPrintStrGrid.PrCanvas.TextOut(0,recPrintStrGrid.amountPrinted,abbrevFilePath)
end
;
end
else // some other line in the header other than the scenario file path
recPrintStrGrid.PrCanvas.TextOut(0,recPrintStrGrid.amountPrinted,headerLines.Strings[i]);
// Increment amount printed for every line in the header
recPrintStrGrid.amountPrinted := recPrintStrGrid.amountPrinted + recPrintStrGrid.lineHeight + recPrintStrGrid.tenthsOfInchPixelsY;
end
;
finally
headerLines.Free;
end;
end
;
// inline proc
procedure PrintColumnNames(var ColNames: TStringList; var recPrintStrGrid: RRecPrintStrGrid );
begin
recPrintStrGrid.PrCanvas.Font := recPrintStrGrid.ftHeadingFont;
PrintRow(ColNames, recPrintStrGrid);
recPrintStrGrid.PrCanvas.Font := recPrintStrGrid.ftDataFont
end
;
var
recPrintStrGrid: RRecPrintStrGrid;
iLoop, jLoop, width, pageNum: integer;
colWidth: array of integer; // the number of pixels needed for each column of the grid
colNames: TStringList; // the header row of column names and column widths
dataLine: TStringList; // contents of a row cells and their column widths
FXScale: double; // factor to adjust for the diffences in horizonatal pixel size between screen and printer
timeStamp, title: string; // info for the print title
printWidth: integer; // width of the info being set to the printer
const
COLSPACER: integer = 50; // 50 maintains portrait orientation for the summary output statistics grid
begin
recPrintStrGrid.amountPrinted := 0;
colNames := TStringList.Create();
dataLine := TStringList.Create();
try
// Set up print options
with recPrintStrGrid do
begin
PrCanvas := printer.Canvas;
sGrid := self.stgGrid;
sTitle := pageTitle;
bPrintFlag := true;
ptXYOffset.X := 10;
ptXYOffset.Y := 100;
bBorderFlag := True;
ftTitleFont := TFont.Create();
with ftTitleFont do
begin
Name := 'Arial';
Style := []; //fsBold
Size := 8;
end
;
ftHeadingFont := TFont.Create();
with ftHeadingFont do
begin
Name := 'Arial';
Style := [fsUnderline];
Size := 8;
end
;
ftDataFont := TFont.Create();
with ftDataFont do
begin
Name := 'Arial';
Style := [];
Size := 8;
end
;
// base line height on text height of currently rendered font
Font := ftDataFont;
tenthsOfInchPixelsY := GetDeviceCaps(Printer.Handle, LOGPIXELSY) div 10;
lineHeight := PrCanvas.TextHeight('X') + tenthsOfInchPixelsY;
end
;
// Account for difference of pixel size between screen (grid cell contents) and printer
//http://stackoverflow.com/questions/3100895/scaling-pixelvalues-for-printing
FXScale := (GetDeviceCaps(Printer.Handle, LOGPIXELSX)/96) -
((2-(GetDeviceCaps(Printer.Handle, HORZRES)*2) /
GetDeviceCaps(Printer.Handle, PHYSICALWIDTH)));
recPrintStrGrid.amountPrinted := recPrintStrGrid.tenthsOfInchPixelsY * 2;
pageNum := 1;
timeStamp := FormatDateTime('c', Now);
// Determine the maximum width (as pixels) of each column in the grid
setLength( colWidth, recPrintStrGrid.sGrid.ColCount );
for iLoop := 0 to recPrintStrGrid.sGrid.ColCount - 1 do
colWidth[iLoop] := round(COLSPACER * FXScale);
;
for iLoop := 0 to recPrintStrGrid.sGrid.ColCount - 1 do
begin
for jLoop := 0 to recPrintStrGrid.sGrid.RowCount -1 do
begin
if( round((recPrintStrGrid.PrCanvas.textWidth( recPrintStrGrid.sGrid.Cells[iLoop, jLoop] )* FXScale)) > colWidth[iLoop] ) then
colWidth[iLoop] := round(recPrintStrGrid.PrCanvas.textWidth( recPrintStrGrid.sGrid.Cells[iLoop, jLoop]) * FXScale) + COLSPACER
;
end
;
end
;
// Calculate total width of the grid, based on the widest member of each column
printWidth := 0;
for iLoop := 0 to recPrintStrGrid.sGrid.ColCount - 1 do
printWidth := printWidth + colWidth[iLoop]
;
// If the grid contents print width is greater than the printer page width go to landscape mode
if recPrintStrGrid.bPrintFlag then
if ( printWidth > Printer.PageWidth ) then Printer.Orientation := poLandscape;
// Create a header row of column names, here assuming that the first row of the grid
// always has a header row (maybe re-visit this assumption)
for iLoop := 0 to recPrintStrGrid.sGrid.ColCount - 1 do
begin
// Store each column header name and the width (pixels) of the column
width := colWidth[iLoop];
ColNames.AddObject( recPrintStrGrid.sGrid.Cells[iLoop, 0] , pointer( width ));
end
;
with recPrintStrGrid, PrCanvas do
begin
//Initialize Printer
if bPrintFlag then
begin
Printer.Title := sTitle;
Printer.BeginDoc;
end
;
// sTitle may often be an empty string, but it doesn't matter
title := recPrintStrGrid.sTitle + ' ' + timeStamp + ' ' + 'page ' + intToStr(pageNum);
if bPrintFlag then
begin
if (reportHeader <> '') then // print only at the top of the 1st page
PrintReportHeader(recPrintStrGrid, reportHeader)
else
PrintTitle( recPrintStrGrid, title );
end
;
PrintColumnNames( colNames, recPrintStrGrid ); // always do this once
for iLoop := 1 to sGrid.RowCount-1 do // skip header row
begin
for jLoop := 0 to sGrid.ColCount-1 do
begin
width := colWidth[jLoop];
dataLine.AddObject(sGrid.Cells[jLoop, iLoop], pointer(width));
end
;
PrintRow(dataLine, recPrintStrGrid);
dataLine.Clear;
// Force print job to begin a new page if printed output has exceeded page height
if bPrintFlag then
begin
if ( (amountPrinted + lineHeight) > Printer.PageHeight ) then
begin
amountPrinted := tenthsOfInchPixelsY * 2;
inc(pageNum);
Printer.NewPage;
title := sTitle + ' ' + timeStamp + ' ' + 'page ' + intToStr(pageNum);
PrintTitle( recPrintStrGrid, title );
PrintColumnNames( colNames, recPrintStrGrid ); // do this again at top of each page
end
;
end
;
end // for row loop
;
if bPrintFlag then
begin
Printer.EndDoc;
Printer.Orientation := poPortrait;
end
;
end // with recPrintStrGrid, prCanvas
;
finally
//clean up
setLength( colWidth, 0 );
recPrintStrGrid.ftTitleFont.free();
recPrintStrGrid.ftHeadingFont.free();
recPrintStrGrid.ftDataFont.free();
colNames.Free;
dataLine.Free;
end;
end
;
{*
Debugging method that sends the value of ARow to the debug output window
@param Sender a grid object referencing this method in OnSelectCell event handler
@param ACol grid column number
@param ARow grid row number
@param CanSelect ?
@comment It looks like this method is not fully implemented ...
}
procedure TFrameStringGridBase.stgGridSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
begin
dbcout( 'Row selected: ' + intToStr( ARow ), true );
end
;
{*
Bug fix for limitation of base component in Delphi 7.
This avoids a runtime "Grid index out of range." error if the user
enters the grid by clicking a fixed column and then mouse-wheels.
@param Sender a grid object referencing this method in OnEnter event handler
}
procedure TFrameStringGridBase.stgGridEnter(Sender: TObject);
begin
{
This avoids a runtime "Grid index out of range." error if the user
enters the grid by clicking a fixed column and then mouse-wheels.
The problem is that cells in a fixed column can not be selected, so
the component has focus but Col and Row = -1. Using the mouse wheel
fires TGrid's current() where a check is done. If the current position is
-1 it raises a EInvalidGridOperation error. Setting selection avoids the error.
Using FixedRows and FixedCols counts for the rectangle coordinates selects the upper
left most data cell and the remaining cells of that row, no matter how many fixed rows or columns are used.
}
if (stgGrid.Col = -1) then
begin
stgGrid.Selection := TGridRect(Rect(stgGrid.FixedCols,stgGrid.FixedRows,(stgGrid.ColCount - stgGrid.FixedCols),stgGrid.FixedRows));
end
;
end
;
end. |
unit cActions;
interface
uses Action, cScavenge;
type
TActions = class
Protected
FTime: TDateTime;
FAction: IAction;
FStatus: String;
FPriority: String;
Public
property time: TDateTime read FTime;
property Action: IAction read FAction;
property status: String read FStatus;
property priority: String read FPriority;
procedure executeAction();
Constructor Create(time: TDateTime; Action: String; priority: String);
end;
implementation
uses StrUtils;
constructor TActions.Create(time: TDateTime; Action: String; priority: String);
begin
self.FTime := time;
if (Action = 'Scavenge') then
FAction := TScavenge.Create;
FStatus := 'waiting';
FPriority := priority;
end;
procedure TActions.executeAction();
begin
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.