text stringlengths 14 6.51M |
|---|
unit UnitUsuario;
interface
uses System.SysUtils, System.Variants,
System.Classes, Data.DB, UnitCuentaDebito, UnitCuentaCredito;
type
TUsuario = class
public
idUsuario : integer;
nombres: string;
apellidoPaterno: string;
apellidoMaterno: string;
claveElector: string;
correoElectronico: string;
telefono: string;
contrasenia: string;
tipo: integer;
nombreCompleto : string;
function getCuentaCredito : TCuentaCredito;
function getCuentaDebito : TCuentaDebito;
function getNombreCompleto : string;
end;
var
usuario: TUsuario;
cuentaDebito : TCuentaDebito;
cuentaCredito : TCuentaCredito;
implementation
uses DataModuleDani, FireDAC.Stan.Param;
function TUsuario.getCuentaCredito : TCuentaCredito;
begin
with DataModuleDaniBD.CuentacreditoTable do
begin
cuentaCredito := TCuentaCredito.Create;
Prepare;
ParamByName('idUsuario').AsInteger := idUsuario;
Open;
Refresh;
First;
while not EOF do
begin
cuentaCredito.estadoCuenta := FieldByName('estadoCuenta').AsString;
cuentaCredito.deudaTotal := FieldByName('deudaTotal').AsCurrency;
cuentaCredito.idClienteCuenta := FieldByName('id_cliente_cuenta').AsInteger;
cuentaCredito.idCuentaCredito := FieldByName('id_cuenta_credito').AsInteger;
cuentaCredito.numeroDeCuenta := FieldByName('numeroDeCuenta').AsString;
Next;
end;
Result := cuentaCredito;
end;
end;
function TUsuario.getCuentaDebito : TCuentaDebito;
begin
with DataModuleDaniBD.CuentaDebitoTable do
begin
cuentaDebito := TCuentaDebito.Create;
Prepare;
ParamByName('idUsuario').AsInteger := idUsuario;
Open;
Refresh;
First;
while not EOF do
begin
cuentaDebito.estadoCuenta := FieldByName('estadoCuenta').AsString;
cuentaDebito.saldo := FieldByName('saldo').AsCurrency;
cuentaDebito.idClienteCuenta := FieldByName('id_cliente_cuenta').AsInteger;
cuentaDebito.idCuentaDebito := FieldByName('id_cuenta_debito').AsInteger;
cuentaDebito.numeroDeCuenta := FieldByName('numeroDeCuenta').AsString;
Next;
end;
Result := cuentaDebito;
end;
end;
function TUsuario.getNombreCompleto: string;
begin
nombreCompleto := nombres + ' ' + apellidoPaterno + ' ' + apellidoMaterno;
Result := nombreCompleto;
end;
end.
|
{===============================================================================
常量单元
===============================================================================}
unit xConsts;
interface
uses System.SysUtils, IniFiles;
const
/// <summary>
/// 回复类型
/// </summary>
C_REPLY_NORESPONSE = -1; // 未返回
C_REPLY_CS_ERROR = 1; // 校验位错误
C_REPLY_CORRECT = 2; // 返回数据正确
C_REPLY_PACK_ERROR = 4; // 数据包错误
C_REPLY_CODE1_ERROR = 5; // 设备码1错误
C_REPLY_CODE2_ERROR = 6; // 设备码2错误
var
{-------------项目信息-----------------}
C_SYS_COMPANY : string= '****公司';
C_SYS_WEB : string= '';
C_SYS_OBJECT_MODEL : string= '****型号';
C_SYS_OBJECT_NAME : string= '****系统';
{-------------权限信息-----------------}
/// <summary>
/// 是否是调试模式
/// </summary>
bPubIsAdmin : Boolean = False;
{-------------公共信息-----------------}
/// <summary>
/// 程序路径+名称
/// </summary>
sPubExePathName : string;
/// <summary>
/// 程序文件夹路径
/// </summary>
spubFilePath : string;
/// <summary>
/// INI文件名称
/// </summary>
sPubIniFileName : string;
/// <summary>
/// 软件信息INI文件名称
/// </summary>
sPubSysIniFileName : string;
implementation
initialization
sPubExePathName := ParamStr(0);
spubFilePath := ExtractFilePath(sPubExePathName);
sPubIniFileName := ChangeFileExt( sPubExePathName, '.ini' );
sPubSysIniFileName := spubFilePath + 'Config.ini';
if sPubSysIniFileName <> '' then
begin
with TIniFile.Create(sPubSysIniFileName) do
begin
C_SYS_COMPANY := ReadString('System', 'Company', '****公司');
C_SYS_WEB := ReadString('System', 'Web', '');
C_SYS_OBJECT_MODEL := ReadString('System', 'ObjectModel', '****型号');
C_SYS_OBJECT_NAME := ReadString('System', 'ObjectName', '****系统');
bPubIsAdmin := ReadBool('System', 'IsAdmin', False);
free;
end;
end;
finalization
if sPubSysIniFileName <> '' then
begin
with TIniFile.Create(sPubSysIniFileName) do
begin
WriteString('System', 'Company', C_SYS_COMPANY);
WriteString('System', 'Web', C_SYS_WEB);
WriteString('System', 'ObjectModel', C_SYS_OBJECT_MODEL);
WriteString('System', 'ObjectName', C_SYS_OBJECT_NAME);
WriteBool('System', 'IsAdmin', bPubIsAdmin);
free;
end;
end;
end.
|
unit JetCommon;
(*
Contains common procedures for printing/converting stuff
*)
interface
function VarIsNil(val: OleVariant): boolean;
function str(val: OleVariant): WideString;
function arr_str(val: OleVariant): WideString;
function int(val: OleVariant): integer;
function uint(val: OleVariant): int64;
function bool(val: OleVariant): boolean;
function includes(main, flag: cardinal): boolean;
(*
Previous section is closed automatically when a new one is declared.
If you need to close manually, call EndSection.
*)
procedure Section(SectionName: string);
procedure Subsection(SectionName: string);
procedure EndSection;
procedure EndSubsection;
implementation
uses Variants;
function VarIsNil(val: OleVariant): boolean;
begin
Result := VarIsClear(val) or VarIsNull(val);
end;
function str(val: OleVariant): WideString;
begin
if VarIsNil(val) then
Result := ''
else begin
Result := string(val);
end;
end;
//То же, что str(), но форматирует и массивы
function arr_str(val: OleVariant): WideString;
var i: integer;
begin
if not VarIsArray(val) then begin
Result := str(val);
exit;
end;
if Length(val) > 0 then
Result := arr_str(val[0])
else
Result := '';
for i := 1 to Length(val) - 1 do
Result := Result + ', ' + arr_str(val[i]);
Result := '(' + Result + ')';
end;
function int(val: OleVariant): integer;
begin
if VarIsNil(val) then
Result := 0
else Result := integer(val);
end;
function uint(val: OleVariant): int64;
begin
if VarIsNil(val) then
Result := 0
else Result := val;
end;
function bool(val: OleVariant): boolean;
begin
if VarIsNil(val) then
Result := false
else Result := boolean(val);
end;
function includes(main, flag: cardinal): boolean;
begin
Result := (main and flag) = flag;
end;
var
InSection: boolean = false;
InSubSection: boolean = false;
procedure Section(SectionName: string);
begin
if InSection then
EndSection;
writeln(SectionName);
writeln('=========================================');
InSection := true;
end;
procedure SubSection(SectionName: string);
begin
if InSubsection then
EndSubsection;
writeln('== ' + SectionName);
InSubsection := true;
end;
procedure EndSection;
begin
if InSection then begin
writeln('');
writeln('');
end else
if InSubsection then
EndSubsection;
InSubsection := false;
InSection := false;
end;
procedure EndSubsection;
begin
if InSubsection then
writeln('');
InSubsection := false;
end;
end.
|
unit ClassWords;
interface
const IS_WORD_FLAG = 32;
LAST_FLAG = 64;
HAS_CHILD_FLAG = 128;
CHAR_MASK = 31;
END_OF_WORDS = 'END OF WORDS';
type TWordsCallback = function( Word : string ) : boolean of object;
TWordsStr = array of string;
TWords = class
private
FFileName : string;
FCallback : TWordsCallback;
FWords : array of string;
FEndSearch : boolean;
procedure UnpackWords( var F : File; Word : string );
procedure GetAllWords( Callback : TWordsCallback );
function FindWord( Word : string ) : boolean;
public
constructor Create( FileName : string );
destructor Destroy; override;
procedure ExistWords( Words : array of string; var Result : TWordsStr );
procedure AllWords( Callback : TWordsCallback );
end;
implementation
uses Forms, Controls, Windows;
//==============================================================================
// Constructor / destructor
//==============================================================================
constructor TWords.Create( FileName : string );
begin
inherited Create;
FFileName := FileName;
FCallback := nil;
FWords := nil;
FEndSearch := false;
end;
destructor TWords.Destroy;
begin
inherited;
end;
//==============================================================================
// P R I V A T E
//==============================================================================
procedure TWords.UnpackWords( var F : File; Word : string );
var B : byte;
C : char;
Last : boolean;
Chars : array of record
C : char;
HasChildren : boolean;
end;
I : integer;
begin
if (FEndSearch) then
exit;
Last := false;
SetLength( Chars , 0 );
repeat
BlockRead( F , B , 1 );
C := char((B and CHAR_MASK) + Ord( 'a' ));
SetLength( Chars , Length( Chars )+1 );
Chars[Length( Chars )-1].C := C;
if ((B and HAS_CHILD_FLAG) <> 0) then
Chars[Length( Chars )-1].HasChildren := true
else
Chars[Length( Chars )-1].HasChildren := false;
if ((B and IS_WORD_FLAG) <> 0) then
if (Assigned( FCallback )) then
if (FCallback( Word + C )) then
FEndSearch := true;
if ((B and LAST_FLAG) <> 0) then
Last := true;
until Last;
for I := 0 to Length( Chars )-1 do
if (Chars[I].HasChildren) then
UnpackWords( F , Word + Chars[I].C );
end;
procedure TWords.GetAllWords( Callback : TWordsCallback );
var F : File;
begin
FCallback := Callback;
if (not Assigned( FCallback )) then
exit;
AssignFile( F , FFileName );
Reset( F , 1 );
FEndSearch := false;
UnpackWords( F , '' );
FCallback( END_OF_WORDS );
CloseFile( F );
end;
function TWords.FindWord( Word : string ) : boolean;
var I : integer;
begin
Result := true;
for I := 0 to Length( FWords )-1 do
if (FWords[I] = Word) then
FWords[I] := ''
else
if (FWords[I] <> '') then
Result := false;
end;
//==============================================================================
// P U B L I C
//==============================================================================
procedure TWords.ExistWords( Words : array of string; var Result : TWordsStr );
var I, J : integer;
C : TCursor;
begin
C := Screen.Cursor;
Screen.Cursor := crHourglass;
try
if (Length( Words ) = 0) then
begin
SetLength( Result , 0 );
exit;
end;
SetLength( FWords , Length( Words ) );
for I := 0 to Length( Words )-1 do
begin
SetLength( FWords[I] , Length( Words[I] ) );
FWords[I] := Words[I];
end;
FEndSearch := false;
GetAllWords( FindWord );
J := 0;
for I := 0 to Length( FWords )-1 do
if (FWords[I] <> '') then
Inc( J );
SetLength( Result , J );
J := 0;
for I := 0 to Length( FWords )-1 do
if (FWords[I] <> '') then
begin
SetLength( Result[J] , Length( FWords[I] ) );
Result[J] := FWords[I];
Inc( J );
end;
finally
Screen.Cursor := C;
end;
end;
procedure TWords.AllWords( Callback : TWordsCallback );
var C : TCursor;
begin
if (not Assigned( Callback )) then
exit;
C := Screen.Cursor;
Screen.Cursor := crHourglass;
try
GetAllWords( Callback );
finally
Screen.Cursor := C;
end;
end;
end.
|
unit MobileDays.ListVertFrame.Mobile.View.Person.ItemList;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
MobileDays.ListVertFrame.Mobile.View.ItemList.Model, FMX.Objects, FMX.Layouts,
FMX.Controls.Presentation,
System.UIConsts;
type
TFilPerson = class(TFrmItemListModel)
lblId: TLabel;
lytInfo1: TLayout;
lblName: TLabel;
lblEmail: TLabel;
lblBirthday: TLabel;
rctGender: TRectangle;
lytImgPerfil: TLayout;
imgPerfil: TImage;
procedure lytBackgroundPainting(Sender: TObject; Canvas: TCanvas;
const ARect: TRectF);
private
FLastName: string;
FEmail: string;
FImageUrl: string;
FBirthday: TDate;
FGender: string;
FId: Integer;
FFirstName: string;
procedure SetBirthday(const Value: TDate);
procedure SetEmail(const Value: string);
procedure SetFirstName(const Value: string);
procedure SetGender(const Value: string);
procedure SetId(const Value: Integer);
procedure SetImageUrl(const Value: string);
procedure SetLastName(const Value: string);
procedure ShowImage;
{ Private declarations }
public
property Id: Integer read FId write SetId;
property FirstName: string read FFirstName write SetFirstName;
property LastName: string read FLastName write SetLastName;
property Birthday: TDate read FBirthday write SetBirthday;
property Email: string read FEmail write SetEmail;
property Gender: string read FGender write SetGender;
property ImageUrl: string read FImageUrl write SetImageUrl;
procedure ShowValues;
{ Public declarations }
end;
var
FilPerson: TFilPerson;
implementation
uses
MobileDays.ListVertFrame.Mobile.Controller.SMImage;
{$R *.fmx}
{ TFilPerson }
procedure TFilPerson.lytBackgroundPainting(Sender: TObject; Canvas: TCanvas;
const ARect: TRectF);
begin
inherited;
if lytBackground.Tag <> 0 then
Exit;
lytBackground.Tag := 1;
ShowValues;
end;
procedure TFilPerson.SetBirthday(const Value: TDate);
begin
FBirthday := Value;
end;
procedure TFilPerson.SetEmail(const Value: string);
begin
FEmail := Value;
end;
procedure TFilPerson.SetFirstName(const Value: string);
begin
FFirstName := Value;
end;
procedure TFilPerson.SetGender(const Value: string);
begin
FGender := Value;
end;
procedure TFilPerson.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TFilPerson.SetImageUrl(const Value: string);
begin
FImageUrl := Value;
end;
procedure TFilPerson.SetLastName(const Value: string);
begin
FLastName := Value;
end;
procedure TFilPerson.ShowImage;
begin
TThread.CreateAnonymousThread(
procedure
var
LPath: string;
begin
try
LPath := TSMImage.ShowImage('Person_' + FId.ToString + '.jpg', FImageUrl);
if FileExists(LPath) then
begin
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
imgPerfil.Bitmap.LoadFromFile(LPath);
end);
end;
finally
TThread.Synchronize(TThread.CurrentThread,
procedure
begin
lytImgPerfil.Visible := imgPerfil.Bitmap.Width > 0;
end);
end;
end).Start;
end;
procedure TFilPerson.ShowValues;
begin
lblId.Text := FId.ToString;
lblName.Text := FFirstName + ' ' + FLastName;
lblEmail.Text := FEmail;
lblBirthday.Text := FormatDateTime('yyyy-mm-dd', FBirthday);
if FGender.Equals('M') then
rctGender.Fill.Color := StringToAlphaColor('Indigo')
else if FGender.Equals('F') then
rctGender.Fill.Color := StringToAlphaColor('Firebrick')
else
rctGender.Fill.Color := StringToAlphaColor('Gray');
ShowImage;
end;
end.
|
unit Test.Devices.TRM138.ReqCreator;
interface
uses Windows, TestFrameWork, GMGlobals, Test.Devices.Base.ReqCreator, GMConst;
type
TTRM138ReqCreatorTest = class(TDeviceReqCreatorTestBase)
protected
function GetDevType(): int; override;
procedure DoCheckRequests(); override;
end;
implementation
{ TTRM138ReqCreatorTest }
procedure TTRM138ReqCreatorTest.DoCheckRequests;
begin
CheckReqString(0, '#GMHGONOKTRLT'#$D);
CheckReqString(1, '#GNHGONOKUHQJ'#$D);
CheckReqString(2, '#GOHGONOKHTVU'#$D);
CheckReqString(3, '#GPHGONOKINGG'#$D);
CheckReqString(4, '#GQHGONOKMOGI'#$D);
CheckReqString(5, '#GRHGONOKLIVS'#$D);
CheckReqString(6, '#GSHGONOKVMGM'#$D);
CheckReqString(7, '#GTHGONOKSSVO'#$D);
end;
function TTRM138ReqCreatorTest.GetDevType: int;
begin
Result := DEVTYPE_TRM138;
end;
initialization
RegisterTest('GMIOPSrv/Devices/TRM138', TTRM138ReqCreatorTest.Suite);
end.
|
unit BaseNodeReader;
interface
uses GMGlobals, Generics.Collections;
type
TBaseNodeReader = class
FReadResults: TList <TVTNodeData>;
public
constructor Create;
destructor Destroy; override;
property ReadResult: TList <TVTNodeData> read FReadResults;
procedure ReadChildren(ID_Node: int); virtual; abstract;
procedure AddNew(ID_Parent: int; p: PVTNodeData); virtual; abstract;
procedure NewCaption(p: PVTNodeData); virtual; abstract;
procedure Delete(p: PVTNodeData); virtual; abstract;
end;
TBaseNodeReaderClass = class of TBaseNodeReader;
implementation
{ TBaseNodeReader }
constructor TBaseNodeReader.Create;
begin
inherited;
FReadResults := TList<TVTNodeData>.Create();
end;
destructor TBaseNodeReader.Destroy;
begin
FReadResults.Free();
inherited;
end;
end.
|
unit EngLangRes;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
resourcestring
msgConfirmDelete = 'Are you sure you want to delete the script named';
msgFormatNotRecognisedTitle = 'File format not recognised';
msgFormatNotRecognised = 'Sorry, unable to recognise that particular filetype!';
msgFormatNotRecognisedTryToLoad = 'Do you want to try and load it as a text file anyway?';
msgImageFormatNotSupported = 'Sorry, image type not supported';
msgExecutionError = 'Execution Error: Something went wrong executing script!';
msgErrorCompiling = 'Error compiling:';
msgClpbrdFrmtNotSpprtdForScriptsTitle = 'Clipboard format not supported for scripts!';
msgClpbrdFrmtNotSpprtdForScripts = 'Sorry, the clipboard contains data of a format that is currently unsupported for using with a script!';
msgClipboardCleared = 'Clipboard cleared!';
msgAllFiles = 'All files (*.*)|*.*';
msgLoadFileTitle = 'Load a file to the clipboard...';
msgLoadFiles = 'Text files (*.txt, *.csv, *.tab)|*.TXT;*.CSV;*.TAB|Images (*.bmp, *.jpg, *.png)|*.BMP;*.JPG;*.PNG;|All Files (*.*)|*.*';
msgScriptExecutedTitle = 'Clipman script "';
msgScriptExecutedSuccess = '" executed ok!';
msgSaveImgClipboardTitle = 'Save image on clipboard as...';
msgSaveImgClipboardFilter = 'Bitmap images (*.bmp)|*.BMP|JPEG Images (*.jpg)|*.JPG|Portable Network Graphic Image (*.png)|*.PNG|[Experimental] 256 Color Bitmap (*.bmp)|*.bmp|X Pixmap File (*.xpm)|*.XPM';
msgSaveTxtClipboardTitle = 'Save text on clipboard as...';
msgSaveTxtClipboardFilter = 'Text files (*.txt)|*.TXT|CSV Files (*.csv)|*.CSV|Tab Files (*.tab)|*.TAB';
msgScriptAlreadyExists = 'A script with this name already exists!';
msgAboutMessageLine1 = 'Written by TheBlackSheep using FreePascal && Lazarus ';
msgAboutMessageLine2 = 'as a demonstration of some of the components and to ';
msgAboutMessageLine3 = 'make something useful for all Pascal developers ';
msgAboutMessageLine4 = '(and other geeks) out there!';
msgAboutCreditsLine1 = 'Credits go to;';
msgAboutCreditsLine2 = ' the Awesome FPC/Lazarus team';
msgAboutCreditsLine3 = ' PilotLogic for CodeTyphon';
msgAboutCreditsLine4 = ' Carlo Kok (RemObjects) for the Open Source PascalScript';
msgAboutCreditsLine5 = ' && the excellent SynEditor components';
msgAboutUseLine1 = 'Free for all uses!';
msgAboutUseLine2 = 'Please make suggestions for improvements!';
implementation
end.
|
unit uGLObjects;
interface
uses
Windows, Classes, Contnrs, Graphics, OpenGL, uPlImagePluginInterface;
type
TGLStimTexture = class(TObject)
private
FImage: HIMAGE;
FTexName: GLuint;
procedure SetImage(const Value: HIMAGE);
procedure SetTexName(const Value: GLuint);
public
property TexName: GLuint read FTexName write SetTexName;
property Image: HIMAGE read FImage write SetImage;
end;
TGLContainer = class(TObject)
private
FDC: HDC;
FRC: HGLRC;
FStimTexList: TObjectList;
function GetImageRect(AGraphic: TGraphic): TRect;
procedure SwapRGBtoBGR(pData: PByte; pDataLength: Integer; BitCount: Integer);
procedure SetDC(const Value: HDC);
procedure SetRC(const Value: HGLRC);
function GetStimTexture(index: Integer): TGLStimTexture;
function GetStimTexturesCount: Integer;
public
constructor Create(ADC: HDC; ARC: HGLRC);
destructor Destroy; override;
procedure RemoveAllTextures;
procedure RemoveTexture(AStimTex: TGLStimTexture);
procedure RemoveTextureByImage(AImage: HImage);
function GetStimTexByImage(AImage: HImage): TGLStimTexture;
function AddNewTexture(AImage: HImage; AGraphic: TGraphic): TGLStimTexture;
property DC: HDC read FDC write SetDC;
property RC: HGLRC read FRC write SetRC;
property StimTexture[index: Integer]: TGLStimTexture read GetStimTexture;
property StimTexturesCount: Integer read GetStimTexturesCount;
end;
procedure glBindTexture (target: GLenum; texture: GLuint); stdcall; external opengl32;
procedure glGenTextures (n: GLsizei; textures: PGLuint); stdcall; external opengl32;
procedure glDeleteTextures (n: GLsizei; const textures: PGLuint); stdcall; external opengl32;
implementation
{ TGLContainer }
function TGLContainer.AddNewTexture(AImage: HImage;
AGraphic: TGraphic): TGLStimTexture;
const
w = 128;
h = 128;
var
i: Integer;
bmp: TBitmap;
texName: GLuint;
pData, p: PByte;
begin
Result := nil;
if wglMakeCurrent(FDC, FRC) then
begin
bmp := TBitmap.Create;
GetMem(pData, w * h * 3);
p := pData;
try
bmp.Width := w;
bmp.Height := h;
bmp.PixelFormat := pf24bit;
bmp.Canvas.Brush.Color := clLtGray;
bmp.Canvas.FillRect(Rect(0, 0, w, h));
bmp.Canvas.StretchDraw(GetImageRect(AGraphic), AGraphic);
bmp.Canvas.Pen.Color := clGray;
bmp.Canvas.MoveTo(1, 1);
bmp.Canvas.LineTo(w - 1, 1);
bmp.Canvas.LineTo(w - 1, h - 1);
bmp.Canvas.LineTo(1, h - 1);
bmp.Canvas.LineTo(1, 1);
i := 0;
while i < h do
begin
Move(bmp.ScanLine[i]^, p^, w * 3);
inc(p, w * 3);
inc(i);
end;
SwapRGBtoBGR(pData, w * h * 3, 24);
glGenTextures(1,@texName);
glBindTexture(GL_TEXTURE_2D,texName);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, 3, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, pData);
glBindTexture(GL_TEXTURE_2D, 0);
Result := TGLStimTexture.Create;
Result.FTexName := texName;
Result.Image := AImage;
FStimTexList.Add(Result);
finally
bmp.Free;
FreeMem(pData, w * h * 3)
end;
end;
end;
constructor TGLContainer.Create(ADC: HDC; ARC: HGLRC);
begin
FStimTexList := TObjectList.Create(True);
FRC := ARC;
FDC := ADC;
end;
procedure TGLContainer.RemoveAllTextures;
var
i: Integer;
begin
if wglMakeCurrent(FDC, FRC) then
begin
i := 0;
while (i < StimTexturesCount) do
begin
glDeleteTextures(1, @StimTexture[i].TexName);
inc(i);
end;
end;
FStimTexList.Clear;
end;
procedure TGLContainer.RemoveTexture(AStimTex: TGLStimTexture);
begin
if wglMakeCurrent(FDC, FRC) then
begin
glDeleteTextures(1, @AStimTex.TexName);
end;
FStimTexList.Remove(AStimTex);
end;
procedure TGLContainer.RemoveTextureByImage(AImage: HImage);
var
st: TGLStimTexture;
begin
st := GetStimTexByImage(AImage);
if st <> nil then
begin
if wglMakeCurrent(FDC, FRC) then
begin
glDeleteTextures(1, @st.TexName);
end;
FStimTexList.Remove(st);
end;
end;
destructor TGLContainer.Destroy;
begin
RemoveAllTextures;
FStimTexList.Free;
end;
function TGLContainer.GetImageRect(AGraphic: TGraphic): TRect;
const
w = 128;
h = 128;
var
k: Double;
begin
Result := Rect(0, 0, 0 ,0);
if (AGraphic <> nil) and
(AGraphic.Width <> 0) and
(AGraphic.Height <> 0) then
begin
k := AGraphic.Height / AGraphic.Width;
if k > 1 then
begin
Result.Top := 0;
Result.Bottom := h;
Result.Left := Trunc((w - h / k) / 2);
Result.Right := Trunc((w + h / k) / 2);
end
else
begin
Result.Left := 0;
Result.Right := w;
Result.Top := Trunc((h - w * k) / 2);
Result.Bottom := Trunc((h + w * k) / 2);
end;
end;
end;
function TGLContainer.GetStimTexByImage(AImage: HImage): TGLStimTexture;
var
i: Integer;
begin
Result := nil;
i := 0;
while (Result = nil) and (i < StimTexturesCount) do
begin
if StimTexture[i].Image = AImage then
Result := StimTexture[i];
inc(i);
end;
end;
function TGLContainer.GetStimTexture(index: Integer): TGLStimTexture;
begin
Result := TGLStimTexture(FStimTexList.Items[index]);
end;
function TGLContainer.GetStimTexturesCount: Integer;
begin
Result := FStimTexList.Count;
end;
procedure TGLContainer.SetDC(const Value: HDC);
begin
FDC := Value;
end;
procedure TGLContainer.SetRC(const Value: HGLRC);
begin
FRC := Value;
end;
procedure TGLContainer.SwapRGBtoBGR(pData: PByte; pDataLength: Integer; BitCount: Integer);
var
step: Integer;
pR, pB: PByte;
R: Byte;
begin
case BitCount of
24, 32:
begin
step := BitCount div 8;
pR := pData;
pB := pR;
inc(pB, 2);
while Integer(pB) < (Integer(pData) + pDataLength) do
begin
R := pR^;
pR^ := pB^;
pB^ := R;
inc(pR, step);
inc(pB, step);
end;
end;
end;
end;
{ TGLStimTexture }
procedure TGLStimTexture.SetImage(const Value: HIMAGE);
begin
FImage := Value;
end;
procedure TGLStimTexture.SetTexName(const Value: GLuint);
begin
FTexName := Value;
end;
end.
|
unit GC.LaserCutBoxes.Test.Sides;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testutils, testregistry,
GC.LaserCutBoxes.Box.Sides;
type
{ TSideTest }
TSideTest = class(TTestCase)
private
FSide: TLaserCutBoxSide;
protected
published
procedure TestSideCreate;
end;
implementation
procedure TSideTest.TestSideCreate;
begin
try
FSide := TlaserCutBoxSide.Create(bstTop);
AssertEquals('Width is 0.0', 0.0, FSide.Width);
AssertEquals('Height is 0.0', 0.0, FSide.Height);
AssertEquals('Tabs Width is 0.0', 0.0, FSide.TabsWidth);
AssertEquals('Legend is ''Top''', 'Top', FSide.Legend);
finally
FSide.Free;
end;
end;
initialization
RegisterTest(TSideTest);
end.
|
unit Optimizer;
interface
uses
SysUtils, Classes, Forms, Generics.Collections,
Optimizer.Template, Optimizer.Hibernation, Optimizer.LastAccess,
Optimizer.Prefetch, Optimizer.Defrag, Optimizer.Indexer,
Optimizer.SystemRestore, Optimizer.P2P;
type
TOptimizeList = TList<Boolean>;
TMetaOptimizationUnit = class of TOptimizationUnit;
TNSTOptimizer = class
private
Optimizers: TOptimizerList;
Descriptions: TStringList;
Applied: TOptimizeList;
IsOptional: TOptimizeList;
procedure RefreshOptList;
procedure CheckOptimized;
procedure IfCompatibleAddToList(
TOptimizationUnitToTry: TMetaOptimizationUnit);
procedure AddOptimizers;
procedure ClearOptimizers;
public
constructor Create;
destructor Destroy; override;
procedure Optimize(OptList: TOptimizeList);
procedure CancelOptimization;
function GetDescriptions: TStringList;
function GetApplied: TOptimizeList;
function GetIsOptional: TOptimizeList;
end;
implementation
constructor TNSTOptimizer.Create;
begin
Descriptions := TStringList.Create;
Applied := TOptimizeList.Create;
IsOptional := TOptimizeList.Create;
Optimizers := TOptimizerList.Create;
RefreshOptList;
CheckOptimized;
end;
destructor TNSTOptimizer.Destroy;
begin
if Descriptions <> nil then
FreeAndNil(Descriptions);
if Applied <> nil then
FreeAndNil(Applied);
if IsOptional <> nil then
FreeAndNil(IsOptional);
if Optimizers <> nil then
FreeAndNil(Optimizers);
inherited;
end;
procedure TNSTOptimizer.Optimize(OptList: TList<Boolean>);
var
CurrentItem: Integer;
begin
for CurrentItem := 0 to Optimizers.Count - 1 do
if (OptList[CurrentItem]) and
(not Optimizers[CurrentItem].IsApplied) then
Optimizers[CurrentItem].Apply;
CheckOptimized;
end;
procedure TNSTOptimizer.CancelOptimization;
var
CurrentItem: Integer;
begin
for CurrentItem := 0 to Optimizers.Count - 1 do
if Optimizers[CurrentItem].IsApplied then
Optimizers[CurrentItem].Undo;
CheckOptimized;
end;
procedure TNSTOptimizer.CheckOptimized;
var
CurrentItem: Integer;
begin
for CurrentItem := 0 to Optimizers.Count - 1 do
Applied[CurrentItem] := Optimizers[CurrentItem].IsApplied;
RefreshOptList;
end;
procedure TNSTOptimizer.RefreshOptList;
begin
ClearOptimizers;
AddOptimizers;
end;
procedure TNSTOptimizer.AddOptimizers;
begin
IfCompatibleAddToList(THibernationOptimizer);
IfCompatibleAddToList(TLastAccessOptimizer);
IfCompatibleAddToList(TPrefetchOptimizer);
IfCompatibleAddToList(TDefragOptimizer);
IfCompatibleAddToList(TP2POptimizer);
IfCompatibleAddToList(TIndexerOptimizer);
IfCompatibleAddToList(TSystemRestoreOptimizer);
end;
procedure TNSTOptimizer.IfCompatibleAddToList(
TOptimizationUnitToTry: TMetaOptimizationUnit);
var
OptimizationUnit: IOptimizationUnit;
begin
OptimizationUnit := TOptimizationUnitToTry.Create;
if OptimizationUnit.IsCompatible then
begin
Optimizers.Add(OptimizationUnit);
Descriptions.Add(OptimizationUnit.GetName);
IsOptional.Add(OptimizationUnit.IsOptional);
Applied.Add(OptimizationUnit.IsApplied);
end;
end;
function TNSTOptimizer.GetDescriptions: TStringList;
begin
result := Descriptions;
end;
function TNSTOptimizer.GetIsOptional: TOptimizeList;
begin
result := IsOptional;
end;
procedure TNSTOptimizer.ClearOptimizers;
begin
Descriptions.Clear;
IsOptional.Clear;
Applied.Clear;
Optimizers.Clear;
end;
function TNSTOptimizer.GetApplied: TOptimizeList;
begin
result := Applied;
end;
end.
|
unit ncDBCommands;
interface
uses Classes, SysUtils, DB, ADODB, ADOInt, ncCommandPacking, ncSources, ncSerializeADO;
const
ncDBOpenDataset = 0; // uses TDBDatasetData as param
ncDBCloseDataset = 1; // uses no params
ncDBUpdateDataset = 2; // uses TDBUpdateDatasetData as param
ncDBExecDataset = 3; // uses TDBDatasetData as param
type
TDBDatasetData = class
public
SQL: string;
Parameters: TBytes;
constructor Create;
destructor Destroy; override;
function FromBytes(aBytes: TBytes): Integer; virtual;
function ToBytes: TBytes; virtual;
end;
TDBUpdateDatasetData = class(TDBDatasetData)
public
RecordUpdates: _Recordset;
constructor Create;
destructor Destroy; override;
function FromBytes(aBytes: TBytes): Integer; override;
function ToBytes: TBytes; override;
end;
implementation
{ TDBOpenDatasetData }
constructor TDBDatasetData.Create;
begin
inherited Create;
SetLength(Parameters, 0);
end;
destructor TDBDatasetData.Destroy;
begin
inherited;
end;
function TDBDatasetData.FromBytes(aBytes: TBytes): Integer;
begin
Result := 0;
SQL := ReadString(aBytes, Result);
Parameters := ReadBytes(aBytes, Result);
end;
function TDBDatasetData.ToBytes: TBytes;
var
BufLen: Integer;
begin
// This is intended for the use of WriteMessageEmbeddedBufferLen
SetLength(Result, 0);
BufLen := 0;
WriteString(SQL, Result, BufLen);
WriteBytes(Parameters, Result, BufLen);
end;
{ TDBUpdateDatasetData }
constructor TDBUpdateDatasetData.Create;
begin
inherited Create;
RecordUpdates := nil;
end;
destructor TDBUpdateDatasetData.Destroy;
begin
if Assigned(RecordUpdates) then
RecordUpdates := nil;
inherited;
end;
function TDBUpdateDatasetData.FromBytes(aBytes: TBytes): Integer;
begin
Result := inherited FromBytes(aBytes);
RecordUpdates := BytesToRecordset(ReadBytes(aBytes, Result));
end;
function TDBUpdateDatasetData.ToBytes: TBytes;
var
BufLen: Integer;
begin
Result := inherited ToBytes;
BufLen := Length(Result);
WriteBytes(RecordsetToBytes(RecordUpdates, pfADTG), Result, BufLen);
end;
end.
|
unit fNoteIDParents;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fAutoSz, ORCtrls, ComCtrls, StdCtrls, ORFn, VA508AccessibilityManager;
type
TfrmNoteIDParents = class(TfrmAutoSz)
cmdOK: TButton;
cmdCancel: TButton;
lstIDParents: TORListBox;
lblSelectParent: TLabel;
procedure FormCreate(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure cmdOKClick(Sender: TObject);
private
FParentNode: string;
public
{ Public declarations }
end;
function SelectParentNodeFromList(ATree: TORTreeView): string;
implementation
{$R *.DFM}
uses
uTIU, rTIU, uConst;
function SelectParentNodeFromList(ATree: TORTreeView): string;
var
frmNoteIDParents: TfrmNoteIDParents;
i, AnImg: integer;
x: string;
tmpList: TStringList;
begin
frmNoteIDParents := TfrmNoteIDParents.Create(Application);
tmpList := TStringList.Create;
try
ResizeFormToFont(TForm(frmNoteIDParents));
for i := 0 to ATree.Items.Count - 1 do
begin
AnImg := TORTreeNode(ATree.Items.Item[i]).ImageIndex;
if AnImg in [IMG_SINGLE, IMG_PARENT,IMG_IDNOTE_SHUT, IMG_IDNOTE_OPEN,
IMG_IDPAR_ADDENDA_SHUT, IMG_IDPAR_ADDENDA_OPEN] then
begin
x := TORTreeNode(ATree.Items.Item[i]).Stringdata;
tmpList.Add(Piece(x, U, 1) + U + MakeNoteDisplayText(x) + U + Piece(x, U, 3));
end;
end;
SortByPiece(tmpList, U, 3);
InvertStringList(tmpList);
FastAssign(tmpList, frmNoteIDParents.lstIDParents.Items);
frmNoteIDParents.ShowModal;
Result := frmNoteIDParents.FParentNode;
finally
tmpList.Free;
frmNoteIDParents.Release;
end;
end;
procedure TfrmNoteIDParents.FormCreate(Sender: TObject);
begin
inherited;
FParentNode := '';
end;
procedure TfrmNoteIDParents.cmdCancelClick(Sender: TObject);
begin
inherited;
FParentNode := '';
Close;
end;
procedure TfrmNoteIDParents.cmdOKClick(Sender: TObject);
const
TX_ATTACH_FAILURE = 'Attachment failed';
var
WhyNot, ErrMsg: string;
begin
inherited;
ErrMsg := '';
if not CanReceiveAttachment(lstIDParents.ItemID, WhyNot) then
ErrMsg := ErrMsg + WhyNot;
if ErrMsg <> '' then
begin
InfoBox(ErrMsg, TX_ATTACH_FAILURE, MB_OK);
Exit;
end;
FParentNode := lstIDParents.ItemID;
Close;
end;
end.
|
{
--------------------- Unit CRC32C.PAS 8<-----------------------
Modified from a version posted on the Pascal echo by Floor
A.C. Naaijkens (note introduction of a Constant and a
Function and making the Array a Constant outside of
crc32() which should improve speed a lot; further
references made to a C version in a File of Snippets from the
compare the large Arrays, which proved to be identical), and to
"File verification using CRC" by Mark R. Nelson in Dr. Dobbs'
Journal, May 1992. The latter provided the final piece of
crucial information. Use: 1) Create a LongInt Variable For the
CRC value; 2) Initialize this With CRCSeed; 3) Build the
CRC Byte-by-Byte With CRC32(); 4) Finish With CRCend()
(this was the part I found in Nelson). The result is a CRC
value identical to that calculated by PKZip and ARJ.
trixter@oldskool.org, 20111105: expanded to add a function that does
an entire buffer.
}
Unit CRC32c;
Interface
Const
CRCSeed = $ffffffff;
CRC32tab : Array[0..255] of LongInt = (
$00000000, $77073096, $ee0e612c, $990951ba, $076dc419, $706af48f,
$e963a535, $9e6495a3, $0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988,
$09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91, $1db71064, $6ab020f2,
$f3b97148, $84be41de, $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7,
$136c9856, $646ba8c0, $fd62f97a, $8a65c9ec, $14015c4f, $63066cd9,
$fa0f3d63, $8d080df5, $3b6e20c8, $4c69105e, $d56041e4, $a2677172,
$3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b, $35b5a8fa, $42b2986c,
$dbbbc9d6, $acbcf940, $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59,
$26d930ac, $51de003a, $c8d75180, $bfd06116, $21b4f4b5, $56b3c423,
$cfba9599, $b8bda50f, $2802b89e, $5f058808, $c60cd9b2, $b10be924,
$2f6f7c87, $58684c11, $c1611dab, $b6662d3d, $76dc4190, $01db7106,
$98d220bc, $efd5102a, $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433,
$7807c9a2, $0f00f934, $9609a88e, $e10e9818, $7f6a0dbb, $086d3d2d,
$91646c97, $e6635c01, $6b6b51f4, $1c6c6162, $856530d8, $f262004e,
$6c0695ed, $1b01a57b, $8208f4c1, $f50fc457, $65b0d9c6, $12b7e950,
$8bbeb8ea, $fcb9887c, $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65,
$4db26158, $3ab551ce, $a3bc0074, $d4bb30e2, $4adfa541, $3dd895d7,
$a4d1c46d, $d3d6f4fb, $4369e96a, $346ed9fc, $ad678846, $da60b8d0,
$44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9, $5005713c, $270241aa,
$be0b1010, $c90c2086, $5768b525, $206f85b3, $b966d409, $ce61e49f,
$5edef90e, $29d9c998, $b0d09822, $c7d7a8b4, $59b33d17, $2eb40d81,
$b7bd5c3b, $c0ba6cad, $edb88320, $9abfb3b6, $03b6e20c, $74b1d29a,
$ead54739, $9dd277af, $04db2615, $73dc1683, $e3630b12, $94643b84,
$0d6d6a3e, $7a6a5aa8, $e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1,
$f00f9344, $8708a3d2, $1e01f268, $6906c2fe, $f762575d, $806567cb,
$196c3671, $6e6b06e7, $fed41b76, $89d32be0, $10da7a5a, $67dd4acc,
$f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5, $d6d6a3e8, $a1d1937e,
$38d8c2c4, $4fdff252, $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b,
$d80d2bda, $af0a1b4c, $36034af6, $41047a60, $df60efc3, $a867df55,
$316e8eef, $4669be79, $cb61b38c, $bc66831a, $256fd2a0, $5268e236,
$cc0c7795, $bb0b4703, $220216b9, $5505262f, $c5ba3bbe, $b2bd0b28,
$2bb45a92, $5cb36a04, $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d,
$9b64c2b0, $ec63f226, $756aa39c, $026d930a, $9c0906a9, $eb0e363f,
$72076785, $05005713, $95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38,
$92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21, $86d3d2d4, $f1d4e242,
$68ddb3f8, $1fda836e, $81be16cd, $f6b9265b, $6fb077e1, $18b74777,
$88085ae6, $ff0f6a70, $66063bca, $11010b5c, $8f659eff, $f862ae69,
$616bffd3, $166ccf45, $a00ae278, $d70dd2ee, $4e048354, $3903b3c2,
$a7672661, $d06016f7, $4969474d, $3e6e77db, $aed16a4a, $d9d65adc,
$40df0b66, $37d83bf0, $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9,
$bdbdf21c, $cabac28a, $53b39330, $24b4a3a6, $bad03605, $cdd70693,
$54de5729, $23d967bf, $b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94,
$b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d );
Function CRC32(value:Byte;crc:LongInt):LongInt;
Function CRCend(crc:LongInt):LongInt;
Function CRC32Buf(buf:pointer;len:word):LongInt; {len of 0 means 65536 bytes}
Implementation
Function CRC32(value: Byte; crc: LongInt) : LongInt;
begin
CRC32 := CRC32tab[Byte(crc xor LongInt(value))] xor ((crc shr 8) and $00ffffff);
end;
Function CRCend( crc : LongInt ): LongInt;
begin
CRCend := (crc xor CRCSeed);
end;
Function CRC32Buf(buf:pointer;len:word):LongInt;
var
l:longint;
w:word;
p:^byte;
begin
p:=buf;
l:=crcseed;
for w:=0 to word(len-1) do begin
l:=CRC32tab[Byte(l xor LongInt(p^))] xor ((l shr 8) and $00ffffff);
inc(word(p));
end;
l:=CRCend(l);
CRC32Buf:=l;
end;
end.
{
Now to use it...
With a LongInt Variable, say vCRC32, first seed it
vCRC32 := CRCSeed;
Then go Byte-by-Byte thorugh to calculate:
For P := 1 to Size DO
vCRC32 := CRC32(Bytes[P], vCRC32);
Then finish it off With CRCend
vCRC32 := CRCend(vCRC32);
You should be able to Write your own Dec2Hex Function =)
}
|
{
/***************************************************************************
indSliders
----------
sliders for the Industrial package
The initial version of this unit was published in the Lazarus forum
by user bylaardt
(https://forum.lazarus.freepascal.org/index.php/topic,45063.msg318180.html#msg318180)
and extended by wp.
License: modified LGPL like Lazarus LCL
*****************************************************************************
}
unit indSliders;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, Controls, Types;
Type
{ TMultiSlider }
TSliderMode = (smSingle, smMinMax, smMinValueMax);
TThumbKind = (tkMin, tkMax, tkValue);
TThumbstyle = (tsGrip, tsCircle, tsRect, tsRoundedRect,
tsTriangle, tsTriangleOtherSide);
TSliderPositionEvent = procedure (
Sender: TObject; AKind: TThumbKind; AValue: Integer) of object;
TMultiSlider = class(TCustomControl)
private
const
DEFAULT_SIZE = 28;
DEFAULT_TRACK_THICKNESS = 7;
DEFAULT_MULTISLIDER_WIDTH = 250;
DEFAULT_MULTISLIDER_HEIGHT = DEFAULT_SIZE * 5 div 4;
private
FAutoRotate: Boolean;
FTrackSize: TPoint;
FBtnSize: TPoint;
FCapture: ShortInt;
FCaptureOffset, FTrackStart: Integer;
FColorAbove: TColor;
FColorBelow: TColor;
FColorBetween: TColor;
FColorThumb: TColor;
FFlat: Boolean;
FVertical: boolean;
FMaxPosition, FMinPosition, FPosition: Integer;
FDefaultSize: Integer;
FSliderMode: TSliderMode;
FThumbStyle: TThumbstyle;
FTrackThickness: Integer;
FOnPositionChange: TSliderPositionEvent;
FRangeMax, FRangeMin: Integer;
function IsDefaultSizeStored: Boolean;
function IsTrackThicknessStored: Boolean;
procedure SetColorAbove(AValue: TColor);
procedure SetColorBelow(AValue: TColor);
procedure SetColorBetween(AValue: TColor);
procedure SetColorThumb(AValue: TColor);
procedure SetDefaultSize(AValue: Integer);
procedure SetFlat(AValue: Boolean);
procedure SetMaxPosition(AValue: Integer);
procedure SetMinPosition(AValue: Integer);
procedure SetPosition(AValue: Integer);
procedure SetRangeMax(AValue: Integer);
procedure SetRangeMin(AValue: Integer);
procedure SetSliderMode(AValue: TSliderMode);
procedure SetThumbStyle(AValue: TThumbStyle);
procedure SetTrackThickness(AValue: Integer);
procedure SetVertical(AValue: Boolean);
protected
function BtnLength: Integer;
procedure DoAutoAdjustLayout(const AMode: TLayoutAdjustmentPolicy;
const AXProportion, AYProportion: Double); override;
procedure DoPositionChange(AKind: TThumbKind; AValue: Integer);
function ExtendedThumbs: Boolean;
function GetRectFromPoint(APosition: Integer; Alignment: TAlignment): TRect;
function GetThumbCenter(ARect: TRect): TPoint;
function GetTrackLength: Integer;
function IsInFirstHalf(APoint: TPoint; ARect: TRect): Boolean;
procedure Loaded; override;
function PointToPosition(P: TPoint): Integer;
procedure UpdateBounds;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Paint; override;
procedure Resize; override;
procedure MouseDown(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); override;
procedure MouseMove(Shift: TShiftState; X,Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); override;
procedure MouseLeave; override;
published
property AutoRotate: Boolean
read FAutoRotate write FAutoRotate default true;
property ColorAbove: TColor
read FColorAbove write SetColorAbove default clInactiveCaption;
property ColorBelow: TColor
read FColorBelow write SetColorBelow default clInactiveCaption;
property ColorBetween: TColor
read FColorBetween write SetColorBetween default clActiveCaption;
property ColorThumb: TColor
read FColorThumb write SetColorThumb default clBtnFace;
property DefaultSize: Integer
read FDefaultSize write SetDefaultSize stored IsDefaultSizeStored;
property Flat: Boolean
read FFlat write SetFlat default false;
property MaxPosition: Integer
read FMaxPosition write SetMaxPosition default 80;
property MinPosition: Integer
read FMinPosition write SetMinPosition default 20;
property Position: Integer
read FPosition write SetPosition default 50;
property RangeMax: Integer
read FRangeMax write SetRangeMax default 100;
property RangeMin: Integer
read FRangeMin write SetRangeMin default 0;
property SliderMode: TSliderMode
read FSliderMode write SetSliderMode default smMinMax;
property ThumbStyle: TThumbStyle
read FThumbStyle write SetThumbStyle default tsGrip;
property TrackThickness: integer
read FTrackThickness write SetTrackThickness stored IsTrackThicknessStored;
property Vertical: boolean
read FVertical write SetVertical default false;
property Height default DEFAULT_SIZE;
property Width default DEFAULT_MULTISLIDER_WIDTH;
property OnPositionChange: TSliderPositionEvent
read FOnPositionChange write FOnPositionChange;
property Align;
property BorderSpacing;
property Constraints;
property Enabled;
// property Font;
property HelpContext;
property HelpKeyword;
property HelpType;
property Left;
// property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Tag;
property Top;
property Visible;
property OnChangeBounds;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnMouseWheelHorz;
property OnMouseWheelLeft;
property OnMouseWheelRight;
property OnResize;
end;
implementation
uses
Math;
constructor TMultiSlider.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAutoRotate := true;
FCapture := -1;
FColorAbove := clInactiveCaption;
FColorBelow := clInactiveCaption;
FColorBetween := clActiveCaption;
FColorThumb := clBtnFace;
FDefaultSize := DEFAULT_SIZE;
FTrackThickness := DEFAULT_TRACK_THICKNESS;
FTrackStart := FDefaultSize*9 div 16 + 2;
SetVertical(false);
FRangeMin := 0;
FRangeMax := 100;
FMinPosition := 20;
FMaxPosition := 80;
FPosition := 50;
FSliderMode := smMinMax;
Width := DEFAULT_MULTISLIDER_WIDTH;
Height := DEFAULT_MULTISLIDER_HEIGHT;
Enabled := true;
end;
destructor TMultiSlider.Destroy;
begin
inherited Destroy;
end;
function TMultiSlider.BtnLength: Integer;
begin
Result := IfThen(FVertical, FBtnSize.Y, FBtnSize.X) div 2;
end;
procedure TMultiSlider.DoAutoAdjustLayout(
const AMode: TLayoutAdjustmentPolicy;
const AXProportion, AYProportion: Double);
begin
inherited DoAutoAdjustLayout(AMode, AXProportion, AYProportion);
if AMode in [lapAutoAdjustWithoutHorizontalScrolling, lapAutoAdjustForDPI] then
begin
if FVertical then
begin
FTrackThickness := Round(FTrackThickness * AXProportion);
FDefaultSize := Round(FDefaultSize * AYProportion);
end else
begin
FTrackThickness := Round(FTrackThickness * AYProportion);
FDefaultSize := Round(FDefaultSize * AXProportion);
end;
end;
end;
procedure TMultiSlider.DoPositionChange(AKind: TThumbKind; AValue: Integer);
begin
if Assigned(FOnPositionChange) then FOnPositionChange(self, AKind, AValue);
end;
function TMultiSlider.ExtendedThumbs: Boolean;
begin
Result := not (FThumbStyle in [tsTriangle, tsTriangleOtherSide]);
end;
function TMultiSlider.GetRectFromPoint(APosition: Integer;
Alignment: TAlignment): TRect;
var
relPos: Double;
begin
relPos := (APosition - FRangeMin) / (FRangeMax - FRangeMin);
if FVertical then begin
if ExtendedThumbs then
case Alignment of
taLeftJustify:
Result.Top := FTrackStart + Round(FTrackSize.Y * relPos) - FBtnSize.Y;
taCenter:
if FSliderMode = smSingle then
Result.Top := FTrackStart + Round((FTrackSize.Y + FBtnSize.Y) * relPos) - FBtnSize.Y
else
Result.Top := FTrackStart + Round((FTrackSize.Y - FBtnSize.Y) * relPos);
taRightJustify:
Result.Top := FTrackStart + Round(FTrackSize.Y * relPos);
end
else
Result.Top := FTrackStart + Round(FTrackSize.Y * relPos) - FBtnSize.Y div 2;
Result.Left := (Width - FBtnSize.X) div 2;
end else begin
if ExtendedThumbs then
case Alignment of
taLeftJustify:
Result.Left := FTrackStart + Round(FTrackSize.X * relpos) - FBtnSize.X;
taCenter:
if FSliderMode = smSingle then
Result.Left := FTrackStart + Round((FTrackSize.X + FBtnSize.X) * relPos) - FBtnSize.X
else
Result.Left := FTrackStart + Round((FTrackSize.X - FBtnSize.X) * relPos);
taRightJustify:
Result.Left := FTrackStart + Round(FTrackSize.X * relPos);
end
else
Result.Left := FTrackStart + Round(FTrackSize.X * relPos) - FBtnSize.X div 2;
Result.Top := (Height - FBtnSize.Y) div 2;
end;
Result.Right := Result.Left + FBtnSize.X;
Result.Bottom := Result.Top + FBtnSize.Y;
end;
function TMultiSlider.GetThumbCenter(ARect: TRect): TPoint;
begin
Result := Point((ARect.Left + ARect.Right) div 2, (ARect.Top + ARect.Bottom) div 2);
end;
function TMultiSlider.GetTrackLength: Integer;
begin
if FVertical then
Result := FTrackSize.Y
else
Result := FTrackSize.X;
end;
function TMultiSlider.IsDefaultSizeStored: Boolean;
begin
Result := FDefaultSize <> Scale96ToFont(DEFAULT_SIZE);
end;
function TMultiSlider.IsInFirstHalf(APoint: TPoint; ARect: TRect): Boolean;
begin
if FVertical then begin
ARect.Right := GetThumbCenter(ARect).X;
Result := PtInRect(ARect, APoint);
end else begin
ARect.Bottom := GetThumbCenter(ARect).Y;
Result := PtInRect(ARect, APoint);
end;
end;
function TMultiSlider.IsTrackThicknessStored: Boolean;
begin
Result := FTrackThickness <> Scale96ToFont(DEFAULT_TRACK_THICKNESS);
end;
procedure TMultiSlider.Loaded;
begin
inherited;
exit;
if FAutoRotate then begin
if (FVertical and (Width > Height)) or ((not FVertical) and (Width < Height)) then
SetBounds(Left, Top, Height, Width);
end;
end;
procedure TMultiSlider.MouseDown(Button: TMouseButton; Shift: TShiftState;
X,Y: Integer);
var
p: TPoint;
btn1, btn2, btn3: TRect;
inFirstHalf3: Boolean;
begin
if Enabled then begin
p := Point(x,y);
btn1 := GetRectFromPoint(FMinPosition, taLeftJustify);
btn2 := GetRectFromPoint(FMaxPosition, taRightJustify);
btn3 := GetRectFromPoint(FPosition, taCenter);
FCapture := -1;
if (FSliderMode <> smSingle) and PtInRect(btn1, p) then begin
FCapture := ord(tkMin);
if ExtendedThumbs then
FCaptureOffset := IfThen(FVertical, Y - btn1.Bottom, X - btn1.Right)
else
FCaptureOffset := IfThen(FVertical, Y - GetThumbCenter(btn1).Y, X - GetThumbCenter(btn1).X);
end else
if (FSliderMode <> smSingle) and PtInRect(btn2, p) then begin
FCapture := ord(tkMax);
if ExtendedThumbs then
FCaptureOffset := IfThen(FVertical, Y - btn2.Top, X - btn2.Left)
else
FCaptureOffset := IfThen(FVertical, Y - GetThumbCenter(btn2).Y, X - GetThumbCenter(btn2).X)
end else
if (FSliderMode <> smMinMax) and PtInRect(btn3, p) then begin
FCapture := ord(tkValue);
if ExtendedThumbs then
FCaptureOffset := IfThen(FVertical, Y - btn3.Top, X - btn3.Left)
else
FCaptureOffset := IfThen(FVertical, Y - GetThumbCenter(btn3).Y, X - GetThumbCenter(btn3).X);
end;
if (FCapture > -1) and (not ExtendedThumbs and PtInRect(btn3, p)) then begin
inFirstHalf3 := IsInFirstHalf(p, btn3);
if (TThumbKind(FCapture) in [tkMin, tkMax]) and (
(inFirstHalf3 and (FThumbStyle = tsTriangleOtherSide)) or
((not inFirstHalf3) and (FThumbStyle = tsTriangle))
) then
begin
FCapture := ord(tkValue);
end;
end;
end;
inherited MouseDown(Button, Shift, X, Y);
end;
procedure TMultiSlider.MouseMove(Shift: TShiftState; X, Y: Integer);
var
p: TPoint;
btn: TRect;
pos: Integer;
begin
if Enabled then begin
p := Point(X, Y);
case FCapture of
-1: begin
btn := GetRectFromPoint(FMinPosition, taLeftJustify);
if PtInRect(btn, p) then begin
Cursor := crHandPoint;
end else begin
btn := GetRectFromPoint(FMaxPosition, taRightJustify);
if PtInRect(btn, p) then begin
Cursor := crHandPoint;
end else
Cursor := crDefault;
end;
end;
else
pos := PointToPosition(p);
case TThumbKind(FCapture) of
tkMin: if FSliderMode <> smSingle then SetMinPosition(pos);
tkMax: if FSliderMode <> smSingle then SetMaxPosition(pos);
tkValue: if FSliderMode <> smMinMax then SetPosition(pos);
end;
end;
end;
inherited MouseMove(Shift,x,y);
end;
procedure TMultiSlider.MouseLeave;
begin
inherited MouseLeave;
FCapture := -1;
end;
procedure TMultiSlider.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
FCapture := -1;
inherited MouseUp(Button,Shift,x,y);
end;
procedure TMultiSlider.Paint;
procedure DrawLine(ARect: TRect; AColor, AShadow, AHilight: TColor);
var
start, ending, distances, centerpoint, loop: Integer;
begin
distances := FDefaultSize div 8;
start := ARect.Left + FBtnSize.x div 2 - distances*8 div 5;
ending := start + distances*16 div 5;
centerPoint := (ARect.Bottom - ARect.Top) div 2 + ARect.Top;
for loop := -1 to 1 do begin
Canvas.Pen.Color := AHilight;
Canvas.MoveTo(start, centerPoint - 1 + loop * distances);
Canvas.LineTo(ending, centerPoint - 1 + loop * distances);
Canvas.Pen.Color := AColor;
Canvas.MoveTo(start, centerPoint + loop * distances);
Canvas.LineTo(ending, centerPoint + loop * distances);
Canvas.Pen.Color := AShadow;
Canvas.MoveTo(start, centerPoint + 1 + loop * distances);
Canvas.LineTo(ending, centerPoint + 1 + loop * distances);
end;
end;
procedure DrawRect(ARect: TRect; X1,Y1, X2,Y2, R: Integer; AColor: TColor);
begin
Canvas.Pen.Color := AColor;
Canvas.Pen.Width := 1;
Canvas.Brush.Color := Canvas.Pen.Color;
Canvas.RoundRect(
ARect.Left + X1,
ARect.Top + Y1,
ARect.Right + X2,
ARect.Bottom + Y2,
R, R);
end;
procedure DrawThumb(ARect, ATrackRect: TRect; InFirstHalf: Boolean);
var
radius: Integer;
center: TPoint;
P: array[0..2] of TPoint;
begin
case FThumbStyle of
tsGrip, tsRoundedRect:
begin
radius := Min(FBtnSize.X, FBtnSize.Y) div 2;
if FFlat then
DrawRect(ARect, 0, 0, 0, 0, radius, FColorThumb)
else begin
DrawRect(ARect, 0, 0, -1, -1, radius, clBtnHighlight);
DrawRect(ARect, 1, 1, 0, 0, radius, clBtnShadow);
DrawRect(ARect, 1, 1, -1, -1, radius, FColorThumb);
end;
if FThumbStyle = tsGrip then
DrawLine(ARect, FColorThumb, clBtnShadow, clBtnHighlight);
end;
tsCircle:
begin
center := Point((ARect.Left + ARect.Right) div 2, (ARect.Top + ARect.Bottom) div 2);
radius := Min(ARect.Right - ARect.Left, ARect.Bottom - ARect.Top) div 2;
if not FFlat then begin
Canvas.Brush.Style := bsClear;
Canvas.Pen.Color := clBtnHighlight;
Canvas.Ellipse(center.X - radius - 1, center.Y - radius - 1, center.X + radius - 1, center.Y + radius - 1);
Canvas.Pen.Color := clBtnShadow;
Canvas.Ellipse(center.X - radius + 1, center.Y - radius + 1, center.X + radius + 1, center.Y + radius + 1);
end;
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := FColorThumb;
Canvas.Pen.Color := FColorThumb;
Canvas.Ellipse(center.X - radius, center.Y - radius, center.X + radius, center.Y + radius);
end;
tsRect:
begin
if not FFlat then begin
Canvas.Brush.Style := bsClear;
Canvas.Pen.Color := clBtnHighlight;
Canvas.Rectangle(ARect.Left - 1, ARect.Top - 1, ARect.Right - 1, ARect.Bottom - 1);
Canvas.Pen.Color := clBtnShadow;
Canvas.Rectangle(ARect.Left + 1, ARect.Top + 1, ARect.Right + 1, ARect.Bottom + 1);
end;
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := FColorThumb;
Canvas.Pen.Color := FColorThumb;
Canvas.Rectangle(ARect);
end;
tsTriangle, tsTriangleOtherSide:
begin
if FVertical then begin
if InFirstHalf then begin
P[0] := Point(ARect.Left, ARect.Top);
P[1] := Point(ARect.Left, ARect.Bottom);
P[2] := Point(ATrackRect.Left, GetThumbCenter(ARect).Y);
end else begin
P[0] := Point(ARect.Right, ARect.Top);
P[1] := Point(ARect.Right, ARect.Bottom);
P[2] := Point(ATrackRect.Right, GetThumbCenter(ARect).Y);
end;
end else begin
if InFirstHalf then begin
P[0] := Point(ARect.Left, ARect.Bottom);
P[1] := Point(ARect.Right, ARect.Bottom);
P[2] := Point(GetThumbCenter(ARect).X, ATrackRect.Bottom);
end else begin
P[0] := Point(ARect.Left, ARect.Top);
P[1] := Point(ARect.Right, ARect.Top);
P[2] := Point(GetThumbCenter(ARect).X, ATrackRect.Top);
end;
end;
if not FFlat then begin
Canvas.Brush.Style := bsClear;
Canvas.Pen.Color := clBtnHighlight;
Canvas.Polygon([Point(P[0].X-1, P[0].Y-1), Point(P[1].X-1, P[1].Y-1), Point(P[2].X-1, P[2].Y-1)]);
Canvas.Pen.Color := clBtnShadow;
Canvas.Polygon([Point(P[0].X+1, P[0].Y+1), Point(P[1].X+1, P[1].Y+1), Point(P[2].X+1, P[2].Y+1)]);
end;
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := FColorThumb;
Canvas.Pen.Color := FColorThumb;
Canvas.Polygon(P);
end;
end;
end;
var
R: Integer;
track, rang, btn1, btn2, btn: TRect;
rectBelow, rectAbove: TRect;
dx, dy: Integer;
begin
if FVertical then begin
track.Left := (Width - FTrackSize.X) div 2;
track.Top := FTrackStart;
end else begin
track.Left := FTrackStart;
track.Top := (Height - FTrackSize.Y) div 2;
end;
track.Right := track.Left + FTrackSize.x;
track.Bottom := track.Top + FTrackSize.y;
btn1 := GetRectFromPoint(FMinPosition, taLeftJustify);
btn2 := GetRectFromPoint(FMaxPosition, taRightJustify);
btn := GetRectFromPoint(FPosition, taCenter);
if FVertical then begin
dx := 0;
dy := IfThen(ExtendedThumbs, FBtnSize.Y, 0);
rang.Top := IfThen(ExtendedThumbs, btn1.Bottom, GetThumbCenter(btn1).Y);
rang.Bottom := IfThen(ExtendedThumbs, btn2.Top, GetThumbCenter(btn2).Y);
rang.Left := track.Left;
rang.Right := track.Right;
if FSliderMode = smSingle then begin
rectBelow := Rect(track.Left, track.Top, track.Right, IfThen(ExtendedThumbs, btn.Top, GetThumbCenter(btn).Y));
rectAbove := Rect(track.Left, IfThen(ExtendedThumbs, btn.Bottom, GetThumbCenter(btn).Y), track.Right, track.bottom);
end else begin
rectBelow := Rect(track.Left, track.Top, track.Right, rang.Top);
rectAbove := Rect(track.Left, rang.Bottom, track.Right, track.Bottom);
end;
end else begin
dx := IfThen(ExtendedThumbs, FBtnSize.X, 0);
dy := 0;
rang.Top := track.Top;
rang.Bottom := track.Bottom;
rang.Left := IfThen(ExtendedThumbs, btn1.Right, GetThumbCenter(btn1).X);
rang.Right := IfThen(ExtendedThumbs, btn2.Left, GetThumbCenter(btn2).X);
if FSliderMode = smSingle then begin
rectBelow := Rect(track.Left, track.Top, IfThen(ExtendedThumbs, btn.Left, GetThumbCenter(btn).X), track.Bottom);
rectAbove := Rect(IfThen(ExtendedThumbs, btn.Right, GetThumbCenter(btn).X), track.Top, track.Right, track.Bottom);
end else begin
rectBelow := Rect(track.Left, track.Top, rang.Left, track.Bottom);
rectAbove := Rect(rang.Right, track.Top, track.Right, track.Bottom)
end;
end;
R := IfThen(ExtendedThumbs, Min(FTrackSize.X, FTrackSize.Y), 0);
if not Flat then begin
DrawRect(track, -(dx+2), -(dy+2), dx, dy, R, clBtnShadow);
DrawRect(track, -dx, -dy, dx+2, dy+2, R, clBtnHighlight);
end;
DrawRect(rectBelow, -(dx+1), -(dy+1), dx+1, dy+1, R, FColorBelow);
DrawRect(rectAbove, -(dx+1), -(dy+1), dx+1, dy+1, R, FColorAbove);
if FSliderMode <> smSingle then
DrawRect(rang, -1, -1, 1, 1, 0, FColorBetween);
if (FSliderMode <> smSingle) then begin
DrawThumb(btn1, track, FThumbStyle = tsTriangleOtherSide);
DrawThumb(btn2, track, FThumbStyle = tsTriangleOtherSide);
end;
if (FSliderMode <> smMinMax) then
DrawThumb(btn, track, FThumbStyle <> tsTriangleOtherSide);
end;
function TMultiSlider.PointToPosition(P: TPoint): Integer;
var
pos_start, pos_range: Integer;
coord: Integer;
coord_range: Integer;
coord_start: Integer;
btn1, btn2: TRect;
begin
if FVertical then
coord := P.Y
else
coord := P.X;
if (TThumbKind(FCapture) = tkValue) and (FSliderMode <> smSingle) then begin
btn1 := GetRectFromPoint(FMinPosition, taLeftJustify);
btn2 := GetRectFromPoint(FMaxPosition, taRightJustify);
pos_start := FMinPosition;
pos_range := FMaxPosition - FMinPosition;
if ExtendedThumbs then begin
if FVertical then begin
coord_start := btn1.Bottom + FCaptureOffset;
coord_range := btn2.Top - btn1.Bottom;
end else begin
coord_start := btn1.Right + FCaptureOffset;
coord_range := btn2.Left - btn1.Right;
end;
end else begin
if FVertical then begin
coord_start := GetThumbCenter(btn1).Y + FCaptureOffset;
coord_range := btn2.Top - btn1.Top;
end else begin
coord_start := GetThumbCenter(btn1).X + FCaptureOffset;
coord_range := btn2.Left - btn1.Left;
end;
end;
{
if FThumbStyle = tsTriangle then begin
if FVertical then begin
end else begin
coord_start := (btn1.Left + btn1.Right) div 2 + FCaptureOffset;
coord_range := btn2.Left - btn1.Left;
end
end else begin
if FVertical then begin
coord_start := btn1.Top + FCaptureOffset;
coord_range := btn2.Top - btn1.Bottom;
end else begin
coord_start := btn1.Right + FCaptureOffset;
coord_range := btn2.Left - btn1.Right;
end;
end;
}
end else begin
pos_start := FRangeMin;
pos_range := FRangeMax - FRangeMin;
coord_start := FTrackStart + FCaptureOffset;
coord_range := GetTracklength;
end;
Result := round(pos_start + pos_range * (coord - coord_start) / coord_range);
end;
procedure TMultiSlider.Resize;
begin
inherited;
UpdateBounds;
end;
{
procedure TMultiSlider.SetColor(AValue: TColor);
begin
inherited;
if AValue = clNone then
ControlStyle := ControlStyle - [csOpaque]
else
ControlStyle := ControlStyle + [csOpaque];
end; }
procedure TMultiSlider.SetColorAbove(AValue: TColor);
begin
if AValue = FColorAbove then exit;
FColorAbove := AValue;
Invalidate;
end;
procedure TMultiSlider.SetColorBelow(AValue: TColor);
begin
if AValue = FColorBelow then exit;
FColorBelow := AValue;
Invalidate;
end;
procedure TMultiSlider.SetColorBetween(AValue: TColor);
begin
if AValue = FColorBetween then exit;
FColorBetween := AValue;
Invalidate;
end;
procedure TMultiSlider.SetColorThumb(AValue: TColor);
begin
if AValue = FColorThumb then exit;
FColorThumb := AValue;
Invalidate;
end;
procedure TMultiSlider.SetDefaultSize(AValue: Integer);
begin
if FDefaultSize = AValue then exit;
FDefaultSize := AValue;
if AutoSize then begin
if FVertical then Width := FDefaultSize else Height := FDefaultSize;
end;
UpdateBounds;
end;
procedure TMultiSlider.SetFlat(AValue: Boolean);
begin
if FFlat = AValue then exit;
FFlat := AValue;
Invalidate;
end;
procedure TMultiSlider.SetMaxPosition(AValue: Integer);
var
newPos: Integer;
begin
newPos := Min(Max(AValue, FRangeMin), FRangeMax);
if (newPos = FMaxPosition) then exit;
if (newPos < FMinPosition) and (FSliderMode <> smSingle) then newPos := FMinPosition;
if (newPos < FPosition) and (FSliderMode <> smMinMax) then newPos := FPosition;
FMaxPosition := newPos;
DoPositionChange(tkMax, FMaxPosition);
Invalidate;
end;
procedure TMultiSlider.SetMinPosition(AValue: Integer);
var
newPos: Integer;
begin
newPos := Max(Min(AValue, FRangeMax), FRangeMin);
if (newPos = FMinPosition) then exit;
if (newPos > FMaxPosition) and (FSliderMode <> smSingle) then newPos := FMaxPosition;
if (newPos > FPosition) and (FSliderMode <> smMinMax) then newPos := FPosition;
FMinPosition := newPos;
DoPositionChange(tkMin, FMinPosition);
Invalidate;
end;
procedure TMultiSlider.SetPosition(AValue: Integer);
var
newPos: Integer;
begin
newPos := Max(Min(AValue, FRangeMax), FRangeMin);
if (newPos = FPosition) then exit;
if (FSliderMode <> smSingle) then begin
if (newPos < FMinPosition) then newPos := FMinPosition;
if (newPos > FMaxPosition) then newPos := FMaxPosition;
end;
FPosition := newPos;
DoPositionChange(tkValue, FPosition);
Invalidate;
end;
procedure TMultiSlider.SetRangeMax(AValue:Integer);
begin
if FRangeMax = AValue then exit;
FRangeMax := AValue;
DoPositionChange(tkMax, FRangeMax);
Invalidate;
end;
procedure TMultiSlider.SetRangeMin(AValue: Integer);
begin
if FRangeMin = AValue then exit;
FRangeMin := AValue;
DoPositionChange(tkMin, FRangeMin);
Invalidate;
end;
procedure TMultiSlider.SetThumbStyle(AValue: TThumbStyle);
begin
if FThumbStyle = AValue then exit;
FThumbStyle := AValue;
Invalidate;
end;
procedure TMultiSlider.SetTrackThickness(AValue: Integer);
begin
if FTrackThickness = AValue then exit;
FTrackThickness := AValue;
UpdateBounds;
end;
procedure TMultiSlider.SetVertical(AValue: Boolean);
begin
if FVertical = AValue then exit;
FVertical := AValue;
//if not (csLoading in ComponentState) then begin
if FAutoRotate then begin
if (FVertical and (Width > Height)) or ((not FVertical) and (Width < Height)) then
SetBounds(Left, Top, Height, Width);
end;
UpdateBounds;
//end;
end;
procedure TMultiSlider.SetSliderMode(AValue: TSliderMode);
begin
if FSliderMode = AValue then exit;
FSliderMode := AValue;
Invalidate;
end;
procedure TMultiSlider.UpdateBounds;
var
buttonSize: Integer;
begin
buttonSize := FDefaultSize*5 div 8;
if FVertical then begin
FBtnSize := Point(FDefaultSize, buttonSize);
FTrackSize := Point(FTrackThickness, Height - FTrackStart * 2);
end else begin
FBtnSize:= Point(buttonSize, FDefaultSize);
FTrackSize := Point(Width - FTrackStart * 2, FTrackThickness);
end;
Invalidate;
end;
end.
|
{*******************************************************}
{ }
{ Borland Visibroker for Delphi Event Service }
{ }
{ PushConsumer Impl Template }
{ }
{ Copyright (C) 2000 Inprise Corporation }
{ }
{*******************************************************}
// Use this template for a PushConsumer implementation.
// Fill in the "Push" method with your code.
// See examples for a sample implementation.
unit PushConsumer_Impl;
interface
uses Corba, COSEvent;
type
TPushConsumer = class(TInterfacedObject, PushConsumer)
public
constructor Create;
procedure Push(const data : Any);
procedure disconnect_push_consumer;
end;
implementation
constructor TPushConsumer.Create;
begin
inherited;
end;
procedure TPushConsumer.Push(const data : Any);
begin
{ *************************** }
{ *** User code goes here *** }
{ *************************** }
end;
procedure TPushConsumer.disconnect_push_consumer;
begin
boa.ExitImplReady;
end;
end.
|
unit TrackBarImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ComCtrls;
type
TTrackBarX = class(TActiveXControl, ITrackBarX)
private
{ Private declarations }
FDelphiControl: TTrackBar;
FEvents: ITrackBarXEvents;
procedure ChangeEvent(Sender: TObject);
procedure KeyPressEvent(Sender: TObject; var Key: Char);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_Ctl3D: WordBool; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Frequency: Integer; safecall;
function Get_LineSize: Integer; safecall;
function Get_Max: Integer; safecall;
function Get_Min: Integer; safecall;
function Get_Orientation: TxTrackBarOrientation; safecall;
function Get_PageSize: Integer; safecall;
function Get_ParentCtl3D: WordBool; safecall;
function Get_Position: Integer; safecall;
function Get_SelEnd: Integer; safecall;
function Get_SelStart: Integer; safecall;
function Get_SliderVisible: WordBool; safecall;
function Get_ThumbLength: Integer; safecall;
function Get_TickMarks: TxTickMark; safecall;
function Get_TickStyle: TxTickStyle; safecall;
function Get_Visible: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure AboutBox; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_Ctl3D(Value: WordBool); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Frequency(Value: Integer); safecall;
procedure Set_LineSize(Value: Integer); safecall;
procedure Set_Max(Value: Integer); safecall;
procedure Set_Min(Value: Integer); safecall;
procedure Set_Orientation(Value: TxTrackBarOrientation); safecall;
procedure Set_PageSize(Value: Integer); safecall;
procedure Set_ParentCtl3D(Value: WordBool); safecall;
procedure Set_Position(Value: Integer); safecall;
procedure Set_SelEnd(Value: Integer); safecall;
procedure Set_SelStart(Value: Integer); safecall;
procedure Set_SliderVisible(Value: WordBool); safecall;
procedure Set_ThumbLength(Value: Integer); safecall;
procedure Set_TickMarks(Value: TxTickMark); safecall;
procedure Set_TickStyle(Value: TxTickStyle); safecall;
procedure Set_Visible(Value: WordBool); safecall;
procedure SetTick(Value: Integer); safecall;
end;
implementation
uses ComObj, About36;
{ TTrackBarX }
procedure TTrackBarX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_TrackBarXPage); }
end;
procedure TTrackBarX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as ITrackBarXEvents;
end;
procedure TTrackBarX.InitializeControl;
begin
FDelphiControl := Control as TTrackBar;
FDelphiControl.OnChange := ChangeEvent;
FDelphiControl.OnKeyPress := KeyPressEvent;
end;
function TTrackBarX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TTrackBarX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TTrackBarX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TTrackBarX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TTrackBarX.Get_Ctl3D: WordBool;
begin
Result := FDelphiControl.Ctl3D;
end;
function TTrackBarX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TTrackBarX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TTrackBarX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TTrackBarX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TTrackBarX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TTrackBarX.Get_Frequency: Integer;
begin
Result := FDelphiControl.Frequency;
end;
function TTrackBarX.Get_LineSize: Integer;
begin
Result := FDelphiControl.LineSize;
end;
function TTrackBarX.Get_Max: Integer;
begin
Result := FDelphiControl.Max;
end;
function TTrackBarX.Get_Min: Integer;
begin
Result := FDelphiControl.Min;
end;
function TTrackBarX.Get_Orientation: TxTrackBarOrientation;
begin
Result := Ord(FDelphiControl.Orientation);
end;
function TTrackBarX.Get_PageSize: Integer;
begin
Result := FDelphiControl.PageSize;
end;
function TTrackBarX.Get_ParentCtl3D: WordBool;
begin
Result := FDelphiControl.ParentCtl3D;
end;
function TTrackBarX.Get_Position: Integer;
begin
Result := FDelphiControl.Position;
end;
function TTrackBarX.Get_SelEnd: Integer;
begin
Result := FDelphiControl.SelEnd;
end;
function TTrackBarX.Get_SelStart: Integer;
begin
Result := FDelphiControl.SelStart;
end;
function TTrackBarX.Get_SliderVisible: WordBool;
begin
Result := FDelphiControl.SliderVisible;
end;
function TTrackBarX.Get_ThumbLength: Integer;
begin
Result := FDelphiControl.ThumbLength;
end;
function TTrackBarX.Get_TickMarks: TxTickMark;
begin
Result := Ord(FDelphiControl.TickMarks);
end;
function TTrackBarX.Get_TickStyle: TxTickStyle;
begin
Result := Ord(FDelphiControl.TickStyle);
end;
function TTrackBarX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TTrackBarX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TTrackBarX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TTrackBarX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TTrackBarX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TTrackBarX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TTrackBarX.AboutBox;
begin
ShowTrackBarXAbout;
end;
procedure TTrackBarX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TTrackBarX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TTrackBarX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TTrackBarX.Set_Ctl3D(Value: WordBool);
begin
FDelphiControl.Ctl3D := Value;
end;
procedure TTrackBarX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TTrackBarX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TTrackBarX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TTrackBarX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TTrackBarX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TTrackBarX.Set_Frequency(Value: Integer);
begin
FDelphiControl.Frequency := Value;
end;
procedure TTrackBarX.Set_LineSize(Value: Integer);
begin
FDelphiControl.LineSize := Value;
end;
procedure TTrackBarX.Set_Max(Value: Integer);
begin
FDelphiControl.Max := Value;
end;
procedure TTrackBarX.Set_Min(Value: Integer);
begin
FDelphiControl.Min := Value;
end;
procedure TTrackBarX.Set_Orientation(Value: TxTrackBarOrientation);
begin
FDelphiControl.Orientation := TTrackBarOrientation(Value);
end;
procedure TTrackBarX.Set_PageSize(Value: Integer);
begin
FDelphiControl.PageSize := Value;
end;
procedure TTrackBarX.Set_ParentCtl3D(Value: WordBool);
begin
FDelphiControl.ParentCtl3D := Value;
end;
procedure TTrackBarX.Set_Position(Value: Integer);
begin
FDelphiControl.Position := Value;
end;
procedure TTrackBarX.Set_SelEnd(Value: Integer);
begin
FDelphiControl.SelEnd := Value;
end;
procedure TTrackBarX.Set_SelStart(Value: Integer);
begin
FDelphiControl.SelStart := Value;
end;
procedure TTrackBarX.Set_SliderVisible(Value: WordBool);
begin
FDelphiControl.SliderVisible := Value;
end;
procedure TTrackBarX.Set_ThumbLength(Value: Integer);
begin
FDelphiControl.ThumbLength := Value;
end;
procedure TTrackBarX.Set_TickMarks(Value: TxTickMark);
begin
FDelphiControl.TickMarks := TTickMark(Value);
end;
procedure TTrackBarX.Set_TickStyle(Value: TxTickStyle);
begin
FDelphiControl.TickStyle := TTickStyle(Value);
end;
procedure TTrackBarX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TTrackBarX.SetTick(Value: Integer);
begin
FDelphiControl.SetTick(Value);
end;
procedure TTrackBarX.ChangeEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnChange;
end;
procedure TTrackBarX.KeyPressEvent(Sender: TObject; var Key: Char);
var
TempKey: Smallint;
begin
TempKey := Smallint(Key);
if FEvents <> nil then FEvents.OnKeyPress(TempKey);
Key := Char(TempKey);
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TTrackBarX,
TTrackBar,
Class_TrackBarX,
36,
'{695CDBED-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
unit IniUtils;
interface
function GetIniFile(out AIniFileName: String):boolean;
function GetValue(const ASection,AParamName,ADefault: String): String;
function GetValueInt(const ASection,AParamName: String; ADefault : Integer): Integer;
//возвраащет тип кассового аппарата;
function iniCashType:String;
//возвращает № кассового места
function iniCashID: Integer;
//возвращает SoldParalel
function iniSoldParallel:Boolean;
//возвращает порт кассового аппарата
function iniPortNumber:String;
//возвращает скорость порта
function iniPortSpeed:String;
//Возвращает путь к локальной базе данных
function iniLocalDataBaseHead: String;
function iniLocalDataBaseBody: String;
function iniLocalDataBaseDiff: String;
//Возвращает код Аптеки
function iniLocalUnitCodeGet: Integer;
function iniLocalUnitCodeSave(AFarmacyCode: Integer): Integer;
//Возвращает имя Аптеки
function iniLocalUnitNameGet: string;
function iniLocalUnitNameSave(AFarmacyName: string): string;
//Возвращает GUID
function iniLocalGUIDGet: string;
function iniLocalGUIDSave(AGUID: string): string;
function iniLocalGUIDNew: string;
function iniCashSerialNumber: String;
//возвращает номер налоговой группы для FP320
function iniTaxGroup7:Integer;
//возвраащет тип POS-терминала;
function iniPosType(ACode : integer):String;
//возвращает порт POS-терминала
function iniPosPortNumber(ACode : integer):Integer;
//возвращает скорость порта POS-терминала
function iniPosPortSpeed(ACode : integer):Integer;
//логировать сообщения от РРО
function iniLog_RRO : Boolean;
//Регистрационный номер текущего кассового аппарата
function iniLocalCashRegisterGet: string;
function iniLocalCashRegisterSave(ACashRegister: string): string;
//Запись информации о старте программы
procedure InitCashSession(ACheckCashSession : Boolean);
function UpdateOption : Boolean;
function NeedTestProgram : Boolean;
function UpdateTestProgram : Boolean;
// Проверка и обновление программы
procedure AutomaticUpdateProgram;
// Проверка и обновление программы для теста
procedure AutomaticUpdateProgramTest;
var gUnitName, gUserName, gPassValue: string;
var gUnitId, gUnitCode : Integer;
var isMainForm_OLD : Boolean;
implementation
uses
iniFiles, Controls, Classes, SysUtils, Forms, vcl.Dialogs, dsdDB, Data.DB,
UnilWin, FormStorage, Updater;
const
FileName: String = '\DEFAULTS.INI';
LocalDBNameHead: String = 'FarmacyCashHead.dbf';
LocalDBNameBody: String = 'FarmacyCashBody.dbf';
LocalDBNameDiff: String = 'FarmacyCashDiff.dbf';
function GetIniFile(out AIniFileName: String):boolean;
var
dir: string;
f: TIniFile;
Begin
result := False;
dir := ExtractFilePath(Application.exeName)+'ini';
if not DirectoryExists(dir) AND not ForceDirectories(dir) then
Begin
ShowMessage('Пользователь не может получить доступ к файлу настроек.'+#13+
'Дальнейшая работа программы невозможна.'+#13+
'Сообщите администратору.');
exit;
End;
if not FileExists(dir + FileName) then
Begin
f := TiniFile.Create(dir + FileName);
try
try
AIniFileName := dir + FileName;
F.WriteString('Common','SoldParallel','false');
F.WriteString('Common','LocalDataBaseHead',ExtractFilePath(Application.ExeName)+LocalDBNameHead);
F.WriteString('Common','LocalDataBaseBody',ExtractFilePath(Application.ExeName)+LocalDBNameBody);
F.WriteString('Common','LocalDataBaseDiff',ExtractFilePath(Application.ExeName)+LocalDBNameDiff);
F.WriteString('TSoldWithCompMainForm','CashType','FP3530T_NEW');
F.WriteString('TSoldWithCompMainForm','CashId','0');
F.WriteString('TSoldWithCompMainForm','PortNumber','1');
F.WriteString('TSoldWithCompMainForm','PortSpeed','19200');
Except
ShowMessage('Пользователь не может получить доступ к файлу настроек. Дальнейшая работа программы невозможна. Сообщите администратору.');
exit;
end;
finally
f.Free;
end;
End
else
AIniFileName := dir+FileName;
result := True;
End;
function GetValue(const ASection,AParamName,ADefault: String): String;
var
ini: TiniFile;
IniFileName : String;
Begin
if not GetIniFile(IniFileName) then
Begin
Result := '';
exit;
End;
ini := TiniFile.Create(IniFileName);
Result := ini.ReadString(ASection,AParamName,ADefault);
ini.Free;
End;
function GetValueInt(const ASection,AParamName: String; ADefault : Integer): Integer;
var
ini: TiniFile;
IniFileName : String;
Begin
if not GetIniFile(IniFileName) then
Begin
Result := 0;
exit;
End;
ini := TiniFile.Create(IniFileName);
Result := ini.ReadInteger(ASection,AParamName,ADefault);
ini.Free;
End;
function iniCashType:String;
begin
Result := GetValue('TSoldWithCompMainForm','CashType','FP3530T_NEW');
end;
function iniCashID: Integer;
Begin
if not TryStrToInt(GetValue('TSoldWithCompMainForm','CashId','0'),Result) then
Result := 0;
End;
function iniSoldParallel:Boolean;
Begin
Result := GetValue('Common','SoldParallel','false') = 'true';
End;
function iniPortNumber:String;
begin
Result := GetValue('TSoldWithCompMainForm','PortNumber','1');
end;
function iniPortSpeed:String;
begin
Result := GetValue('TSoldWithCompMainForm','PortSpeed','19200');
end;
//Возвращает путь к локальной базе данных
function iniLocalDataBaseHead: String;
var
f: TIniFile;
begin
Result := GetValue('Common','LocalDataBaseHead','');
if Result = '' then
Begin
Result := ExtractFilePath(Application.ExeName)+LocalDBNameHead;
f := TIniFile.Create(ExtractFilePath(Application.ExeName)+'ini\'+FileName);
try
f.WriteString('Common','LocalDataBaseHead',Result);
finally
f.Free;
end;
End;
end;
function iniLocalDataBaseBody: String;
var
f: TIniFile;
begin
Result := GetValue('Common','LocalDataBaseBody','');
if Result = '' then
Begin
Result := ExtractFilePath(Application.ExeName)+LocalDBNameBody;
f := TIniFile.Create(ExtractFilePath(Application.ExeName)+'ini\'+FileName);
try
f.WriteString('Common','LocalDataBaseBody',Result);
finally
f.Free;
end;
End;
end;
function iniLocalDataBaseDiff: String;
var
f: TIniFile;
begin
Result := GetValue('Common','LocalDataBaseDiff','');
if Result = '' then
Begin
Result := ExtractFilePath(Application.ExeName)+LocalDBNameDiff;
f := TIniFile.Create(ExtractFilePath(Application.ExeName)+'ini\'+FileName);
try
f.WriteString('Common','LocalDataBaseDiff',Result);
finally
f.Free;
end;
End;
end;
function iniLocalUnitCodeGet: Integer;
begin
Result := GetValueInt('Common','FarmacyCode', 0);
end;
function iniLocalUnitCodeSave(AFarmacyCode: Integer): Integer;
var
f: TIniFile;
begin
Result := GetValueInt('Common','FarmacyCode', 0);
if Result <> AFarmacyCode then
Begin
Result := AFarmacyCode;
f := TIniFile.Create(ExtractFilePath(Application.ExeName)+'ini\'+FileName);
try
f.WriteInteger('Common','FarmacyCode',Result);
finally
f.Free;
end;
End;
end;
function iniLocalUnitNameGet: string;
begin
Result := GetValue('Common','FarmacyName', '');
end;
function iniLocalUnitNameSave(AFarmacyName: string): string;
var
f: TIniFile;
begin
Result := GetValue('Common','FarmacyName', '');
if Result <> AFarmacyName then
Begin
Result := AFarmacyName;
f := TIniFile.Create(ExtractFilePath(Application.ExeName)+'ini\'+FileName);
try
f.WriteString('Common','FarmacyName',Result);
finally
f.Free;
end;
End;
end;
function iniLocalGUIDGet: string;
begin
Result := GetValue('Common','CashSessionGUID', '');
end;
function iniLocalGUIDSave(AGUID: string): string;
var
f: TIniFile;
begin
Result := GetValue('Common','CashSessionGUID', '');
if Result = '' then
Begin
Result := AGUID;
f := TIniFile.Create(ExtractFilePath(Application.ExeName)+'ini\'+FileName);
try
f.WriteString('Common','CashSessionGUID',Result);
finally
f.Free;
end;
End;
end;
function iniLocalGUIDNew: string;
var
f: TIniFile;
G: TGUID;
begin
CreateGUID(G);
Result := GUIDToString(G);
f := TIniFile.Create(ExtractFilePath(Application.ExeName)+'ini\'+FileName);
try
f.WriteString('Common','CashSessionGUID',Result);
finally
f.Free;
end;
end;
function iniCashSerialNumber: String;
begin
Result := GetValue('TSoldWithCompMainForm','FP320SERIAL','');
End;
//возвращает номер налоговой группы для FP320 7%
function iniTaxGroup7:Integer;
var
s: String;
begin
S := GetValue('TSoldWithCompMainForm','FP320_TAX7','1');
if not tryStrToInt(S,Result) then
Result := 1;
End;
//возвраащет тип POS-терминала;
function iniPosType(ACode : integer):String;
begin
Result := GetValue('TSoldWithCompMainForm','PosType' + IntToStr(ACode),'');
end;
//возвращает порт POS-терминала
function iniPosPortNumber(ACode : integer):Integer;
var
S: String;
begin
S := GetValue('TSoldWithCompMainForm','PosPortNumber' + IntToStr(ACode),'');
if not tryStrToInt(S,Result) then
Result := 0;
end;
//возвращает скорость порта POS-терминала
function iniPosPortSpeed(ACode : integer):Integer;
var
S: String;
begin
S := GetValue('TSoldWithCompMainForm','PosPortSpeed' + IntToStr(ACode),'');
if not tryStrToInt(S,Result) then
Result := 0;
end;
//логировать сообщения от РРО
function iniLog_RRO: Boolean;
var
S: String;
begin
S := GetValue('TSoldWithCompMainForm','Log_RRO', 'False');
if not TryStrToBool(S, Result) then Result := False;
end;
function iniLocalCashRegisterGet: string;
begin
Result := GetValue('Common','CashRegister', '');
end;
function iniLocalCashRegisterSave(ACashRegister: string): string;
var
f: TIniFile;
begin
Result := GetValue('Common','CashRegister', '');
if (ACashRegister <> '') and (Result <> ACashRegister) then
Begin
Result := ACashRegister;
f := TIniFile.Create(ExtractFilePath(Application.ExeName)+'ini\'+FileName);
try
f.WriteString('Common','CashRegister',Result);
finally
f.Free;
end;
End;
end;
procedure CheckCashSession;
var
sp : TdsdStoredProc;
begin
sp := TdsdStoredProc.Create(nil);
try
try
sp.OutputType := otResult;
sp.StoredProcName := 'gpGet_CashSession_Busy';
sp.Params.Clear;
sp.Params.AddParam('inCashSessionId', ftString, ptInput, iniLocalGUIDGet);
sp.Params.AddParam('outisBusy', ftBoolean, ptOutput, False);
sp.Execute;
if sp.Params.ParamByName('outisBusy').Value then iniLocalGUIDNew;
except
end;
finally
freeAndNil(sp);
end;
end;
procedure InitCashSession(ACheckCashSession : Boolean);
var
sp : TdsdStoredProc;
begin
if ACheckCashSession then CheckCashSession;
sp := TdsdStoredProc.Create(nil);
try
try
sp.OutputType := otResult;
sp.StoredProcName := 'gpInsertUpdate_CashSession';
sp.Params.Clear;
sp.Params.AddParam('inCashSessionId', ftString, ptInput, iniLocalGUIDGet);
sp.Execute;
except
end;
finally
freeAndNil(sp);
end;
end;
function UpdateOption : Boolean;
var
sp : TdsdStoredProc;
begin
Result := False;
sp := TdsdStoredProc.Create(nil);
try
try
sp.OutputType := otResult;
sp.StoredProcName := 'gpUpdate_CashSession_StartUpdate';
sp.Params.Clear;
sp.Params.AddParam('inCashSessionId', ftString, ptInput, iniLocalGUIDGet);
sp.Params.AddParam('outStartOk', ftBoolean, ptOutput, False);
sp.Params.AddParam('outMessage', ftString, ptOutput, '');
sp.Execute;
Result := sp.Params.ParamByName('outStartOk').Value;
if not Result then
begin
ShowMessage(sp.Params.ParamByName('outMessage').Value);
end;
except
end;
finally
freeAndNil(sp);
end;
end;
function NeedTestProgram : Boolean;
var
sp : TdsdStoredProc;
begin
Result := False;
sp := TdsdStoredProc.Create(nil);
try
try
sp.OutputType := otResult;
sp.StoredProcName := 'gpGet_CheckoutTesting_CashGUID';
sp.Params.Clear;
sp.Params.AddParam('inCashSessionId', ftString, ptInput, iniLocalGUIDGet);
sp.Params.AddParam('outOk', ftBoolean, ptOutput, False);
sp.Execute;
Result := sp.Params.ParamByName('outOk').Value;
except
end;
finally
freeAndNil(sp);
end;
end;
function UpdateTestProgram : Boolean;
var
sp : TdsdStoredProc;
begin
Result := True;
sp := TdsdStoredProc.Create(nil);
try
try
sp.OutputType := otResult;
sp.StoredProcName := 'gpUpdate_Object_CheckoutTesting_Cash';
sp.Params.Clear;
sp.Params.AddParam('inCashSessionId', ftString, ptInput, iniLocalGUIDGet);
sp.Execute;
except
Result := False;
end;
finally
freeAndNil(sp);
end;
end;
procedure AutomaticUpdateProgram;
var LocalVersionInfo, BaseVersionInfo: TVersionInfo;
begin
try
Application.ProcessMessages;
BaseVersionInfo := TdsdFormStorageFactory.GetStorage.LoadFileVersion(ExtractFileName(ParamStr(0)),
GetBinaryPlatfotmSuffics(ParamStr(0), ''));
LocalVersionInfo := UnilWin.GetFileVersion(ParamStr(0));
if (BaseVersionInfo.VerHigh > LocalVersionInfo.VerHigh) or
((BaseVersionInfo.VerHigh = LocalVersionInfo.VerHigh) and (BaseVersionInfo.VerLow > LocalVersionInfo.VerLow)) then
begin
if MessageDlg('Обнаружена новая версия программы! Обновить?', mtInformation, mbOKCancel, 0) = mrOk then
if UpdateOption then TUpdater.AutomaticUpdateProgramStart;
end;
except
on E: Exception do
ShowMessage('Не работает автоматическое обновление.'#13#10'Обратитесь к разработчику.'#13#10 + E.Message);
end;
end;
// Проверка и обновление программы для теста
procedure AutomaticUpdateProgramTest;
begin
try
Application.ProcessMessages;
if NeedTestProgram then
begin
if MessageDlg('Обнаружена тестовая версия программы! Обновить?', mtInformation, mbOKCancel, 0) = mrOk then
begin
if TUpdater.AutomaticUpdateProgramTestStart then
begin
UpdateTestProgram;
Application.Terminate
end;
end;
end;
except
on E: Exception do
ShowMessage('Не работает автоматическое обновление.'#13#10'Обратитесь к разработчику.'#13#10 + E.Message);
end;
end;
end.
|
unit Example1.Form;
interface
{ Example showing the use of the uDataSetHelper unit }
uses
System.Classes,
Data.DB, Datasnap.DBClient,
Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Forms, Vcl.Grids, Vcl.DBGrids;
type
TForm1 = class(TForm)
MemOutput: TMemo;
PnlTop: TPanel;
PnlMain: TPanel;
BtnListEmployees: TButton;
BtnListCustomers: TButton;
GrdEmployee: TDBGrid;
DsEmployee: TDataSource;
GrdCustomer: TDBGrid;
DsCustomer: TDataSource;
QuEmployee: TClientDataSet;
QuCustomer: TClientDataSet;
procedure FormCreate(Sender: TObject);
procedure BtnListEmployeesClick(Sender: TObject);
procedure BtnListCustomersClick(Sender: TObject);
procedure GrdCustomerDblClick(Sender: TObject);
procedure GrdEmployeeDblClick(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
uses
System.Sysutils,
Vcl.Dialogs,
MidasLib,
urs.DataSetHelper;
{$R *.dfm}
type
TEmployee = record
EmpNo: Integer;
LastName: string;
FirstName: string;
PhoneExt: string;
HireDate: TDateTime;
Salary: Double;
end;
TCustomer = class
private
[DBField('CustNo')]
FCustNo: Double;
FCompany: string;
FAddress1: string;
FAddress2: string;
FCity: string;
FState: string;
[DBField('Zip')]
FZipCode: string;
FCountry: string;
FPhone: string;
FFAX: string;
FTaxRate: Double;
FContact: string;
FLastInvoiceDate: TDateTime;
function GetCustNo: Integer;
procedure SetCustNo(const Value: Integer);
public
[DBField('Addr1')]
property Address1: string read FAddress1 write FAddress1;
[DBField('Addr2')]
property Address2: string read FAddress2 write FAddress2;
property City: string read FCity write FCity;
property Company: string read FCompany write FCompany;
property Contact: string read FContact write FContact;
property Country: string read FCountry write FCountry;
[DBField(false)]
property CustNo: Integer read GetCustNo write SetCustNo;
property FAX: string read FFAX write FFAX;
property LastInvoiceDate: TDateTime read FLastInvoiceDate write FLastInvoiceDate;
property Phone: string read FPhone write FPhone;
property State: string read FState write FState;
property TaxRate: Double read FTaxRate write FTaxRate;
property ZipCode: string read FZipCode write FZipCode;
end;
type
[DBFields(mapManual)]
TSomeManuallyMappedClass = class
private
[DBField('SomeDBFieldName')]
FSomeField: Integer;
[DBField('SomeOtherDBFieldName')]
FSomeOtherField: string;
FSomeNotMappedField: Double;
public
property SomeField: Integer read FSomeField write FSomeField;
property SomeOtherField: string read FSomeOtherField write FSomeOtherField;
end;
function TCustomer.GetCustNo: Integer;
begin
result := Round(FCustNo);
end;
procedure TCustomer.SetCustNo(const Value: Integer);
begin
FCustNo := Value;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
QuEmployee.Active := true;
QuCustomer.Active := true;
end;
procedure TForm1.BtnListEmployeesClick(Sender: TObject);
var
Employee: TEmployee;
S: string;
begin
{ List all emplyoees with First- and LastName in the Memo. Employees hired
before 01/01/1991 are marked with an * in front of their names. }
MemOutput.Lines.BeginUpdate;
try
MemOutput.Lines.Clear;
for Employee in QuEmployee.Records<TEmployee> do begin
S := Trim(Format('%s %s', [Employee.FirstName, Employee.LastName]));
if Employee.HireDate < EncodeDate(1991, 1, 1) then
S := '*' + S;
MemOutput.Lines.Add(S);
end;
finally
MemOutput.Lines.EndUpdate;
end;
end;
procedure TForm1.BtnListCustomersClick(Sender: TObject);
var
Customer: TCustomer;
S: string;
begin
{ List all Customers with their Name and City in the Memo. Customers outside
the US have their Country enclosed in brackets appended. }
MemOutput.Lines.BeginUpdate;
try
MemOutput.Lines.Clear;
Customer := TCustomer.Create;
try
for Customer in QuCustomer.Records(Customer) do begin
S := Format('%d: %s - %s %s', [Customer.CustNo, Customer.Company, Customer.ZipCode, Customer.City]);
if Customer.Country <> 'US' then
S := S + ' (' + Customer.Country + ')';
MemOutput.Lines.Add(S);
end;
finally
Customer.Free;
end;
finally
MemOutput.Lines.EndUpdate;
end;
end;
procedure TForm1.GrdCustomerDblClick(Sender: TObject);
var
Customer: TCustomer;
begin
{ Set LastInvoiceDate to current date/time }
Customer := TCustomer.Create;
try
QuCustomer.LoadInstanceFromCurrent(Customer);
Customer.LastInvoiceDate := Now;
QuCustomer.Edit;
QuCustomer.StoreInstanceToCurrent(Customer);
QuCustomer.Post;
finally
Customer.Free;
end;
end;
procedure TForm1.GrdEmployeeDblClick(Sender: TObject);
var
Employee: TEmployee;
begin
{ Show the employee's name and the hire date. }
Employee := QuEmployee.GetCurrentRec<TEmployee>;
ShowMessage(Format('%s %s was hired on %s', [Employee.FirstName, Employee.LastName, FormatDateTime('dddddd', Employee.HireDate)]));
end;
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/primitives/transaction.h
// Bitcoin file: src/primitives/transaction.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_TOutPoint;
interface
// /** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
uint32_t n;
static constexpr uint32_t NULL_INDEX = std::numeric_limits<uint32_t>::max();
COutPoint(): n(NULL_INDEX) { }
COutPoint(const uint256& hashIn, uint32_t nIn): hash(hashIn), n(nIn) { }
SERIALIZE_METHODS(COutPoint, obj) { READWRITE(obj.hash, obj.n); }
void SetNull() { hash.SetNull(); n = NULL_INDEX; }
bool IsNull() const { return (hash.IsNull() && n == NULL_INDEX); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
int cmp = a.hash.Compare(b.hash);
return cmp < 0 || (cmp == 0 && a.n < b.n);
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const;
};
implementation
std::string COutPoint::ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n);
}
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Layouts;
{$I FMX.Defines.inc}
{$H+}
interface
uses
System.Classes, System.Types, System.UITypes,
FMX.Types, FMX.Ani, FMX.Controls;
type
{ TLayout }
TLayout = class(TControl)
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Paint; override;
published
property HitTest default False;
end;
{ TScaledLayout }
TScaledLayout = class(TControl)
private
FOriginalWidth: Single;
FOriginalHeight: Single;
procedure SetOriginalWidth(const Value: Single);
procedure SetOriginalHeight(const Value: Single);
protected
function GetChildrenMatrix: TMatrix; override;
procedure SetHeight(const Value: Single); override;
procedure SetWidth(const Value: Single); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Paint; override;
procedure Realign; override;
published
property OriginalWidth: Single read FOriginalWidth write SetOriginalWidth;
property OriginalHeight: Single read FOriginalHeight write SetOriginalHeight;
end;
{ TScrollContent }
TScrollContent = class(TContent)
protected
function GetClipRect: TRectF; override;
function ObjectAtPoint(P: TPointF): IControl; override;
function GetUpdateRect: TRectF; override;
public
constructor Create(AOwner: TComponent); override;
procedure AddObject(AObject: TFmxObject); override;
procedure RemoveObject(AObject: TFmxObject); override;
end;
{ TScrollBox }
TScrollBox = class(TStyledControl)
private
FAutoHide: Boolean;
FDisableMouseWheel: Boolean;
FDown: Boolean;
FHScrollAni: TFloatAnimation;
FHScrollTrack: single;
FHScrollTrackMinAni: TFloatAnimation;
FHScrollTrackMaxAni: TFloatAnimation;
FVScrollAni: TFloatAnimation;
FVScrollTrack: single;
FVScrollTrackMinAni: TFloatAnimation;
FVScrollTrackMaxAni: TFloatAnimation;
FAnimated: Boolean;
FShowScrollBars: Boolean;
FShowSizeGrip: Boolean;
FMouseTracking: Boolean;
FUseSmallScrollBars: Boolean;
procedure SetShowScrollBars(const Value: Boolean);
procedure SetShowSizeGrip(const Value: Boolean);
procedure SetUseSmallScrollBars(const Value: Boolean);
function GetVScrollBar: TScrollBar;
function GetHScrollBar: TScrollBar;
procedure CreateVScrollTrackAni;
procedure CreateHScrollTrackAni;
protected
FScrollDesign: TPointF;
FContent: TScrollContent;
FHScrollBar: TScrollBar;
FVScrollBar: TScrollBar;
FContentLayout: TControl;
FDownPos: TPointF;
FLastDelta: TPointF;
FCurrentPos: TPointF;
{ VCL }
procedure Loaded; override;
procedure DefineProperties(Filer: TFiler); override;
procedure ReadScrollDesign(Reader: TReader);
procedure WriteScrollDesign(Writer: TWriter);
{ }
procedure ContentAddObject(AObject: TFmxObject); virtual;
procedure ContentBeforeRemoveObject(AObject: TFmxObject); virtual;
procedure ContentRemoveObject(AObject: TFmxObject); virtual;
procedure HScrollChange(Sender: TObject); virtual;
procedure VScrollChange(Sender: TObject); virtual;
procedure ApplyStyle; override;
procedure FreeStyle; override;
procedure CreateVScrollAni;
procedure CreateHScrollAni;
function ContentRect: TRectF;
function VScrollBarValue: Single;
function HScrollBarValue: Single;
function GetContentBounds: TRectF; virtual;
procedure RealignContent(R: TRectF); virtual;
property ContentLayout: TControl read FContentLayout;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddObject(AObject: TFmxObject); override;
procedure Sort(Compare: TFmxObjectSortCompare); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseMove(Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); override;
procedure Realign; override;
procedure Center;
procedure ScrollTo(const Dx, Dy: Single);
procedure InViewRect(const Rect: TRectF);
function ClientWidth: Single;
function ClientHeight: Single;
property HScrollBar: TScrollBar read GetHScrollBar;
property VScrollBar: TScrollBar read GetVScrollBar;
published
property AutoHide: Boolean read FAutoHide write FAutoHide default True;
property Animated: Boolean read FAnimated write FAnimated default True;
property DisableMouseWheel: Boolean read FDisableMouseWheel write FDisableMouseWheel default False;
property MouseTracking: Boolean read FMouseTracking write FMouseTracking default False;
property ShowScrollBars: Boolean read FShowScrollBars write SetShowScrollBars default True;
property ShowSizeGrip: Boolean read FShowSizeGrip write SetShowSizeGrip default False;
property UseSmallScrollBars: Boolean read FUseSmallScrollBars write SetUseSmallScrollBars default False;
end;
{ TVertScrollBox }
TVertScrollBox = class(TScrollBox)
protected
function GetContentBounds: TRectF; override;
public
constructor Create(AOwner: TComponent); override;
end;
{ TFramedScrollBox }
TFramedScrollBox = class(TScrollBox)
end;
{ TFramedVertScrollBox }
TFramedVertScrollBox = class(TVertScrollBox)
public
constructor Create(AOwner: TComponent); override;
end;
{ TGridLayout }
TGridLayout = class(TControl)
private
FItemWidth: Single;
FItemHeight: Single;
FOrientation: TOrientation;
procedure SetItemHeight(const Value: Single);
procedure SetItemWidth(const Value: Single);
procedure SetOrientation(const Value: TOrientation);
protected
procedure Realign; override;
public
constructor Create(AOwner: TComponent); override;
procedure AddObject(AObject: TFmxObject); override;
published
property ItemHeight: Single read FItemHeight write SetItemHeight;
property ItemWidth: Single read FItemWidth write SetItemWidth;
property Orientation: TOrientation read FOrientation write SetOrientation;
end;
implementation
{ TLayout }
constructor TLayout.Create(AOwner: TComponent);
begin
inherited;
HitTest := False;
end;
destructor TLayout.Destroy;
begin
inherited;
end;
procedure TLayout.Paint;
var
R: TRectF;
begin
if (csDesigning in ComponentState) and not Locked and not FInPaintTo then
begin
R := LocalRect;
InflateRect(R, -0.5, -0.5);
Canvas.StrokeThickness := 1;
Canvas.StrokeDash := TStrokeDash.sdDash;
Canvas.Stroke.Kind := TBrushKind.bkSolid;
Canvas.Stroke.Color := $A0909090;
Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity);
Canvas.StrokeDash := TStrokeDash.sdSolid;
end;
end;
{ TScrollContent }
constructor TScrollContent.Create(AOwner: TComponent);
begin
inherited;
ClipChildren := True;
SetAcceptsControls(False);
end;
function TScrollContent.GetClipRect: TRectF;
begin
if (Parent <> nil) and (Parent is TScrollBox) and
(TScrollBox(Parent).ContentLayout <> nil) then
begin
Result := TScrollBox(Parent).ContentLayout.LocalRect;
if (TScrollBox(Parent).VScrollBar <> nil) and
(TScrollBox(Parent).VScrollBar.Enabled) then
OffsetRect(Result, 0, TScrollBox(Parent).VScrollBar.Value);
if (TScrollBox(Parent).HScrollBar <> nil) and
(TScrollBox(Parent).HScrollBar.Enabled) then
OffsetRect(Result, TScrollBox(Parent).HScrollBar.Value, 0);
end
else
Result := inherited GetClipRect;
end;
function TScrollContent.ObjectAtPoint(P: TPointF): IControl;
begin
Result := inherited ObjectAtPoint(P);
if Result <> nil then
begin
if FScene <> nil then
P := FScene.ScreenToLocal(P);
P := AbsoluteToLocal(P);
if not PointInRect(P, ClipRect) then
Result := nil;
end;
end;
procedure TScrollContent.AddObject(AObject: TFmxObject);
begin
inherited;
if (Parent <> nil) and (Parent is TScrollBox) then
TScrollBox(Parent).ContentAddObject(AObject);
end;
procedure TScrollContent.RemoveObject(AObject: TFmxObject);
begin
if (Parent <> nil) and (Parent is TScrollBox) then
TScrollBox(Parent).ContentBeforeRemoveObject(AObject);
inherited;
if (Parent <> nil) and (Parent is TScrollBox) then
TScrollBox(Parent).ContentRemoveObject(AObject);
end;
function TScrollContent.GetUpdateRect: TRectF;
begin
if FRecalcUpdateRect then
begin
if (Parent <> nil) and (Parent is TScrollBox) then
begin
if (TScrollBox(Parent).ContentLayout <> nil) then
FUpdateRect := TScrollBox(Parent).ContentLayout.UpdateRect
else
FUpdateRect := TScrollBox(Parent).UpdateRect;
end;
end;
Result := FUpdateRect;
end;
{ TScrollBox }
constructor TScrollBox.Create(AOwner: TComponent);
begin
inherited;
AutoCapture := True;
FAnimated := True;
FAutoHide := True;
FShowScrollBars := True;
FContent := TScrollContent.Create(Self);
FContent.Parent := Self;
FContent.Stored := False;
FContent.Locked := True;
FContent.HitTest := False;
end;
destructor TScrollBox.Destroy;
begin
FContent := nil;
inherited;
end;
procedure TScrollBox.FreeStyle;
begin
inherited;
FContentLayout := nil;
FHScrollBar := nil;
FVScrollBar := nil;
end;
procedure TScrollBox.ApplyStyle;
var
B: TFmxObject;
begin
inherited;
B := FindStyleResource('sizegrip');
if (B <> nil) and (B is TControl) then
TControl(B).Visible := FShowSizeGrip;
// hide all before align
B := FindStyleResource('vscrollbar');
if (B <> nil) and (B is TControl) then
TControl(B).Visible := False;
B := FindStyleResource('hscrollbar');
if (B <> nil) and (B is TControl) then
TControl(B).Visible := False;
B := FindStyleResource('vsmallscrollbar');
if (B <> nil) and (B is TControl) then
TControl(B).Visible := False;
B := FindStyleResource('hsmallscrollbar');
if (B <> nil) and (B is TControl) then
TControl(B).Visible := False;
if FUseSmallScrollBars then
begin
B := FindStyleResource('vsmallscrollbar');
if (B <> nil) and (B is TScrollBar) then
begin
FVScrollBar := TScrollBar(B);
FVScrollBar.OnChange := VScrollChange;
FVScrollBar.Locked := True;
if FVScrollBar.Tag = 0 then
FVScrollBar.Tag := Integer(FVScrollBar.Align);
end;
B := FindStyleResource('hsmallscrollbar');
if (B <> nil) and (B is TScrollBar) then
begin
FHScrollBar := TScrollBar(B);
FHScrollBar.OnChange := HScrollChange;
FHScrollBar.Locked := True;
if FHScrollBar.Tag = 0 then
FHScrollBar.Tag := Integer(FHScrollBar.Align);
end;
end;
if not FUseSmallScrollBars or ((FVScrollBar = nil) or (FHScrollBar = nil))
then
begin
B := FindStyleResource('vscrollbar');
if (B <> nil) and (B is TScrollBar) then
begin
FVScrollBar := TScrollBar(B);
FVScrollBar.OnChange := VScrollChange;
FVScrollBar.Locked := True;
if FVScrollBar.Tag = 0 then
FVScrollBar.Tag := Integer(FVScrollBar.Align);
end;
B := FindStyleResource('hscrollbar');
if (B <> nil) and (B is TScrollBar) then
begin
FHScrollBar := TScrollBar(B);
FHScrollBar.OnChange := HScrollChange;
FHScrollBar.Locked := True;
if FHScrollBar.Tag = 0 then
FHScrollBar.Tag := Integer(FHScrollBar.Align);
end;
end;
B := FindStyleResource('content');
if (B <> nil) and (B is TControl) then
FContentLayout := TControl(B);
Realign;
FVScrollAni := nil;
FHScrollAni := nil;
end;
function TScrollBox.GetContentBounds: TRectF;
var
i: Integer;
R, LocalR: TRectF;
begin
Result := RectF(0, 0, Width, Height);
if (FContent <> nil) and (ContentLayout <> nil) then
begin
R := ContentLayout.LocalRect;
for i := 0 to FContent.ChildrenCount - 1 do
if FContent.Children[i] is TControl then
if (TControl(FContent.Children[i]).Visible) then
begin
if (csDesigning in ComponentState) and not (csDesigning in FContent.Children[i].ComponentState) then Continue;
LocalR := TControl(FContent.Children[i]).ParentedRect;
R := UnionRect(R, LocalR);
end;
Result := R;
end;
end;
function TScrollBox.GetHScrollBar: TScrollBar;
begin
if FHScrollBar = nil then
ApplyStyleLookup;
Result := FHScrollBar;
end;
function TScrollBox.GetVScrollBar: TScrollBar;
begin
if FVScrollBar = nil then
ApplyStyleLookup;
Result := FVScrollBar;
end;
procedure TScrollBox.RealignContent(R: TRectF);
begin
if (FContent <> nil) and (ContentLayout <> nil) then
begin
FContent.SetBounds(R.Left, R.Top, RectWidth(R), RectHeight(R));
FContent.FRecalcUpdateRect := True; // need to recalc
end;
end;
procedure TScrollBox.Realign;
procedure IntAlign;
var
R: TRectF;
begin
R := GetContentBounds;
if RectWidth(R) * RectHeight(R) = 0 then
Exit;
OffsetRect(R, ContentLayout.Position.X, ContentLayout.Position.Y);
if (HScrollBar <> nil) and (HScrollBar.Enabled) then
OffsetRect(R, -FScrollDesign.X, 0);
if (VScrollBar <> nil) and (VScrollBar.Enabled) then
OffsetRect(R, 0, -FScrollDesign.Y);
RealignContent(R);
// realign resource
if (ContentLayout.Parent <> nil) and (ContentLayout.Parent is TControl) then
TControl(ContentLayout.Parent).BeginUpdate;
if (VScrollBar <> nil) then
begin
VScrollBar.Enabled := RectHeight(R) > ContentLayout.Height;
if FAutoHide then
VScrollBar.Visible := VScrollBar.Enabled;
if not FShowScrollBars then
begin
VScrollBar.Opacity := 0;
VScrollBar.Align := TAlignLayout.alNone;
end
else
begin
VScrollBar.Opacity := 1;
VScrollBar.Align := TAlignLayout(VScrollBar.Tag);
end;
end;
if (HScrollBar <> nil) then
begin
HScrollBar.Enabled := RectWidth(R) > ContentLayout.Width;
if FAutoHide then
HScrollBar.Visible := HScrollBar.Enabled;
if not FShowScrollBars then
begin
HScrollBar.Opacity := 0;
HScrollBar.Align := TAlignLayout.alNone;
end
else
begin
HScrollBar.Opacity := 1;
HScrollBar.Align := TAlignLayout(HScrollBar.Tag);
if (VScrollBar <> nil) and (VScrollBar.Enabled) then
HScrollBar.Padding.right := VScrollBar.Width;
end;
end;
if (ContentLayout.Parent <> nil) and (ContentLayout.Parent is TControl) then
begin
TControl(ContentLayout.Parent).EndUpdate;
TControl(ContentLayout.Parent).Realign;
end;
// align scrollbars
if (VScrollBar <> nil) then
begin
VScrollBar.Enabled := RectHeight(R) > ContentLayout.Height;
if FAutoHide then
VScrollBar.Visible := VScrollBar.Enabled;
if not FShowScrollBars then
begin
VScrollBar.Opacity := 0;
VScrollBar.Align := TAlignLayout.alNone;
VScrollBar.Position.Y := Width + 100;
end
else
begin
VScrollBar.Opacity := 1;
VScrollBar.HitTest := True;
VScrollBar.Align := TAlignLayout(VScrollBar.Tag);
end;
VScrollBar.BringToFront;
if VScrollBar.Visible and (ContentLayout <> nil) then
begin
VScrollBar.Max := RectHeight(R);
VScrollBar.TagFloat := VScrollBar.Max;
VScrollBar.ViewportSize := ContentLayout.Height;
VScrollBar.SmallChange := VScrollBar.ViewportSize / 5;
VScrollBar.Value := FScrollDesign.Y;
end
else
begin
VScrollBar.Value := 0;
end;
end;
if (HScrollBar <> nil) then
begin
HScrollBar.Enabled := RectWidth(R) > ContentLayout.Width;
HScrollBar.Padding.right := 0;
if FAutoHide then
HScrollBar.Visible := HScrollBar.Enabled;
if not FShowScrollBars then
begin
HScrollBar.Opacity := 0;
HScrollBar.Align := TAlignLayout.alNone;
HScrollBar.Position.Y := Height + 100;
end
else
begin
HScrollBar.Opacity := 1;
HScrollBar.Align := TAlignLayout(HScrollBar.Tag);
if (VScrollBar <> nil) and (VScrollBar.Enabled) then
HScrollBar.Padding.right := VScrollBar.Width;
end;
HScrollBar.BringToFront;
if HScrollBar.Visible and (ContentLayout <> nil) then
begin
HScrollBar.Max := RectWidth(R);
HScrollBar.TagFloat := HScrollBar.Max;
HScrollBar.ViewportSize := ContentLayout.Width;
HScrollBar.SmallChange := HScrollBar.ViewportSize / 5;
HScrollBar.Value := ContentLayout.Position.X - FContent.Position.X;
end
else
HScrollBar.Value := 0;
end;
end;
var
R, NewR: TRectF;
begin
if csDestroying in ComponentState then
Exit;
inherited;
if csLoading in ComponentState then
Exit;
if ContentLayout = nil then
Exit;
if FDisableAlign then
Exit;
if FUpdating > 0 then
Exit;
FDisableAlign := True;
try
R := ContentLayout.LocalRect;
IntAlign;
NewR := ContentLayout.LocalRect;
if (RectWidth(NewR) <> RectWidth(R)) or (RectHeight(NewR) <> RectHeight(R))
then
begin
IntAlign;
end;
finally
FDisableAlign := False;
end;
end;
function TScrollBox.ContentRect: TRectF;
begin
if ContentLayout <> nil then
Result := ContentLayout.ParentedRect
else
Result := LocalRect;
end;
function TScrollBox.VScrollBarValue: Single;
begin
if (VScrollBar <> nil) and (VScrollBar.Visible) then
Result := VScrollBar.Value
else
Result := 0;
end;
function TScrollBox.HScrollBarValue: Single;
begin
if (HScrollBar <> nil) and (HScrollBar.Visible) then
Result := HScrollBar.Value
else
Result := 0;
end;
procedure TScrollBox.HScrollChange(Sender: TObject);
begin
if ContentLayout = nil then
Exit;
if HScrollBar.Visible then
FContent.Position.X := ContentLayout.Position.X - HScrollBar.Value
else
FContent.Position.X := ContentLayout.Position.X;
FScrollDesign.X := HScrollBar.Value;
end;
procedure TScrollBox.VScrollChange(Sender: TObject);
begin
if ContentLayout = nil then
Exit;
if VScrollBar.Visible then
FContent.Position.Y := ContentLayout.Position.Y - VScrollBar.Value
else
FContent.Position.Y := ContentLayout.Position.Y;
FScrollDesign.Y := VScrollBar.Value;
end;
procedure TScrollBox.CreateHScrollAni;
begin
if FHScrollAni = nil then
begin
FHScrollAni := TFloatAnimation.Create(Self);
FHScrollAni.Parent := HScrollBar;
FHScrollAni.AnimationType := TAnimationType.atOut;
FHScrollAni.Interpolation := TInterpolationType.itQuadratic;
FHScrollAni.Duration := 0.7;
FHScrollAni.PropertyName := 'Value';
FHScrollAni.StartFromCurrent := True;
end;
end;
procedure TScrollBox.CreateHScrollTrackAni;
begin
if FHScrollTrackMinAni = nil then
begin
FHScrollTrackMinAni := TFloatAnimation.Create(Self);
FHScrollTrackMinAni.Parent := HScrollBar;
FHScrollTrackMinAni.AnimationType := TAnimationType.atOut;
FHScrollTrackMinAni.Interpolation := TInterpolationType.itQuadratic;
FHScrollTrackMinAni.Duration := 0.7;
FHScrollTrackMinAni.PropertyName := 'Min';
FHScrollTrackMinAni.StartFromCurrent := True;
end;
if FHScrollTrackMaxAni = nil then
begin
FHScrollTrackMaxAni := TFloatAnimation.Create(Self);
FHScrollTrackMaxAni.Parent := HScrollBar;
FHScrollTrackMaxAni.AnimationType := TAnimationType.atOut;
FHScrollTrackMaxAni.Interpolation := TInterpolationType.itQuadratic;
FHScrollTrackMaxAni.Duration := 0.7;
FHScrollTrackMaxAni.PropertyName := 'Max';
FHScrollTrackMaxAni.StartFromCurrent := True;
end;
end;
procedure TScrollBox.CreateVScrollAni;
begin
if FVScrollAni = nil then
begin
FVScrollAni := TFloatAnimation.Create(Self);
FVScrollAni.Parent := VScrollBar;
FVScrollAni.AnimationType := TAnimationType.atOut;
FVScrollAni.Interpolation := TInterpolationType.itQuadratic;
FVScrollAni.Duration := 0.7;
FVScrollAni.PropertyName := 'Value';
FVScrollAni.StartFromCurrent := True;
end;
end;
procedure TScrollBox.CreateVScrollTrackAni;
begin
if FVScrollTrackMinAni = nil then
begin
FVScrollTrackMinAni := TFloatAnimation.Create(Self);
FVScrollTrackMinAni.Parent := VScrollBar;
FVScrollTrackMinAni.AnimationType := TAnimationType.atOut;
FVScrollTrackMinAni.Interpolation := TInterpolationType.itQuadratic;
FVScrollTrackMinAni.Duration := 0.7;
FVScrollTrackMinAni.PropertyName := 'Min';
FVScrollTrackMinAni.StartFromCurrent := True;
end;
if FVScrollTrackMaxAni = nil then
begin
FVScrollTrackMaxAni := TFloatAnimation.Create(Self);
FVScrollTrackMaxAni.Parent := VScrollBar;
FVScrollTrackMaxAni.AnimationType := TAnimationType.atOut;
FVScrollTrackMaxAni.Interpolation := TInterpolationType.itQuadratic;
FVScrollTrackMaxAni.Duration := 0.7;
FVScrollTrackMaxAni.PropertyName := 'Max';
FVScrollTrackMaxAni.StartFromCurrent := True;
end;
end;
procedure TScrollBox.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Single);
begin
inherited;
if (Button = TMouseButton.mbLeft) and FMouseTracking then
begin
FLastDelta := PointF(0, 0);
FDownPos := PointF(X, Y);
FCurrentPos := PointF(X, Y);
FDown := True;
if (FVScrollAni <> nil) and FVScrollAni.Running then
FVScrollAni.StopAtCurrent;
if (FHScrollAni <> nil) and FHScrollAni.Running then
FHScrollAni.StopAtCurrent;
if (FVScrollTrackMinAni <> nil) and FVScrollTrackMinAni.Running then
FVScrollTrackMinAni.StopAtCurrent;
if (FVScrollTrackMaxAni <> nil) and FVScrollTrackMaxAni.Running then
FVScrollTrackMaxAni.StopAtCurrent;
if (FHScrollTrackMinAni <> nil) and FHScrollTrackMinAni.Running then
FHScrollTrackMinAni.StopAtCurrent;
if (FHScrollTrackMaxAni <> nil) and FHScrollTrackMaxAni.Running then
FHScrollTrackMaxAni.StopAtCurrent;
if (VScrollBar <> nil) then
FVScrollTrack := VScrollBar.Value;
if (HScrollBar <> nil) then
FHScrollTrack := HScrollBar.Value;
end;
end;
procedure TScrollBox.MouseMove(Shift: TShiftState; X, Y: Single);
begin
inherited;
if FDown and FMouseTracking then
begin
if (VScrollBar <> nil) and (VScrollBar.Visible) then
begin
VScrollBar.Value := VScrollBar.Value - (Y - FCurrentPos.Y);
FVScrollTrack := FVScrollTrack - (Y - FCurrentPos.Y);
if FVScrollTrack < 0 then
VScrollBar.Min := FVScrollTrack;
if FVScrollTrack > VScrollBar.Max - VScrollBar.ViewportSize then
VScrollBar.Max := FVScrollTrack + VScrollBar.ViewportSize;
FLastDelta.Y := (Y - FCurrentPos.Y);
end;
if (HScrollBar <> nil) and (HScrollBar.Visible) then
begin
HScrollBar.Value := HScrollBar.Value - (X - FCurrentPos.X);
FHScrollTrack := FHScrollTrack - (X - FCurrentPos.X);
if FHScrollTrack < 0 then
HScrollBar.Min := FHScrollTrack;
if FHScrollTrack > HScrollBar.Max - HScrollBar.ViewportSize then
HScrollBar.Max := FHScrollTrack + HScrollBar.ViewportSize;
FLastDelta.X := (X - FCurrentPos.X);
end;
FCurrentPos := PointF(X, Y);
end;
end;
procedure TScrollBox.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Single);
begin
inherited;
if FDown and FMouseTracking then
begin
FDown := False;
// animation
if FAnimated and (VScrollBar.Min < 0) and (FVScrollTrack <> VScrollBar.Value) and not ((FVScrollTrackMinAni <> nil) and (FVScrollTrackMinAni.Running)) then
begin
CreateVScrollTrackAni;
if FVScrollTrackMinAni.Running then
FVScrollTrackMinAni.StopAtCurrent
else
FVScrollTrackMinAni.StartValue := VScrollBar.Min;
FVScrollTrackMinAni.StopValue := 0;
FVScrollTrackMinAni.Start;
end
else
if FAnimated and (VScrollBar.Max > VScrollBar.TagFloat) and (FVScrollTrack <> VScrollBar.Value) and not ((FVScrollTrackMaxAni <> nil) and (FVScrollTrackMaxAni.Running)) then
begin
CreateVScrollTrackAni;
if FVScrollTrackMaxAni.Running then
FVScrollTrackMaxAni.StopAtCurrent
else
FVScrollTrackMaxAni.StartValue := VScrollBar.Max;
FVScrollTrackMaxAni.StopValue := VScrollBar.TagFloat;
FVScrollTrackMaxAni.Start;
end
else
if FAnimated and (HScrollBar.Min < 0) and (FHScrollTrack <> HScrollBar.Value) and not ((FHScrollTrackMinAni <> nil) and (FHScrollTrackMinAni.Running)) then
begin
CreateHScrollTrackAni;
if FHScrollTrackMinAni.Running then
FHScrollTrackMinAni.StopAtCurrent
else
FHScrollTrackMinAni.StartValue := HScrollBar.Min;
FHScrollTrackMinAni.StopValue := 0;
FHScrollTrackMinAni.Start;
end
else
if FAnimated and (HScrollBar.Max > HScrollBar.TagFloat) and (FHScrollTrack <> HScrollBar.Value) and not ((FHScrollTrackMaxAni <> nil) and (FHScrollTrackMaxAni.Running)) then
begin
CreateHScrollTrackAni;
if FHScrollTrackMaxAni.Running then
FHScrollTrackMaxAni.StopAtCurrent
else
FHScrollTrackMaxAni.StartValue := HScrollBar.Max;
FHScrollTrackMaxAni.StopValue := HScrollBar.TagFloat;
FHScrollTrackMaxAni.Start;
end
else
if FAnimated then
begin
if (VScrollBar <> nil) and (VScrollBar.Visible) and (FLastDelta.Y <> 0) then
begin
CreateVScrollAni;
if FVScrollAni.Running then
FVScrollAni.StopAtCurrent;
FVScrollAni.StopValue := VScrollBar.Value - (FLastDelta.Y * 7);
if FVScrollAni.StopValue < 0 then
begin
FVScrollBar.Min := FVScrollAni.StopValue;
CreateVScrollTrackAni;
if FVScrollTrackMinAni.Running then
FVScrollTrackMinAni.StopAtCurrent
else
FVScrollTrackMinAni.StartValue := VScrollBar.Min;
FVScrollTrackMinAni.StopValue := 0;
FVScrollTrackMinAni.Start;
end;
if FVScrollAni.StopValue > FVScrollBar.Max then
begin
FVScrollBar.Max := FVScrollAni.StopValue;
CreateVScrollTrackAni;
if FVScrollTrackMaxAni.Running then
FVScrollTrackMaxAni.StopAtCurrent
else
FVScrollTrackMaxAni.StartValue := VScrollBar.Max;
FVScrollTrackMaxAni.StopValue := VScrollBar.TagFloat;
FVScrollTrackMaxAni.Start;
end;
FVScrollAni.Start;
end;
if (HScrollBar <> nil) and (HScrollBar.Visible) and (FLastDelta.X <> 0) then
begin
CreateHScrollAni;
if FHScrollAni.Running then
FHScrollAni.StopAtCurrent;
FHScrollAni.StopValue := HScrollBar.Value - (FLastDelta.X * 7);
if FHScrollAni.StopValue < 0 then
begin
FHScrollBar.Min := FHScrollAni.StopValue;
CreateHScrollTrackAni;
if FHScrollTrackMinAni.Running then
FHScrollTrackMinAni.StopAtCurrent
else
FHScrollTrackMinAni.StartValue := HScrollBar.Min;
FHScrollTrackMinAni.StopValue := 0;
FHScrollTrackMinAni.Start;
end;
if FHScrollAni.StopValue > FHScrollBar.Max then
begin
FHScrollBar.Max := FHScrollAni.StopValue;
CreateHScrollTrackAni;
if FHScrollTrackMaxAni.Running then
FHScrollTrackMaxAni.StopAtCurrent
else
FHScrollTrackMaxAni.StartValue := HScrollBar.Max;
FHScrollTrackMaxAni.StopValue := HScrollBar.TagFloat;
FHScrollTrackMaxAni.Start;
end;
FHScrollAni.Start;
end;
end;
end;
end;
procedure TScrollBox.MouseWheel(Shift: TShiftState; WheelDelta: Integer;
var Handled: Boolean);
begin
inherited;
if not Handled and not(FDisableMouseWheel) and (VScrollBar <> nil) and (VScrollBar.Visible) then
begin
if FAnimated then
begin
CreateVScrollAni;
if FVScrollAni.Running then
FVScrollAni.StopAtCurrent;
FVScrollAni.StopValue := VScrollBar.Value -
(VScrollBar.SmallChange * 3 * (WheelDelta / 120));
FVScrollAni.Start;
end
else
VScrollBar.Value := VScrollBar.Value -
(VScrollBar.SmallChange * 3 * (WheelDelta / 120));
Handled := True;
end;
if not Handled and not(FDisableMouseWheel) and (HScrollBar <> nil) and
(HScrollBar.Visible) then
begin
if FAnimated then
begin
CreateHScrollAni;
if FHScrollAni.Running then
FHScrollAni.StopAtCurrent;
FHScrollAni.StopValue := HScrollBar.Value -
(HScrollBar.SmallChange * 3 * (WheelDelta / 120));
FHScrollAni.Start;
end
else
HScrollBar.Value := HScrollBar.Value -
(HScrollBar.SmallChange * 3 * (WheelDelta / 120));
Handled := True;
end;
end;
procedure TScrollBox.AddObject(AObject: TFmxObject);
begin
if (FContent <> nil) and (AObject <> FContent) and (AObject <> FResourceLink) and
not (AObject is TEffect) and not (AObject is TAnimation) then
begin
FContent.AddObject(AObject);
end
else
inherited;
end;
procedure TScrollBox.Loaded;
begin
inherited;
// ScrollTo(-FScrollDesign.X, -FScrollDesign.Y);
end;
procedure TScrollBox.Center;
begin
if (VScrollBar <> nil) and (VScrollBar.Visible) then
begin
VScrollBar.Value := (VScrollBar.Max - VScrollBar.ViewportSize) / 2;
end;
if (HScrollBar <> nil) and (HScrollBar.Visible) then
begin
HScrollBar.Value := (HScrollBar.Max - HScrollBar.ViewportSize) / 2;
end;
end;
procedure TScrollBox.ScrollTo(const Dx, Dy: Single);
begin
if (VScrollBar <> nil) and (VScrollBar.Visible) then
VScrollBar.Value := VScrollBar.Value - Dy;
if (HScrollBar <> nil) and (HScrollBar.Visible) then
HScrollBar.Value := HScrollBar.Value - Dx;
end;
procedure TScrollBox.InViewRect(const Rect: TRectF);
begin
end;
procedure TScrollBox.SetShowScrollBars(const Value: Boolean);
begin
if FShowScrollBars <> Value then
begin
FShowScrollBars := Value;
Realign;
end;
end;
procedure TScrollBox.SetShowSizeGrip(const Value: Boolean);
begin
if FShowSizeGrip <> Value then
begin
FShowSizeGrip := Value;
ApplyStyle;
end;
end;
procedure TScrollBox.DefineProperties(Filer: TFiler);
begin
inherited;
// Filer.DefineProperty('ScrollDesign', ReadScrollDesign, WriteScrollDesign, (FScrollDesign.X <> 0) and (FScrollDesign.Y <> 0));
end;
procedure TScrollBox.ReadScrollDesign(Reader: TReader);
begin
FScrollDesign := StringToPoint(Reader.ReadString);;
end;
procedure TScrollBox.WriteScrollDesign(Writer: TWriter);
begin
Writer.WriteString(PointToString(FScrollDesign));
end;
procedure TScrollBox.SetUseSmallScrollBars(const Value: Boolean);
begin
if FUseSmallScrollBars <> Value then
begin
FUseSmallScrollBars := Value;
ApplyStyle;
end;
end;
procedure TScrollBox.Sort(Compare: TFmxObjectSortCompare);
begin
FContent.Sort(Compare);
end;
function TScrollBox.ClientHeight: Single;
begin
if ContentLayout <> nil then
Result := ContentLayout.Height
else
Result := Height;
end;
function TScrollBox.ClientWidth: Single;
begin
if ContentLayout <> nil then
Result := ContentLayout.Width
else
Result := Width;
end;
procedure TScrollBox.ContentAddObject(AObject: TFmxObject);
begin
end;
procedure TScrollBox.ContentRemoveObject(AObject: TFmxObject);
begin
end;
procedure TScrollBox.ContentBeforeRemoveObject(AObject: TFmxObject);
begin
end;
{ TGridLayout }
procedure TGridLayout.AddObject(AObject: TFmxObject);
begin
inherited;
Realign;
end;
constructor TGridLayout.Create(AOwner: TComponent);
begin
inherited;
FItemHeight := 64;
FItemWidth := 64;
end;
procedure TGridLayout.Realign;
var
i: Integer;
CurPos: TPointF;
begin
if FDisableAlign then
Exit;
FDisableAlign := True;
{ content }
CurPos := PointF(Margins.Left, Margins.Top);
for i := 0 to ChildrenCount - 1 do
if (Children[i] is TControl) then
with TControl(Children[i]) do
begin
if (csDesigning in Self.ComponentState) and not (csDesigning in TControl(Self.Children[i]).ComponentState) then Continue;
SetBounds(CurPos.X + Padding.Left, CurPos.Y + Padding.Top,
FItemWidth - Padding.Left - Padding.right, FItemHeight - Padding.Top -
Padding.bottom);
if Orientation = TOrientation.orHorizontal then
begin
CurPos.X := CurPos.X + FItemWidth;
if CurPos.X + FItemWidth > Self.Width - Self.Margins.Left -
Self.Margins.right then
begin
CurPos.X := Self.Margins.Left;
CurPos.Y := CurPos.Y + FItemHeight;
end;
end
else
begin
CurPos.Y := CurPos.Y + FItemHeight;
if CurPos.Y + FItemHeight > Self.Height - Self.Margins.Top -
Self.Margins.bottom then
begin
CurPos.Y := Self.Margins.Top;
CurPos.X := CurPos.X + FItemWidth;
end;
end;
end;
FDisableAlign := False;
end;
procedure TGridLayout.SetItemHeight(const Value: Single);
begin
if FItemHeight <> Value then
begin
FItemHeight := Value;
Realign;
end;
end;
procedure TGridLayout.SetItemWidth(const Value: Single);
begin
if FItemWidth <> Value then
begin
FItemWidth := Value;
Realign;
end;
end;
procedure TGridLayout.SetOrientation(const Value: TOrientation);
begin
if FOrientation <> Value then
begin
FOrientation := Value;
Realign;
end;
end;
{ TScaledLayout }
constructor TScaledLayout.Create(AOwner: TComponent);
begin
inherited;
FOriginalWidth := Width;
FOriginalHeight := Height;
end;
destructor TScaledLayout.Destroy;
begin
inherited;
end;
procedure TScaledLayout.Realign;
begin
if (Parent <> nil) and (Parent is TScrollBox) and
(TScrollBox(Parent).FUpdating > 0) then
Exit;
inherited;
if not((csDesigning in ComponentState)) then
begin
RecalcAbsolute;
FRecalcUpdateRect := True;
end;
end;
function TScaledLayout.GetChildrenMatrix: TMatrix;
begin
if ((csDesigning in ComponentState)) then
begin
OriginalHeight := Height;
OriginalWidth := Width;
end;
Result := IdentityMatrix;
Result.m11 := Width / FOriginalWidth;
Result.m22 := Height / FOriginalHeight;
end;
procedure TScaledLayout.Paint;
var
R: TRectF;
begin
if (csDesigning in ComponentState) and not Locked and not FInPaintTo then
begin
R := LocalRect;
InflateRect(R, -0.5, -0.5);
Canvas.StrokeThickness := 1;
Canvas.StrokeDash := TStrokeDash.sdDash;
Canvas.Stroke.Kind := TBrushKind.bkSolid;
Canvas.Stroke.Color := $A0909090;
Canvas.DrawRect(R, 0, 0, AllCorners, AbsoluteOpacity);
Canvas.StrokeDash := TStrokeDash.sdSolid;
end;
inherited;
end;
procedure TScaledLayout.SetOriginalHeight(const Value: Single);
begin
if FOriginalHeight <> Value then
begin
FOriginalHeight := Value;
if FOriginalHeight < 1 then
FOriginalHeight := 1;
RecalcAbsolute;
end;
end;
procedure TScaledLayout.SetOriginalWidth(const Value: Single);
begin
if FOriginalWidth <> Value then
begin
FOriginalWidth := Value;
if FOriginalWidth < 1 then
FOriginalWidth := 1;
RecalcAbsolute;
end;
end;
procedure TScaledLayout.SetHeight(const Value: Single);
begin
inherited;
if (csDesigning in ComponentState) then
OriginalHeight := Height
else
RecalcAbsolute;
end;
procedure TScaledLayout.SetWidth(const Value: Single);
begin
inherited;
if (csDesigning in ComponentState) then
OriginalWidth := Width
else
RecalcAbsolute;
end;
{ TVertScrollBox }
constructor TVertScrollBox.Create(AOwner: TComponent);
begin
inherited;
FStyleLookup := 'scrollboxstyle';
end;
function TVertScrollBox.GetContentBounds: TRectF;
var
i: Integer;
begin
if (FContent <> nil) and (ContentLayout <> nil) then
begin
FContent.Width := ContentLayout.Width;
end;
Result := inherited GetContentBounds;
end;
{ TFramedVertScrollBox }
constructor TFramedVertScrollBox.Create(AOwner: TComponent);
begin
inherited;
FStyleLookup := 'framedscrollboxstyle';
end;
initialization
RegisterFmxClasses([TLayout, TScaledLayout, TGridLayout, TScrollBox, TVertScrollBox,
TFramedScrollBox, TFramedVertScrollBox]);
end.
|
unit uColorDialog;
interface
uses
{$IF CompilerVersion > 22}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls,
{$IFEND}
CNClrLib.Control.EnumTypes, CNClrLib.Control.EventArgs, CNClrLib.Control.Base,
CNClrLib.Component.ColorDialog;
type
TfrmColorDialog = class(TForm)
btnShowColorDialog: TButton;
CnColorDialog1: TCnColorDialog;
chkAllowFullOpen: TCheckBox;
chkAnyColor: TCheckBox;
chkSolidColorOnly: TCheckBox;
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
LabelBackColor: TLabel;
MemoBackColor: TMemo;
PanelBackColor: TPanel;
LabelForeColor: TLabel;
MemoForeColor: TMemo;
PanelForeColor: TPanel;
EditBackColor: TEdit;
EditForeColor: TEdit;
procedure btnShowColorDialogClick(Sender: TObject);
procedure chkAnyColorClick(Sender: TObject);
procedure chkSolidColorOnlyClick(Sender: TObject);
procedure chkAllowFullOpenClick(Sender: TObject);
private
procedure SetControlsBackColor;
procedure SetControlsForeColor;
public
{ Public declarations }
end;
var
frmColorDialog: TfrmColorDialog;
implementation
{$R *.dfm}
procedure TfrmColorDialog.btnShowColorDialogClick(Sender: TObject);
begin
if CnColorDialog1.ShowDialog = TDialogResult.drOK then
begin
SetControlsBackColor;
SetControlsForeColor;
end;
end;
procedure TfrmColorDialog.chkAllowFullOpenClick(Sender: TObject);
begin
CnColorDialog1.AllowFullOpen := chkAllowFullOpen.Checked;
end;
procedure TfrmColorDialog.chkAnyColorClick(Sender: TObject);
begin
CnColorDialog1.AnyColor := chkAnyColor.Checked;
end;
procedure TfrmColorDialog.chkSolidColorOnlyClick(Sender: TObject);
begin
CnColorDialog1.SolidColorOnly := chkSolidColorOnly.Checked;
end;
procedure TfrmColorDialog.SetControlsBackColor;
var
backColor: TColor;
begin
backColor := CnColorDialog1.Color.ToWin32Color;
LabelBackColor.Color := backColor;
EditBackColor.Color := backColor;
MemoBackColor.Color := backColor;
PanelBackColor.Color := backColor;
end;
procedure TfrmColorDialog.SetControlsForeColor;
var
foreColor: TColor;
begin
foreColor := CnColorDialog1.Color.ToWin32Color;
LabelForeColor.Font.Color := foreColor;
EditForeColor.Font.Color := foreColor;
MemoForeColor.Font.Color := foreColor;
PanelForeColor.Font.Color := foreColor;
end;
end.
|
unit dxSkinsdxExplorerBarView;
interface
uses
Types, Windows, Graphics, Classes, ImgList,
dxNavBar, dxNavBarBase, dxNavBarCollns, dxNavBarStyles, dxNavBarExplorerViews,
dxNavBarGraphics, dxNavBarOffice11Views, dxNavBarOfficeViews,
cxLookAndFeels, cxLookAndFeelPainters,cxGraphics, cxClasses, dxSkinInfo,
dxNavBarSkinBasedViews, dxSkinsCore, dxSkinsLookAndFeelPainter,
dxNavBarCustomPainters, dxOffice11;
const
dxNavBarSkinExplorerBarView = 20;
type
TdxNavBarSkinVista2PainterHelper = class(TdxNavBarSkinBasedPainterHelper)
private
FLookAndFeel: TcxLookAndFeel;
protected
function GetSkinsCount: Integer; override;
function GetSkinNames(AIndex: Integer): TdxSkinName; override;
function GetSkinInfoClass: TdxSkinInfoClass; override;
function GetSkinName: TdxSkinName; override;
function GetSkinPainterData(var AData: TdxSkinInfo): Boolean; override;
procedure LookAndFeelChanged(Sender: TcxLookAndFeel; AChangedValues: TcxLookAndFeelValues);
procedure SetSkinName(AValue: TdxSkinName); override;
public
constructor Create(ASkinName: TdxSkinName); override;
destructor Destroy; override;
function NavPaneDoesGroupCaptionButtonRequireOffset: Boolean; override;
function NavPanePopupControl: TdxSkinElement; override;
function NavBarDragDropItemTarget: TdxSkinElement; override;
function NavBarSeparator: TdxSkinElement; override;
end;
{ TdxNavBarSkinVista2ExplorerBarViewInfo }
TdxNavBarSkinVista2ExplorerBarViewInfo = class(TdxNavBarExplorerBarViewInfo)
protected
function GetHelper: TdxNavBarSkinVista2PainterHelper;
function GetGroupCaptionSignSize: TSize; override;
function CanSelectLinkByRect: Boolean; override;
function GetAbsoluteLinksImageEdges: TRect; override;
function GetGroupBorderOffsets: TRect; override;
class function GetGroupCaptionImageIndent: Integer; override;
function GetGroupCaptionHeightAddon: Integer; override;
function GetGroupEdges: TPoint; override;
function GetGroupSeparatorWidth: Integer; override;
// Link
class function GetLinksSmallSeparatorWidth: Integer; override;
public
procedure AssignDefaultItemHotTrackedStyle; override;
procedure AssignDefaultItemPressedStyle; override;
end;
{ TdxNavBarSkinVista2ExplorerBarPainter }
TdxNavBarSkinVista2ExplorerBarPainter = class(TdxNavBarSkinBasedExplorerBarPainter)
private
function GetLookAndFeel: TcxLookAndFeel;
function GetSkinName: TdxSkinName;
function GetSkinNameAssigned: Boolean;
function IsSkinNameStored: Boolean;
procedure SetLookAndFeel(AValue: TcxLookAndFeel);
procedure SetSkinName(const AValue: TdxSkinName);
procedure SetSkinNameAssigned(AValue: Boolean);
protected
class function GetGroupViewInfoClass: TdxNavBarGroupViewInfoClass; override;
class function GetLinkViewInfoClass: TdxNavBarLinkViewInfoClass; override;
class function GetViewInfoClass: TdxNavBarViewInfoClass; override;
class function GetSkinPainterHelperClass: TdxNavBarSkinBasedPainterHelperClass; override;
class function SignPainterClass: TdxNavBarCustomSignPainterClass; override;
class function SelectionPainterClass: TdxNavBarCustomSelectionPainterClass; override;
procedure DrawGroupTopBorder(AGroupViewInfo: TdxNavBarGroupViewInfo);
function GetMasterLookAndFeel: TcxLookAndFeel; override;
public
procedure Assign(Source: TPersistent); override;
procedure DrawItemSelection(ALinkViewInfo: TdxNavBarLinkViewInfo); override;
procedure DrawBackground; override;
procedure DrawGroupBackground(AGroupViewInfo: TdxNavBarGroupViewInfo); override;
procedure DrawGroupBorder(AGroupViewInfo: TdxNavBarGroupViewInfo); override;
procedure DrawGroupControl(ACanvas: TCanvas; ARect: TRect;
AGroupViewInfo: TdxNavBarGroupViewInfo); override;
procedure DrawGroupControlSplitter(AGroupViewInfo: TdxNavBarExplorerBarGroupViewInfo); override;
procedure DrawSeparator(ALinkViewInfo: TdxNavBarLinkViewInfo); override;
property LookAndFeel: TcxLookAndFeel read GetLookAndFeel write SetLookAndFeel;
published
property SkinName: TdxSkinName read GetSkinName write SetSkinName stored IsSkinNameStored;
property SkinNameAssigned: Boolean read GetSkinNameAssigned write SetSkinNameAssigned default False;
end;
TdxNavBarSkinVista2ExplorerBarSelectionPainter = class(TdxNavBarCustomSelectionPainter)
protected
class procedure GetColors(AState: TdxNavBarObjectStates; ABackColor: TColor; out AFillColor,
ATopLeftOuterColor, ABottomRightOuterColor, ATopLeftInnerColor, ABottomRightInnerColor: TColor); override;
end;
{ TdxNavBarSkinPopupControlViewInfo }
TdxNavBarSkinPopupControlViewInfo = class(TdxNavBarSkinBasedPopupControlViewInfo)
protected
function GetBorderOffsets: TRect; override;
end;
TdxNavBarSkinVista2ExplorerBarLinkViewInfo = class(TdxNavBarSkinBasedExplorerBarLinkViewInfo)
public
function Font: TFont; override;
function FontColor: TColor; override;
end;
TdxNavBarSkinVista2ExplorerBarGroupViewInfo = class(TdxNavBarExplorerBarGroupViewInfo)
protected
function GetSplitterSize: Integer; override;
public
function CaptionBackColor: TColor; override;
function CaptionBackColor2: TColor; override;
function CaptionFont: TFont; override;
function CaptionFontColor: TColor; override;
end;
implementation
uses
dxNavBarViewsFact, Math, cxGeometry, dxUxTheme;
type
TdxCustomNavBarAccess = class(TdxCustomNavBar);
procedure DrawElementPart(AElement: TdxSkinElement; ACanvas: TcxCanvas; ADrawRect, AClipRect: TRect);
begin
if AElement = nil then Exit;
ACanvas.SaveClipRegion;
try
ACanvas.SetClipRegion(TcxRegion.Create(AClipRect), roIntersect);
AElement.Draw(ACanvas.Handle, ADrawRect);
finally
ACanvas.RestoreClipRegion;
end;
end;
{ TdxNavBarSkinVista2PainterHelper }
constructor TdxNavBarSkinVista2PainterHelper.Create(ASkinName: TdxSkinName);
begin
inherited Create(ASkinName);
FLookAndFeel := TcxLookAndFeel.Create(nil);
FLookAndFeel.NativeStyle := False;
FLookAndFeel.OnChanged := LookAndFeelChanged;
end;
destructor TdxNavBarSkinVista2PainterHelper.Destroy;
begin
FLookAndFeel.Free;
inherited;
end;
function TdxNavBarSkinVista2PainterHelper.NavBarDragDropItemTarget: TdxSkinElement;
begin
Result := nil;
end;
function TdxNavBarSkinVista2PainterHelper.NavBarSeparator: TdxSkinElement;
begin
Result := nil;
end;
function TdxNavBarSkinVista2PainterHelper.NavPaneDoesGroupCaptionButtonRequireOffset: Boolean;
var
ABoolProperty: TdxSkinBooleanProperty;
ASkinInfo: TdxSkinInfo;
begin
if GetSkinPainterData(ASkinInfo) then
ABoolProperty := ASkinInfo.NavPaneOffsetGroupBorders
else
ABoolProperty := nil;
if ABoolProperty = nil then
Result := inherited NavPaneDoesGroupCaptionButtonRequireOffset
else
Result := ABoolProperty.Value;
end;
function TdxNavBarSkinVista2PainterHelper.NavPanePopupControl: TdxSkinElement;
var
ASkinInfo: TdxSkinInfo;
begin
Result := nil;
if GetSkinPainterData(ASkinInfo) then
Result := ASkinInfo.NavPaneFormBorder;
end;
function TdxNavBarSkinVista2PainterHelper.GetSkinsCount: Integer;
begin
Result := GetExtendedStylePainters.Count;
end;
function TdxNavBarSkinVista2PainterHelper.GetSkinNames(AIndex: Integer): TdxSkinName;
begin
Result := GetExtendedStylePainters.Names[AIndex];
end;
function TdxNavBarSkinVista2PainterHelper.GetSkinInfoClass: TdxSkinInfoClass;
begin
Result := TdxSkinInfo;
end;
function TdxNavBarSkinVista2PainterHelper.GetSkinName: TdxSkinName;
begin
Result := FLookAndFeel.SkinName;
end;
function TdxNavBarSkinVista2PainterHelper.GetSkinPainterData(var AData: TdxSkinInfo): Boolean;
begin
Result := GetExtendedStylePainters.GetPainterData(FLookAndFeel.SkinPainter, AData);
end;
procedure TdxNavBarSkinVista2PainterHelper.LookAndFeelChanged(Sender: TcxLookAndFeel; AChangedValues: TcxLookAndFeelValues);
begin
DoChanged;
end;
procedure TdxNavBarSkinVista2PainterHelper.SetSkinName(AValue: TdxSkinName);
begin
FLookAndFeel.SkinName := AValue;
end;
{ TdxNavBarSkinPopupControlViewInfo }
function TdxNavBarSkinPopupControlViewInfo.GetBorderOffsets: TRect;
var
AElement: TdxSkinElement;
begin
AElement := GetSkinHelper.NavPanePopupControl;
if AElement <> nil then
if not AElement.Image.Empty then
Result := AElement.Image.Margins.Rect
else
with AElement.Borders do
Result := cxRect(Left.Thin, Top.Thin, Right.Thin, Bottom.Thin)
else
Result := inherited GetBorderOffsets;
end;
{ TdxNavBarSkinVista2ExplorerBarViewInfo }
function TdxNavBarSkinVista2ExplorerBarViewInfo.GetHelper: TdxNavBarSkinVista2PainterHelper;
begin
Result := TdxNavBarSkinVista2PainterHelper(TdxNavBarSkinVista2ExplorerBarPainter(Painter).FSkinBasedPainterHelper);
end;
class function TdxNavBarSkinVista2ExplorerBarViewInfo.GetLinksSmallSeparatorWidth: Integer;
begin
Result := 15;
end;
procedure TdxNavBarSkinVista2ExplorerBarViewInfo.AssignDefaultItemHotTrackedStyle;
begin
inherited AssignDefaultItemHotTrackedStyle;
NavBar.DefaultStyles.ItemHotTracked.Font.Style := NavBar.DefaultStyles.ItemHotTracked.Font.Style - [fsUnderline];
end;
procedure TdxNavBarSkinVista2ExplorerBarViewInfo.AssignDefaultItemPressedStyle;
begin
inherited;
NavBar.DefaultStyles.ItemPressed.Font.Style := NavBar.DefaultStyles.ItemPressed.Font.Style - [fsUnderline];
end;
function TdxNavBarSkinVista2ExplorerBarViewInfo.CanSelectLinkByRect: Boolean;
begin
Result := True;
end;
function TdxNavBarSkinVista2ExplorerBarViewInfo.GetAbsoluteLinksImageEdges: TRect;
begin
Result := cxRect(7, 4, 9, 4);
end;
function TdxNavBarSkinVista2ExplorerBarViewInfo.GetGroupBorderOffsets: TRect;
begin
if TdxNavBarSkinVista2ExplorerBarPainter(Painter).IsSkinAvailable then
Result := GetSkinElementOffsets(GetHelper.NavBarGroupClient)
else
Result := inherited GetGroupBorderOffsets;
end;
function TdxNavBarSkinVista2ExplorerBarViewInfo.GetGroupCaptionHeightAddon: Integer;
begin
Result := 15;
end;
class function TdxNavBarSkinVista2ExplorerBarViewInfo.GetGroupCaptionImageIndent: Integer;
begin
Result := 2;
end;
function TdxNavBarSkinVista2ExplorerBarViewInfo.GetGroupCaptionSignSize: TSize;
var
AElement: TdxSkinElement;
begin
AElement := GetHelper.NavBarGroupSigns(True);
if AElement <> nil then
Result := AElement.Size
else
Result := inherited GetGroupCaptionSignSize;
end;
function TdxNavBarSkinVista2ExplorerBarViewInfo.GetGroupEdges: TPoint;
begin
if not IsThemeActive then
Result := cxNullPoint
else
Result := cxPoint(1, 1);
end;
function TdxNavBarSkinVista2ExplorerBarViewInfo.GetGroupSeparatorWidth: Integer;
begin
Result := -1;
end;
{ TdxNavBarSkinVista2ExplorerBarPainter }
procedure TdxNavBarSkinVista2ExplorerBarPainter.Assign(Source: TPersistent);
begin
if Source is TdxNavBarSkinVista2ExplorerBarPainter then
LookAndFeel := TdxNavBarSkinVista2ExplorerBarPainter(Source).LookAndFeel
else
inherited;
end;
procedure TdxNavBarSkinVista2ExplorerBarPainter.DrawBackground;
begin
if not DrawSkinElement(FSkinBasedPainterHelper.NavBarBackground, Canvas, NavBar.ClientRect) then
inherited;
end;
procedure TdxNavBarSkinVista2ExplorerBarPainter.DrawGroupBackground(AGroupViewInfo: TdxNavBarGroupViewInfo);
begin
if not IsSkinAvailable then
inherited;
end;
procedure TdxNavBarSkinVista2ExplorerBarPainter.DrawGroupBorder(
AGroupViewInfo: TdxNavBarGroupViewInfo);
begin
inherited DrawGroupBorder(AGroupViewInfo);
if not AGroupViewInfo.IsCaptionVisible then
DrawGroupTopBorder(AGroupViewInfo);
end;
procedure TdxNavBarSkinVista2ExplorerBarPainter.DrawGroupTopBorder(
AGroupViewInfo: TdxNavBarGroupViewInfo);
var
AElement: TdxSkinElement;
R: TRect;
begin
AElement := FSkinBasedPainterHelper.NavBarGroupButtonCaption;
if AElement <> nil then
begin
cxCanvas.SaveClipRegion;
try
R := AGroupViewInfo.ItemsRect;
cxCanvas.SetClipRegion(TcxRegion.Create(cxRectSetHeight(R, 1)), roSet);
R.Bottom := R.Top + 1;
Dec(R.Top, AElement.Size.cy);
AElement.Draw(cxCanvas.Handle, R);
finally
cxCanvas.RestoreClipRegion;
end;
end;
end;
procedure TdxNavBarSkinVista2ExplorerBarPainter.DrawItemSelection(
ALinkViewInfo: TdxNavBarLinkViewInfo);
var
AState: TdxSkinElementState;
begin
AState := NavBarObjectStateToSkinState(ALinkViewInfo.State);
if not DrawSkinElement(FSkinBasedPainterHelper.NavPaneItem((AState = esNormal) and (sSelected in ALinkViewInfo.State)),
Canvas, ALinkViewInfo.SelectionRect, 0, AState) then
inherited;
end;
procedure TdxNavBarSkinVista2ExplorerBarPainter.DrawGroupControl(ACanvas: TCanvas;
ARect: TRect; AGroupViewInfo: TdxNavBarGroupViewInfo);
begin
if not DrawSkinElement(FSkinBasedPainterHelper.NavBarGroupClient, ACanvas, ARect, 0, esNormal, True) then
inherited;
end;
procedure TdxNavBarSkinVista2ExplorerBarPainter.DrawGroupControlSplitter(AGroupViewInfo: TdxNavBarExplorerBarGroupViewInfo);
var
ARect: TRect;
begin
ARect := cxRectSetBottom(AGroupViewInfo.SplitterRect, AGroupViewInfo.SplitterRect.Top + 1, 1);
FillRectByColor(Canvas.Handle, ARect, clBtnHighlight);
ARect := cxRectSetBottom(ARect, ARect.Bottom + 2, 2);
FillRectByColor(Canvas.Handle, ARect, clBtnFace);
ARect := cxRectSetBottom(ARect, ARect.Bottom + 1, 1);
FillRectByColor(Canvas.Handle, ARect, clBtnHighlight);
end;
procedure TdxNavBarSkinVista2ExplorerBarPainter.DrawSeparator(ALinkViewInfo: TdxNavBarLinkViewInfo);
var
AClipRect, ADrawRect: TRect;
begin
if (FSkinBasedPainterHelper.NavPaneHeader <> nil) and
(FSkinBasedPainterHelper.NavPaneCaptionHeight <> nil) then
begin
AClipRect := ALinkViewInfo.SeparatorRect;
ADrawRect := cxRectSetBottom(AClipRect, AClipRect.Bottom, FSkinBasedPainterHelper.NavPaneCaptionHeight.Value);
DrawElementPart(FSkinBasedPainterHelper.NavPaneHeader, cxCanvas, ADrawRect, AClipRect);
end
else
inherited;
end;
class function TdxNavBarSkinVista2ExplorerBarPainter.GetViewInfoClass: TdxNavBarViewInfoClass;
begin
Result := TdxNavBarSkinVista2ExplorerBarViewInfo;
end;
class function TdxNavBarSkinVista2ExplorerBarPainter.GetSkinPainterHelperClass: TdxNavBarSkinBasedPainterHelperClass;
begin
Result := TdxNavBarSkinVista2PainterHelper;
end;
class function TdxNavBarSkinVista2ExplorerBarPainter.SignPainterClass: TdxNavBarCustomSignPainterClass;
begin
Result := TdxNavBarExplorerBarSignPainter;
end;
function TdxNavBarSkinVista2ExplorerBarPainter.GetMasterLookAndFeel: TcxLookAndFeel;
begin
Result := LookAndFeel;
end;
function TdxNavBarSkinVista2ExplorerBarPainter.IsSkinNameStored: Boolean;
begin
Result := SkinNameAssigned;
end;
class function TdxNavBarSkinVista2ExplorerBarPainter.SelectionPainterClass: TdxNavBarCustomSelectionPainterClass;
begin
Result := TdxNavBarSkinVista2ExplorerBarSelectionPainter;
end;
procedure TdxNavBarSkinVista2ExplorerBarPainter.SetLookAndFeel(AValue: TcxLookAndFeel);
begin
LookAndFeel.Assign(AValue);
end;
procedure TdxNavBarSkinVista2ExplorerBarPainter.SetSkinName(const AValue: TdxSkinName);
begin
ColorSchemeName := AValue;
end;
class function TdxNavBarSkinVista2ExplorerBarPainter.GetGroupViewInfoClass: TdxNavBarGroupViewInfoClass;
begin
Result := TdxNavBarSkinVista2ExplorerBarGroupViewInfo;
end;
class function TdxNavBarSkinVista2ExplorerBarPainter.GetLinkViewInfoClass: TdxNavBarLinkViewInfoClass;
begin
Result := TdxNavBarSkinVista2ExplorerBarLinkViewInfo;
end;
function TdxNavBarSkinVista2ExplorerBarPainter.GetLookAndFeel: TcxLookAndFeel;
begin
Result := TdxNavBarSkinVista2PainterHelper(FSkinBasedPainterHelper).FLookAndFeel;
end;
function TdxNavBarSkinVista2ExplorerBarPainter.GetSkinName: TdxSkinName;
begin
Result := ColorSchemeName;
end;
function TdxNavBarSkinVista2ExplorerBarPainter.GetSkinNameAssigned: Boolean;
begin
Result := lfvSkinName in LookAndFeel.AssignedValues;
end;
procedure TdxNavBarSkinVista2ExplorerBarPainter.SetSkinNameAssigned(AValue: Boolean);
begin
if AValue then
LookAndFeel.AssignedValues := LookAndFeel.AssignedValues + [lfvSkinName]
else
LookAndFeel.AssignedValues := LookAndFeel.AssignedValues - [lfvSkinName];
end;
{ TdxNavBarSkinVista2ExplorerBarSelectionPainter }
class procedure TdxNavBarSkinVista2ExplorerBarSelectionPainter.GetColors(
AState: TdxNavBarObjectStates; ABackColor: TColor; out AFillColor,
ATopLeftOuterColor, ABottomRightOuterColor, ATopLeftInnerColor,
ABottomRightInnerColor: TColor);
begin
inherited;
AFillColor := clActiveCaption;
end;
{ TdxNavBarSkinVista2ExplorerBarLinkViewInfo }
function TdxNavBarSkinVista2ExplorerBarLinkViewInfo.Font: TFont;
begin
Result := inherited Font;
Result.Name := 'Segoe UI';
end;
function TdxNavBarSkinVista2ExplorerBarLinkViewInfo.FontColor: TColor;
const
ATextColor: array [Boolean] of TColor = (clWindowText, clHighlightText);
begin
if not IsThemeActive then
Result := ATextColor[[sSelected, sPressed, sHotTracked] * State <> []]
else
Result := inherited FontColor;
end;
{ TdxNavBarSkinVista2ExplorerBarGroupViewInfo }
function TdxNavBarSkinVista2ExplorerBarGroupViewInfo.CaptionBackColor: TColor;
begin
if [sSelected, sPressed, sHotTracked] * State <> [] then
if sPressed in State then
Result := clHotLight
else
Result := clActiveCaption
else
Result := clWindow;
end;
function TdxNavBarSkinVista2ExplorerBarGroupViewInfo.CaptionBackColor2: TColor;
begin
Result := CaptionBackColor;
end;
function TdxNavBarSkinVista2ExplorerBarGroupViewInfo.CaptionFont: TFont;
begin
Result := inherited CaptionFont;
Result.Style := Result.Style - [fsBold];
Result.Name := 'Segoe UI';
end;
function TdxNavBarSkinVista2ExplorerBarGroupViewInfo.CaptionFontColor: TColor;
const
ATextColor: array [Boolean] of TColor = (clWindowText, clHighlightText);
var
AElement: TdxSkinElement;
begin
if not IsThemeActive then
Result := ATextColor[[sSelected, sPressed, sHotTracked] * State <> []]
else
with TdxNavBarSkinVista2ExplorerBarPainter(Painter) do
begin
AElement := FSkinBasedPainterHelper.NavBarGroupButtonCaption;
if AElement <> nil then
Result := AElement.TextColor
else
Result := inherited CaptionFontColor;
end;
end;
function TdxNavBarSkinVista2ExplorerBarGroupViewInfo.GetSplitterSize: Integer;
begin
Result := 4;
end;
initialization
dxNavBarViewsFactory.RegisterView(dxNavBarSkinExplorerBarView,
'SkinVista2ExplorerBarView', TdxNavBarSkinVista2ExplorerBarPainter);
RegisterClasses([TdxNavBarSkinVista2ExplorerBarPainter]);
finalization
dxNavBarViewsFactory.UnRegisterView(dxNavBarSkinExplorerBarView);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Runtime Library }
{ }
{ Copyright (C) 1999 Inprise Corporation }
{ }
{*******************************************************}
unit ComCorba;
interface
uses SysUtils, ORBPAS, ComObj, CorbaObj;
type
TCorbaComObjectFactory = class(TCorbaFactory)
private
FImplementationClass: TComClass;
protected
function CreateInterface(const InstanceName: string): IObject; override;
public
constructor Create(const InterfaceName, InstanceName, RepositoryId: string;
const ImplGUID: TGUID; ImplementationClass: TComClass;
Instancing: TCorbaInstancing = iMultiInstance;
ThreadModel: TCorbaThreadModel = tmSingleThread);
property ImplementationClass: TComClass read FImplementationClass;
end;
implementation
uses ActiveX;
{ TCorbaComOjectFactory }
constructor TCorbaComObjectFactory.Create(const InterfaceName, InstanceName,
RepositoryId: string; const ImplGUID: TGUID;
ImplementationClass: TComClass;
Instancing: TCorbaInstancing; ThreadModel: TCorbaThreadModel);
begin
inherited Create(InterfaceName, InstanceName, RepositoryID, ImplGUID,
Instancing, ThreadModel);
FImplementationClass := ImplementationClass;
end;
function TCorbaComObjectFactory.CreateInterface(const InstanceName: string): IObject;
begin
Result := FImplementationClass.Create;
end;
initialization
CoInitialize(nil);
end.
|
unit Initializer.PartitionAlign;
interface
uses
SysUtils, Windows, Classes, Graphics,
Global.LanguageString, Device.PhysicalDrive,
Getter.PhysicalDrive.PartitionList;
type
TMainformPartitionAlignApplier = class
private
PartitionList: TPartitionList;
procedure AppendThisEntryAsInvalid(CurrentEntry: TPartitionEntry);
procedure AppendThisEntryAsValid(CurrentEntry: TPartitionEntry);
function ApplyAndGetPartitionAlignStatus: Boolean;
procedure FreePartitionList;
function IsThisStartingOffsetInvalid(
StartingOffset: TLargeInteger): Boolean;
procedure SetPartitionList;
function AppendThisEntryToAlignLabel(
CurrentEntry: TPartitionEntry): Boolean;
public
function ApplyAlignAndGetMisalignedExists: Boolean;
end;
implementation
uses Form.Main;
procedure TMainformPartitionAlignApplier.SetPartitionList;
begin
PartitionList := fMain.SelectedDrive.GetPartitionList;
end;
procedure TMainformPartitionAlignApplier.FreePartitionList;
begin
FreeAndNil(PartitionList);
end;
function TMainformPartitionAlignApplier.IsThisStartingOffsetInvalid(
StartingOffset: TLargeInteger): Boolean;
const
ValidAlignUnit = 4096;
begin
result := (StartingOffset / ValidAlignUnit) <>
(StartingOffset div ValidAlignUnit);
end;
procedure TMainformPartitionAlignApplier.AppendThisEntryAsInvalid(
CurrentEntry: TPartitionEntry);
const
DisplayUnit = 1024;
begin
fMain.lPartitionAlign.Font.Color := clRed;
fMain.lPartitionAlign.Caption := fMain.lPartitionAlign.Caption +
CurrentEntry.Letter + ' (' +
IntToStr(CurrentEntry.StartingOffset div DisplayUnit) +
CapBad[CurrLang];
end;
procedure TMainformPartitionAlignApplier.AppendThisEntryAsValid(
CurrentEntry: TPartitionEntry);
begin
fMain.lPartitionAlign.Caption := fMain.lPartitionAlign.Caption +
CurrentEntry.Letter + CapGood[CurrLang];
end;
function TMainformPartitionAlignApplier.AppendThisEntryToAlignLabel(
CurrentEntry: TPartitionEntry): Boolean;
begin
result := IsThisStartingOffsetInvalid(CurrentEntry.StartingOffset);
if result then
AppendThisEntryAsInvalid(CurrentEntry)
else
AppendThisEntryAsValid(CurrentEntry);
end;
function TMainformPartitionAlignApplier.ApplyAndGetPartitionAlignStatus:
Boolean;
var
CurrentEntry: TPartitionEntry;
begin
fMain.lPartitionAlign.Caption := CapAlign[CurrLang];
result := false;
for CurrentEntry in PartitionList do
result := result or AppendThisEntryToAlignLabel(CurrentEntry);
end;
function TMainformPartitionAlignApplier.ApplyAlignAndGetMisalignedExists:
Boolean;
begin
SetPartitionList;
result := ApplyAndGetPartitionAlignStatus;
FreePartitionList;
end;
end. |
unit uImagem;
interface
uses Messages, Windows, SysUtils, Classes, Contnrs,
Controls, Forms, Menus, Graphics, StdCtrls, GraphUtil, ShellApi;
type
TImagem = class(TGraphicControl)
private
FBitmap: TBitmap;
FOnProgress: TProgressEvent;
FStretch: Boolean;
FCenter: Boolean;
FIncrementalDisplay: Boolean;
FTransparent: Boolean;
FDrawing: Boolean;
FProportional: Boolean;
function GetCanvas: TCanvas;
procedure PictureChanged(Sender: TObject);
procedure SetCenter(Value: Boolean);
procedure SetBitmap(Value: TBitmap);
procedure SetStretch(Value: Boolean);
procedure SetTransparent(Value: Boolean);
procedure SetProportional(Value: Boolean);
protected
function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; override;
function DestRect: TRect;
function DoPaletteChange: Boolean;
function getPageNum: integer;
function GetPalette: HPALETTE; override;
procedure Paint; override;
procedure Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string); dynamic;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Canvas: TCanvas read GetCanvas;
property PageNum : integer read getPageNum;
published
property Align;
property Anchors;
property AutoSize;
property Center: Boolean read FCenter write SetCenter default False;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property IncrementalDisplay: Boolean read FIncrementalDisplay write FIncrementalDisplay default False;
property ParentShowHint;
property Bitmap: TBitmap read FBitmap write SetBitmap;
property PopupMenu;
property Proportional: Boolean read FProportional write SetProportional default false;
property ShowHint;
property Stretch: Boolean read FStretch write SetStretch default False;
property Transparent: Boolean read FTransparent write SetTransparent default False;
property Visible;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnMouseActivate;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnProgress: TProgressEvent read FOnProgress write FOnProgress;
property OnStartDock;
property OnStartDrag;
end;
implementation
uses Consts, Dialogs, Themes, Math, UxTheme, DwmApi, uPrintManBaseClasses;
{ TImagem }
constructor TImagem.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csReplicatable, csPannable];
FBitmap := nil;
Height := 105;
Width := 105;
end;
destructor TImagem.Destroy;
begin
inherited Destroy;
end;
function TImagem.GetPalette: HPALETTE;
begin
Result := 0;
if FBitmap <> nil then
Result := FBitmap.Palette;
end;
function TImagem.DestRect: TRect;
var
w, h, cw, ch: Integer;
xyaspect: Double;
begin
w := FBitmap.Width;
h := FBitmap.Height;
cw := ClientWidth;
ch := ClientHeight;
if Stretch or (Proportional and ((w > cw) or (h > ch))) then
begin
if Proportional and (w > 0) and (h > 0) then
begin
xyaspect := w / h;
if w > h then
begin
w := cw;
h := Trunc(cw / xyaspect);
if h > ch then // woops, too big
begin
h := ch;
w := Trunc(ch * xyaspect);
end;
end
else
begin
h := ch;
w := Trunc(ch * xyaspect);
if w > cw then // woops, too big
begin
w := cw;
h := Trunc(cw / xyaspect);
end;
end;
end
else
begin
w := cw;
h := ch;
end;
end;
with Result do
begin
Left := 0;
Top := 0;
Right := w;
Bottom := h;
end;
if Center then
OffsetRect(Result, (cw - w) div 2, (ch - h) div 2);
end;
procedure TImagem.Paint;
procedure DoBufferedPaint(Canvas: TCanvas);
var
MemDC: HDC;
Rect: TRect;
PaintBuffer: HPAINTBUFFER;
begin
Rect := DestRect;
PaintBuffer := BeginBufferedPaint(Canvas.Handle, Rect, BPBF_TOPDOWNDIB, nil, MemDC);
try
Canvas.Handle := MemDC;
Canvas.StretchDraw(DestRect, FBitmap);
BufferedPaintMakeOpaque(PaintBuffer, @Rect);
finally
EndBufferedPaint(PaintBuffer, True);
end;
end;
var
Save: Boolean;
LForm: TCustomForm;
PaintOnGlass: Boolean;
begin
if csDesigning in ComponentState then
with inherited Canvas do
begin
Pen.Style := psDash;
Brush.Style := bsClear;
Rectangle(0, 0, Width, Height);
end;
Save := FDrawing;
FDrawing := True;
try
PaintOnGlass := DwmCompositionEnabled and not (csDesigning in ComponentState);
if PaintOnGlass then
begin
LForm := GetParentForm(Self);
PaintOnGlass := (LForm <> nil) and LForm.GlassFrame.FrameExtended and
LForm.GlassFrame.IntersectsControl(Self);
end;
if PaintOnGlass then
DoBufferedPaint(inherited Canvas)
else
with inherited Canvas do
StretchDraw(DestRect, FBitmap);
finally
FDrawing := Save;
end;
end;
function TImagem.DoPaletteChange: Boolean;
var
ParentForm: TCustomForm;
Tmp: TGraphic;
begin
Result := False;
Tmp := FBitmap;
if Visible and (not (csLoading in ComponentState)) and (Tmp <> nil) and
(Tmp.PaletteModified) then
begin
if (Tmp.Palette = 0) then
Tmp.PaletteModified := False
else
begin
ParentForm := GetParentForm(Self);
if Assigned(ParentForm) and ParentForm.Active and Parentform.HandleAllocated then
begin
if FDrawing then
ParentForm.Perform(wm_QueryNewPalette, 0, 0)
else
PostMessage(ParentForm.Handle, wm_QueryNewPalette, 0, 0);
Result := True;
Tmp.PaletteModified := False;
end;
end;
end;
end;
procedure TImagem.Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string);
begin
if FIncrementalDisplay and RedrawNow then
begin
if DoPaletteChange then Update
else Paint;
end;
if Assigned(FOnProgress) then FOnProgress(Sender, Stage, PercentDone, RedrawNow, R, Msg);
end;
function TImagem.GetCanvas: TCanvas;
begin
Result := nil;
if FBitmap <> nil then
Result := FBitmap.Canvas;
end;
function TImagem.getPageNum: integer;
begin
result := TImagemPanel(owner).PageNum;
end;
procedure TImagem.SetCenter(Value: Boolean);
begin
if FCenter <> Value then
begin
FCenter := Value;
PictureChanged(Self);
end;
end;
procedure TImagem.SetBitmap(Value: TBitmap);
begin
if FBitmap <> Value then
begin
FBitmap := Value;
if FBitmap<>nil then
PictureChanged(Self);
end;
end;
procedure TImagem.SetStretch(Value: Boolean);
begin
if Value <> FStretch then
begin
FStretch := Value;
PictureChanged(Self);
end;
end;
procedure TImagem.SetTransparent(Value: Boolean);
begin
if Value <> FTransparent then
begin
FTransparent := Value;
PictureChanged(Self);
end;
end;
procedure TImagem.SetProportional(Value: Boolean);
begin
if FProportional <> Value then
begin
FProportional := Value;
PictureChanged(Self);
end;
end;
procedure TImagem.PictureChanged(Sender: TObject);
var
G: TGraphic;
D : TRect;
begin
if AutoSize and (FBitmap.Width > 0) and (FBitmap.Height > 0) then
SetBounds(Left, Top, FBitmap.Width, FBitmap.Height);
G := FBitmap;
if G <> nil then
begin
G.Transparent := FTransparent;
D := DestRect;
if (not G.Transparent) and (D.Left <= 0) and (D.Top <= 0) and
(D.Right >= Width) and (D.Bottom >= Height) then
ControlStyle := ControlStyle + [csOpaque]
else // picture might not cover entire clientrect
ControlStyle := ControlStyle - [csOpaque];
if DoPaletteChange and FDrawing then Update;
end
else ControlStyle := ControlStyle - [csOpaque];
if not FDrawing then Invalidate;
end;
function TImagem.CanAutoSize(var NewWidth, NewHeight: Integer): Boolean;
begin
Result := True;
if not (csDesigning in ComponentState) or (FBitmap.Width > 0) and
(FBitmap.Height > 0) then
begin
if Align in [alNone, alLeft, alRight] then
NewWidth := FBitmap.Width;
if Align in [alNone, alTop, alBottom] then
NewHeight := FBitmap.Height;
end;
end;
end.
|
{
Serial communication port (UART). In Windows it COM-port, real or virtual.
In Linux it /dev/ttyS or /dev/ttyUSB. Also, Linux use file /var/lock/LCK..ttyS for port locking
(C) Sergey Bodrov, 2012-2018
Properties:
Port - port name (COM1, /dev/ttyS01)
BaudRate - data excange speed
MinDataBytes - minimal bytes count in buffer for triggering event OnDataAppear
Methods:
Open() - Opens port. As parameter it use port initialization string:
InitStr = 'Port,BaudRate,DataBits,Parity,StopBits,SoftFlow,HardFlow'
Port - COM port name (COM1, /dev/ttyS01)
BaudRate - connection speed (50..4000000 bits per second), default 9600
DataBits - default 8
Parity - (N - None, O - Odd, E - Even, M - Mark or S - Space) default N
StopBits - (1, 1.5, 2)
SoftFlow - Enable XON/XOFF byte ($11 for resume and $13 for pause transmission), default 1
HardFlow - Enable CTS/RTS handshake, default 0
Events:
OnOpen - Triggered after sucсessful connection.
OnClose - Triggered after disconnection.
}
unit DataPortSerial;
{$IFDEF FPC}
{$MODE DELPHI}
{$DEFINE NO_LIBC}
{$ENDIF}
interface
uses
{$IFNDEF MSWINDOWS}
{$IFNDEF NO_LIBC}
Libc,
KernelIoctl,
{$ELSE}
termio, baseunix, unix,
{$ENDIF}
{$IFNDEF FPC}
Types,
{$ENDIF}
{$ELSE}
Windows,
{$ENDIF}
SysUtils, Classes, DataPort, DataPortUART, synaser, synautil;
type
{ TSerialClient - serial port reader/writer, based on Ararat Synapse }
TSerialClient = class(TThread)
private
FSerial: TBlockSerial;
sFromPort: AnsiString;
sLastError: string;
FSafeMode: Boolean;
FOnIncomingMsgEvent: TMsgEvent;
FOnErrorEvent: TMsgEvent;
FOnConnectEvent: TNotifyEvent;
FDoConfig: Boolean;
procedure SyncProc();
procedure SyncProcOnError();
procedure SyncProcOnConnect();
protected
FParentDataPort: TDataPortUART;
function IsError(): Boolean;
procedure Execute(); override;
public
sPort: string;
BaudRate: Integer;
DataBits: Integer;
Parity: char;
StopBits: TSerialStopBits;
FlowControl: TSerialFlowControl;
CalledFromThread: Boolean;
sToSend: AnsiString;
SleepInterval: Integer;
constructor Create(AParent: TDataPortUART); reintroduce;
property SafeMode: Boolean read FSafeMode write FSafeMode;
property Serial: TBlockSerial read FSerial;
property OnIncomingMsgEvent: TMsgEvent read FOnIncomingMsgEvent
write FOnIncomingMsgEvent;
property OnErrorEvent: TMsgEvent read FOnErrorEvent write FOnErrorEvent;
property OnConnectEvent: TNotifyEvent read FOnConnectEvent write FOnConnectEvent;
{ Set port parameters (baud rate, data bits, etc..) }
procedure Config();
function SendString(const AData: AnsiString): Boolean;
procedure SendStream(st: TStream);
end;
{ TDataPortSerial - serial DataPort }
TDataPortSerial = class(TDataPortUART)
private
FSerialClient: TSerialClient;
function CloseClient(): Boolean;
protected
procedure SetBaudRate(AValue: Integer); override;
procedure SetDataBits(AValue: Integer); override;
procedure SetParity(AValue: AnsiChar); override;
procedure SetStopBits(AValue: TSerialStopBits); override;
procedure SetFlowControl(AValue: TSerialFlowControl); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
{ Open serial DataPort
InitStr = 'Port,BaudRate,DataBits,Parity,StopBits,SoftFlow,HardFlow'
Port - COM port name (COM1, /dev/tty01)
BaudRate - connection speed (50..4000000 bits per second), default 9600
DataBits - default 8
Parity - (N - None, O - Odd, E - Even, M - Mark or S - Space) default N
StopBits - (1, 1.5, 2)
SoftFlow - Enable XON/XOFF handshake, default 0
HardFlow - Enable CTS/RTS handshake, default 0 }
procedure Open(const AInitStr: string = ''); override;
procedure Close(); override;
function Push(const AData: AnsiString): Boolean; override;
class function GetSerialPortNames(): string;
{ Get modem wires status (DSR,CTS,Ring,Carrier) }
function GetModemStatus(): TModemStatus; override;
{ Set DTR (Data Terminal Ready) signal }
procedure SetDTR(AValue: Boolean); override;
{ Set RTS (Request to send) signal }
procedure SetRTS(AValue: Boolean); override;
property SerialClient: TSerialClient read FSerialClient;
published
{ Serial port name (COM1, /dev/ttyS01) }
property Port: string read FPort write FPort;
{ BaudRate - connection speed (50..4000000 bits per second), default 9600 }
property BaudRate: Integer read FBaudRate write SetBaudRate;
{ DataBits - default 8 (5 for Baudot code, 7 for true ASCII) }
property DataBits: Integer read FDataBits write SetDataBits;
{ Parity - (N - None, O - Odd, E - Even, M - Mark or S - Space) default N }
property Parity: AnsiChar read FParity write SetParity;
{ StopBits - (stb1, stb15, stb2), default stb1 }
property StopBits: TSerialStopBits read FStopBits write SetStopBits;
{ FlowControl - (sfcNone, sfcSend, sfcReady, sfcSoft) default sfcNone }
property FlowControl: TSerialFlowControl read FFlowControl write SetFlowControl;
{ Minimum bytes in incoming buffer to trigger OnDataAppear }
property MinDataBytes: Integer read FMinDataBytes write FMinDataBytes;
property Active;
property OnDataAppear;
property OnError;
property OnOpen;
property OnClose;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('DataPort', [TDataPortSerial]);
end;
// === TSerialClient ===
constructor TSerialClient.Create(AParent: TDataPortUART);
begin
inherited Create(True);
FParentDataPort := AParent;
SleepInterval := 10;
end;
procedure TSerialClient.Config();
begin
FDoConfig := True;
end;
procedure TSerialClient.SyncProc();
begin
if not CalledFromThread then
begin
CalledFromThread := True;
try
if Assigned(OnIncomingMsgEvent) then
OnIncomingMsgEvent(Self, sFromPort);
finally
CalledFromThread := False;
end;
end;
end;
procedure TSerialClient.SyncProcOnError();
begin
if not CalledFromThread then
begin
CalledFromThread := True;
try
if Assigned(OnErrorEvent) then
OnErrorEvent(Self, sLastError);
finally
CalledFromThread := False;
end;
end;
end;
procedure TSerialClient.SyncProcOnConnect();
begin
if not CalledFromThread then
begin
CalledFromThread := True;
try
if Assigned(OnConnectEvent) then
OnConnectEvent(Self);
finally
CalledFromThread := False;
end;
end;
end;
function TSerialClient.IsError(): Boolean;
begin
Result := (Serial.LastError <> 0) and (Serial.LastError <> ErrTimeout);
if Result then
begin
sLastError := Serial.LastErrorDesc;
if Assigned(FParentDataPort.OnError) then
Synchronize(SyncProcOnError)
else if Assigned(OnErrorEvent) then
OnErrorEvent(Self, sLastError);
Terminate();
end
end;
procedure TSerialClient.Execute();
var
SoftFlow: Boolean;
HardFlow: Boolean;
iStopBits: Integer;
begin
sLastError := '';
SoftFlow := False;
HardFlow := False;
iStopBits := 1;
if Terminated then Exit;
FSerial := TBlockSerial.Create();
try
Serial.DeadlockTimeout := 3000;
Serial.Connect(sPort);
Sleep(SleepInterval);
if Serial.LastError = 0 then
begin
case StopBits of
stb1: iStopBits := SB1;
stb15: iStopBits := SB1andHalf;
stb2: iStopBits := SB2;
end;
if FlowControl = sfcSoft then
SoftFlow := True
else if FlowControl = sfcSend then
HardFlow := True;
Serial.Config(BaudRate, DataBits, Parity, iStopBits, SoftFlow, HardFlow);
FDoConfig := False;
Sleep(SleepInterval);
end;
if not IsError() then
begin
if Assigned(FParentDataPort.OnOpen) then
Synchronize(SyncProcOnConnect)
else if Assigned(OnConnectEvent) then
OnConnectEvent(Self);
end;
while not Terminated do
begin
sLastError := '';
Serial.GetCommState();
if IsError() then
Break;
if FDoConfig then
begin
if FlowControl = sfcSoft then
SoftFlow := True
else if FlowControl = sfcSend then
HardFlow := True;
Serial.Config(BaudRate, DataBits, Parity, iStopBits, SoftFlow, HardFlow);
FDoConfig := False;
Sleep(SleepInterval);
end
else
begin
sFromPort := Serial.RecvPacket(SleepInterval);
end;
if IsError() then
Break
else if (Length(sFromPort) > 0) then
begin
try
if Assigned(FParentDataPort.OnDataAppear) then
Synchronize(SyncProc)
else
if Assigned(OnIncomingMsgEvent) then
OnIncomingMsgEvent(Self, sFromPort);
finally
sFromPort := '';
end;
end;
Sleep(1);
if sToSend <> '' then
begin
if Serial.CanWrite(SleepInterval) then
begin
Serial.SendString(sToSend);
if IsError() then
Break;
sToSend := '';
end;
end;
end;
finally
FreeAndNil(FSerial);
end;
end;
function TSerialClient.SendString(const AData: AnsiString): Boolean;
begin
Result := False;
if not Assigned(Self.Serial) then
Exit;
if SafeMode then
Self.sToSend := Self.sToSend + AData
else
begin
if Serial.CanWrite(100) then
Serial.SendString(AData);
if (Serial.LastError <> 0) and (Serial.LastError <> ErrTimeout) then
begin
sLastError := Serial.LastErrorDesc;
Synchronize(SyncProc);
Exit;
end;
end;
Result := True;
end;
procedure TSerialClient.SendStream(st: TStream);
var
ss: TStringStream;
begin
if not Assigned(Self.Serial) then
Exit;
if SafeMode then
begin
ss := TStringStream.Create('');
try
ss.CopyFrom(st, st.Size);
Self.sToSend := Self.sToSend + ss.DataString;
finally
ss.Free();
end;
end
else
begin
Serial.SendStreamRaw(st);
if Serial.LastError <> 0 then
begin
sLastError := Serial.LastErrorDesc;
Synchronize(SyncProc);
end;
end;
end;
{ TDataPortSerial }
constructor TDataPortSerial.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSerialClient := nil;
end;
destructor TDataPortSerial.Destroy();
begin
if Assigned(FSerialClient) then
begin
FSerialClient.OnIncomingMsgEvent := nil;
FSerialClient.OnErrorEvent := nil;
FSerialClient.OnConnectEvent := nil;
FreeAndNil(FSerialClient);
end;
inherited Destroy();
end;
function TDataPortSerial.CloseClient(): Boolean;
begin
Result := True;
if Assigned(FSerialClient) then
begin
Result := not FSerialClient.CalledFromThread;
if Result then
begin
FSerialClient.OnIncomingMsgEvent := nil;
FSerialClient.OnErrorEvent := nil;
FSerialClient.OnConnectEvent := nil;
FreeAndNil(FSerialClient);
end
else
FSerialClient.Terminate()
end;
end;
procedure TDataPortSerial.Open(const AInitStr: string = '');
{$IFDEF UNIX}
var
s: string;
{$ENDIF}
begin
inherited Open(AInitStr);
if not CloseClient() then
Exit;
FSerialClient := TSerialClient.Create(Self);
FSerialClient.OnIncomingMsgEvent := OnIncomingMsgHandler;
FSerialClient.OnErrorEvent := OnErrorHandler;
FSerialClient.OnConnectEvent := OnConnectHandler;
FSerialClient.SafeMode := HalfDuplex;
FSerialClient.sPort := FPort;
FSerialClient.BaudRate := FBaudRate;
FSerialClient.DataBits := FDataBits;
FSerialClient.Parity := FParity;
FSerialClient.StopBits := FStopBits;
FSerialClient.FlowControl := FFlowControl;
// Check serial port
//if Pos(Port, synaser.GetSerialPortNames())=0 then Exit;
{$IFDEF UNIX}
// detect lock file name
if Pos('tty', Port) > 0 then
begin
s := '/var/lock/LCK..' + Copy(Port, Pos('tty', Port), maxint);
if FileExists(s) then
begin
// try to remove lock file (if any)
DeleteFile(s);
end;
end;
{$ENDIF}
FSerialClient.Suspended := False;
// don't set FActive - will be set in OnConnect event after successfull connection
end;
procedure TDataPortSerial.Close();
begin
if Assigned(FSerialClient) then
begin
if FSerialClient.CalledFromThread then
FSerialClient.Terminate()
else
FreeAndNil(FSerialClient);
end;
inherited Close();
end;
class function TDataPortSerial.GetSerialPortNames: string;
begin
Result := synaser.GetSerialPortNames();
end;
function TDataPortSerial.GetModemStatus(): TModemStatus;
var
ModemWord: Integer;
begin
if Assigned(SerialClient) and Assigned(SerialClient.Serial) then
begin
ModemWord := SerialClient.Serial.ModemStatus();
{$IFNDEF MSWINDOWS}
FModemStatus.DSR := (ModemWord and TIOCM_DSR) > 0;
FModemStatus.CTS := (ModemWord and TIOCM_CTS) > 0;
FModemStatus.Carrier := (ModemWord and TIOCM_CAR) > 0;
FModemStatus.Ring := (ModemWord and TIOCM_RNG) > 0;
{$ELSE}
FModemStatus.DSR := (ModemWord and MS_DSR_ON) > 0;
FModemStatus.CTS := (ModemWord and MS_CTS_ON) > 0;
FModemStatus.Carrier := (ModemWord and MS_RLSD_ON) > 0;
FModemStatus.Ring := (ModemWord and MS_RING_ON) > 0;
{$ENDIF}
end;
Result := inherited GetModemStatus;
end;
procedure TDataPortSerial.SetDTR(AValue: Boolean);
begin
if Assigned(SerialClient) and Assigned(SerialClient.Serial) then
begin
SerialClient.Serial.DTR := AValue;
end;
inherited SetDTR(AValue);
end;
procedure TDataPortSerial.SetRTS(AValue: Boolean);
begin
if Assigned(SerialClient) and Assigned(SerialClient.Serial) then
begin
SerialClient.Serial.RTS := AValue;
end;
inherited SetRTS(AValue);
end;
function TDataPortSerial.Push(const AData: AnsiString): Boolean;
begin
Result := False;
if Assigned(SerialClient) and FLock.BeginWrite() then
begin
try
Result := SerialClient.SendString(AData);
finally
FLock.EndWrite();
end;
end;
end;
procedure TDataPortSerial.SetBaudRate(AValue: Integer);
begin
inherited SetBaudRate(AValue);
if Active then
begin
SerialClient.BaudRate := FBaudRate;
SerialClient.Config();
end;
end;
procedure TDataPortSerial.SetDataBits(AValue: Integer);
begin
inherited SetDataBits(AValue);
if Active then
begin
SerialClient.DataBits := FDataBits;
SerialClient.Config();
end;
end;
procedure TDataPortSerial.SetParity(AValue: AnsiChar);
begin
inherited SetParity(AValue);
if Active then
begin
SerialClient.Parity := FParity;
SerialClient.Config();
end;
end;
procedure TDataPortSerial.SetFlowControl(AValue: TSerialFlowControl);
begin
inherited SetFlowControl(AValue);
if Active then
begin
SerialClient.FlowControl := FFlowControl;
SerialClient.Config();
end;
end;
procedure TDataPortSerial.SetStopBits(AValue: TSerialStopBits);
begin
inherited SetStopBits(AValue);
if Active then
begin
SerialClient.StopBits := FStopBits;
SerialClient.Config();
end;
end;
end.
|
unit uClient;
interface
uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, Soap.encddecd,
System.IOUtils, FMX.Dialogs, FMX.Forms, Classes, SysUtils, System.UITypes,
System.Variants,
FMX.Graphics, Data.DB, Data.DbxSqlite, Data.SqlExpr, iClientsTalking1;
type
TClient = class(TCollectionItem)
public
id: string;
FIO: string;
DataTime: string;
Phone: string;
Adress: string;
Job: string;
Hobbie: string;
Photo: TBitmap;
destructor Destroy; override;
end;
TClientList = class(TCollection)
private
function GetClientsArray: clientsarray;
procedure SetClientsArray(const Value: clientsarray);
public
DBPath: string;
procedure AddClient(id, FIO, DataTime: string; Photo: TBitmap;
Phone: string = ''; Adress: string = ''; Job: string = '';
Hobbie: string = '');
function CreateDb: Tsqlconnection;
function GenerateId: string;
function InFormat64(Bitmap: TBitmap): string;
function From64(const base64: string): TBitmap;
procedure SaveItem(Item: TClient);
procedure LoadFromDatabas;
procedure SaveInBd;
procedure UpdateOnServer(Item: TClient);
procedure DeleteItem(Item: TClient; i: integer);
property ClientArray: clientsarray read GetClientsArray
write SetClientsArray;
end;
implementation
{ TClientList }
procedure TClientList.AddClient(id, FIO, DataTime: string; Photo: TBitmap;
Phone, Adress, Job, Hobbie: string);
var
Item: TClient;
begin
Item := TClient(self.Add);
Item.id := id;
Item.FIO := FIO;
Item.Photo := Photo;
Item.Phone := Phone;
Item.Adress := Adress;
Item.Job := Job;
Item.Hobbie := Hobbie;
Item.DataTime := DataTime;
end;
function TClientList.CreateDb: Tsqlconnection;
var
ASQLConnection: Tsqlconnection;
Path: string;
begin
ASQLConnection := Tsqlconnection.Create(nil);
ASQLConnection.ConnectionName := 'SQLITECONNECTION';
ASQLConnection.DriverName := 'Sqlite';
ASQLConnection.LoginPrompt := false;
ASQLConnection.Params.Values['Host'] := 'localhost';
ASQLConnection.Params.Values['FailIfMissing'] := 'False';
ASQLConnection.Params.Values['ColumnMetaDataSupported'] := 'False';
Createdir(IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) +
IncludeTrailingPathDelimiter('resourse'));
Path := IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) +
IncludeTrailingPathDelimiter('resourse') + 'clients.db';
ASQLConnection.Params.Values['Database'] := Path;
ASQLConnection.Execute('CREATE TABLE if not exists clients(' + 'Cl_id TEXT,' +
'FIO TEXT,' + 'Phone TEXT,' + 'Adress TEXT,' + 'DataTime Text' + ');', nil);
ASQLConnection.Open;
result := ASQLConnection;
end;
procedure TClientList.DeleteItem(Item: TClient; i: integer);
var
connect: Tsqlconnection;
query: TSQLQuery;
begin
connect := CreateDb;
query := TSQLQuery.Create(nil);
try
query.SQLConnection := connect;
query.SQL.Text := 'Delete from clients Where Cl_id = "' + Item.id + '"';
query.ExecSQL();
finally
FreeAndNil(query);
end;
FreeAndNil(connect);
FreeAndNil(Item);
end;
function TClientList.From64(const base64: string): TBitmap;
var
Input: TStringStream;
Output: TBytesStream;
begin
Input := TStringStream.Create(base64, TEncoding.ASCII);
try
Output := TBytesStream.Create;
try
Soap.encddecd.DecodeStream(Input, Output);
Output.Position := 0;
result := TBitmap.Create;
try
result.LoadFromStream(Output);
except
result.Free;
raise;
end;
finally
Output.Free;
end;
finally
Input.Free;
end;
end;
function TClientList.GenerateId: string;
begin
result := formatdatetime('hhmmsszz', now);
end;
function TClientList.GetClientsArray: clientsarray;
var
server: iclientstalking;
Objects: clientsarray;
i: integer;
begin
server := GetIClientsTalking;
for i := 0 to self.Count - 1 do
begin
SetLength(Objects, i + 1);
Objects[i] := TClientServ.Create;
Objects[i].id := TClient(self.Items[i]).id;
Objects[i].FIO := TClient(self.Items[i]).FIO;
Objects[i].Adress := TClient(self.Items[i]).Adress;
Objects[i].Phone := TClient(self.Items[i]).Phone;
Objects[i].Photo := InFormat64(TClient(self.Items[i]).Photo);
end;
result := Objects;
end;
function TClientList.InFormat64(Bitmap: TBitmap): string;
var
Input: TBytesStream;
Output: TStringStream;
begin
Input := TBytesStream.Create;
try
Bitmap.SaveToStream(Input);
Input.Position := 0;
Output := TStringStream.Create('', TEncoding.ASCII);
try
Soap.encddecd.EncodeStream(Input, Output);
result := Output.DataString;
finally
Output.Free;
end;
finally
Input.Free;
end;
end;
procedure TClientList.LoadFromDatabas;
var
Image: TBitmap;
Item: TClient;
ASQLConnection: Tsqlconnection;
Path: string;
ResImage: TResourceStream;
RS: TDataset;
begin
ASQLConnection := CreateDb;
try
ASQLConnection.Execute
('select Cl_id,FIO,Phone,Adress,DataTime from clients', nil, RS);
try
while not RS.Eof do
begin
Item := TClient(self.Add);
Item.id := RS.FieldByName('Cl_id').Value;
Item.FIO := RS.FieldByName('FIO').Value;
Item.Phone := RS.FieldByName('Phone').Value;
Item.Adress := RS.FieldByName('Adress').Value;
Item.DataTime := RS.FieldByName('DataTime').Value;
Path := IncludeTrailingPathDelimiter(Tpath.GetSharedDocumentsPath) +
IncludeTrailingPathDelimiter('resourse') + RS.FieldByName('Cl_id')
.Value + '.jpg';
if not FileExists(Path) then
begin
ResImage := TResourceStream.Create(HInstance, 'Standart_Picture',
RT_RCDATA);
try
Image := TBitmap.Create;
Image.LoadFromStream(ResImage);
Item.Photo := Image;
finally
FreeAndNil(ResImage);
end;
end
else
begin
Image := TBitmap.Create;
Image.LoadFromFile(IncludeTrailingPathDelimiter
(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter
('resourse') + RS.FieldByName('Cl_id').Value + '.jpg');
Item.Photo := Image;
end;
RS.Next;
end;
finally
FreeAndNil(RS);
end;
finally
end;
FreeAndNil(ASQLConnection);
end;
procedure TClientList.SaveInBd;
const
cInsertQuery =
'INSERT INTO clients (Cl_id,FIO,Phone,Adress,DataTime) VALUES (:id,:FIO,:Phone,:Adress,:DataTime)';
var
Image: TBitmap;
i: integer;
DB: Tsqlconnection;
Params: TParams;
begin
DB := CreateDb;
try
for i := 0 to self.Count - 1 do
begin
Params := TParams.Create;
Params.CreateParam(TFieldType.ftString, 'id', ptInput);
Params.ParamByName('id').AsString := TClient(self.Items[i]).id;
Params.CreateParam(TFieldType.ftString, 'FIO', ptInput);
Params.ParamByName('FIO').AsString := TClient(self.Items[i]).FIO;
Params.CreateParam(TFieldType.ftString, 'DataTime', ptInput);
Params.ParamByName('DataTime').AsString :=
formatdatetime('dd/mm/yy hh:mm:ss.zz', now);
Params.CreateParam(TFieldType.ftString, 'Phone', ptInput);
Params.ParamByName('Phone').AsString := TClient(self.Items[i]).Phone;
Params.CreateParam(TFieldType.ftString, 'Adress', ptInput);
Params.ParamByName('Adress').AsString := TClient(self.Items[i]).Adress;
Image := TClient(self.Items[i]).Photo;
Image.SaveToFile(IncludeTrailingPathDelimiter
(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter
('resourse') + TClient(self.Items[i]).id + '.jpg');
DB.Execute(cInsertQuery, Params);
FreeAndNil(Params);
end;
finally
FreeAndNil(DB);
end;
end;
procedure TClientList.SaveItem(Item: TClient);
const
cInsertQuery =
'UPDATE clients SET `FIO` =:FIO, `Phone`= :Phone, `Adress` = :Adress,`DataTime` = :DataTime WHERE Cl_id="%s"';
var
Image: TBitmap;
query: String;
querity: TSQLQuery;
connect: Tsqlconnection;
begin
connect := CreateDb;
querity := TSQLQuery.Create(nil);
try
querity.SQLConnection := connect;
querity.SQL.Text := 'select CL_id from clients where Cl_id = "' +
Item.id + '"';
querity.Open;
if not querity.Eof then
begin
query := Format(cInsertQuery, [Item.id]);
querity.Params.CreateParam(TFieldType.ftString, 'FIO', ptInput);
querity.Params.ParamByName('FIO').AsString := Item.FIO;
querity.Params.CreateParam(TFieldType.ftString, 'Phone', ptInput);
querity.Params.ParamByName('Phone').AsString := Item.Phone;
Image := Item.Photo;
Image.SaveToFile(IncludeTrailingPathDelimiter
(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter
('resourse') + Item.id + '.jpg');
querity.Params.CreateParam(TFieldType.ftString, 'Adress', ptInput);
querity.Params.ParamByName('Adress').AsString := Item.Adress;
querity.Params.CreateParam(TFieldType.ftString, 'DataTime', ptInput);
querity.Params.ParamByName('DataTime').AsString :=
formatdatetime('dd/mm/yy hh:mm:ss:zz', now);
querity.SQL.Text := query;
querity.ExecSQL();
end
else
begin
query := 'INSERT INTO clients (Cl_id,FIO,Phone,Adress,DataTime) VALUES (:id,:FIO,:Phone,:Adress,:DataTime)';
querity.Params.CreateParam(TFieldType.ftString, 'id', ptInput);
querity.Params.ParamByName('id').AsString := self.GenerateId;
Item.id := querity.Params.ParamByName('id').AsString;
querity.Params.CreateParam(TFieldType.ftString, 'FIO', ptInput);
querity.Params.ParamByName('FIO').AsString := Item.FIO;
querity.Params.CreateParam(TFieldType.ftString, 'DataTime', ptInput);
querity.Params.ParamByName('DataTime').AsString :=
formatdatetime('dd/mm/yy hh:mm:ss:zz', now);
querity.Params.CreateParam(TFieldType.ftString, 'Phone', ptInput);
querity.Params.ParamByName('Phone').AsString := Item.Phone;
querity.Params.CreateParam(TFieldType.ftString, 'Adress', ptInput);
querity.Params.ParamByName('Adress').AsString := Item.Adress;
Image := Item.Photo;
Image.SaveToFile(IncludeTrailingPathDelimiter
(Tpath.GetSharedDocumentsPath) + IncludeTrailingPathDelimiter
('resourse') + Item.id + '.jpg');
querity.SQL.Text := query;
querity.ExecSQL();
end;
finally
FreeAndNil(querity);
end;
FreeAndNil(connect);
end;
procedure TClientList.SetClientsArray(const Value: clientsarray);
var
server: iclientstalking;
i: integer;
begin
server := GetIClientsTalking;
for i := 0 to length(Value) - 1 do
server.AddClientInBd(Value[i]);
end;
procedure TClientList.UpdateOnServer(Item: TClient);
var
server: iclientstalking;
i: integer;
Clients: TClientServ;
begin
end;
{ TClient }
destructor TClient.Destroy;
begin
FreeAndNil(Photo);
inherited;
end;
end.
|
unit uPlStimModule;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Windows, ActiveX, Classes, ComObj, uModules, MMSystem, SysUtils, Dialogs, OpenGL,
uPlStimModuleInterface, uPlDirectSoundPluginInterface, uPlImagePluginInterface;
type
TPlStimModule = class(TCustomModule, IPlStimModuleInterface)
//IModuleInterface
protected
function GetGUID: TGUID; override;
function GetModuleName: WideString; override;
function ModuleInitialize: Boolean; override;
procedure SetNotifyWindowHandle(const Value: THandle); override;
//IPlStimModuleInterface
public
//Работа с изображениями
function Image_LoadFromFile(const FileNameW: PWideChar): HIMAGE;
function Image_LoadFromPointer(PData: Pointer; DataSize: Integer): HIMAGE;
function Image_WindowShow(MonitorIndex: Integer; WindowRect: TRect): HWND;
function Image_WindowHide: HRESULT;
function Image_Show(AImage: HIMAGE): HRESULT;
function Image_ShowPreview(AImage: HIMAGE): HRESULT;
function Image_Hide(AImage: HIMAGE): HRESULT;
function Image_GetData(AImage: HIMAGE; var PData: Pointer; var DataSize: Integer): HRESULT;
function Image_Duplicate(AImage: HIMAGE): HIMAGE;
procedure Image_Free(AImage: HIMAGE);
function Image_GetPreviewTex(AImage: HIMAGE; ADC: HDC; ARC: HGLRC): GLuint;
procedure Image_FreeGLContext(ADC: HDC; ARC: HGLRC);
//Работа со звуком
function Effect_LoadFromFile(const FileNameW: PWideChar): HEFFECT;
function Effect_LoadFromPointer(var wf: tWAVEFORMATEX; PData: Pointer; DataSize: Integer): HEFFECT; overload;
function Effect_LoadFromPointer(PData: Pointer; DataSize: Integer): HEFFECT; overload;
function Effect_GetStatus(AEffect: HEFFECT; var pdwStatus: Cardinal): HRESULT;
function Effect_StartPlay(AEffect: HEFFECT; PlayLooping: Boolean): HRESULT;
function Effect_StopPlay(AEffect: HEFFECT): HRESULT;
function Effect_StartCapture: HEFFECT;
function Effect_StopCapture(AEffect: HEFFECT): HRESULT;
function Effect_GetTime(AEffect: HEFFECT): Integer;
function Effect_GetData(AEffect: HEFFECT; var PData: Pointer; var DataSize: Integer): HRESULT;
function Effect_Duplicate(AEffect: HEFFECT): HEFFECT;
procedure Effect_Free(AEffect: HEFFECT);
procedure Sound_SetWindowHandle(Win: HWND);
public
procedure Initialize; override;
destructor Destroy; override;
private
FIDSPlugin: IPlDirectSoundPluginInterface;
FIImagePlugin: IPlImagePluginInterface;
//указатель на временную область памяти используется для доступа к данным звука
FPTempMem: Pointer;
function CreateTempMemAudio(pWaveFormat: PWaveFormatEx; pvAudioPtr1: Pointer; dwAudioBytes1: DWORD;
pvAudioPtr2: Pointer; dwAudioBytes2: DWORD): Integer;
end;
const
FOURCC_RIFF = $46464952; { 'RIFF' }
FOURCC_WAVE = $45564157; { 'WAVE' }
FOURCC_FMT = $20746d66; { 'fmt ' }
FOURCC_FACT = $74636166; { 'fact' }
FOURCC_DATA = $61746164; { 'data' }
implementation
uses ComServ;
{ TPlStimModule }
function TPlStimModule.CreateTempMemAudio(pWaveFormat: PWaveFormatEx;
pvAudioPtr1: Pointer; dwAudioBytes1: DWORD; pvAudioPtr2: Pointer;
dwAudioBytes2: DWORD): Integer;
const
add_mem = 1024 * 100; //100 кб памяти резервируем для формата
var
mi: MMIOINFO;
mmfp: HMMIO;
mminfopar : TMMCKINFO;
mminfosub : TMMCKINFO;
dwTotalSamples : Cardinal;
begin
Result := 0;
if FPTempMem <> nil then
FreeMem(FPTempMem);
GetMem(FPTempMem, dwAudioBytes1 + dwAudioBytes2 + add_mem);
FillChar(mi, sizeof(mi), 0);
mi.pchBuffer := FPTempMem;
mi.cchBuffer := dwAudioBytes1 + dwAudioBytes2 + add_mem;
mi.fccIOProc := FOURCC_MEM;
mmfp := mmioOpen(nil, @mi, MMIO_CREATE or MMIO_READWRITE);
if (mmfp <> 0) then
begin
try
mminfopar.fccType := FOURCC_WAVE;
mminfopar.cksize := 0; // let the function determine the size
if mmioCreateChunk(mmfp, @mminfopar, MMIO_CREATERIFF) = 0 then
begin
mminfosub.ckid := FOURCC_FMT;
mminfosub.cksize :=0; // let the function determine the size
if mmioCreateChunk(mmfp, @mminfosub, 0) = 0 then
begin
if mmioWrite(mmfp, PAnsiChar(pWaveFormat), sizeof(tWAVEFORMATEX) + pWaveFormat.cbSize) = LongInt(sizeof(tWAVEFORMATEX) + pWaveFormat.cbSize) then
begin
// back out of format chunk...
mmioAscend(mmfp, @mminfosub, 0);
// write the fact chunk (required for all non-PCM .wav files...
// this chunk just contains the total length in samples...
mminfosub.ckid := FOURCC_FACT;
mminfosub.cksize := sizeof(DWORD);
if mmioCreateChunk(mmfp, @mminfosub, 0) = 0 then
begin
dwTotalSamples := (dwAudioBytes1 + dwAudioBytes2) * 8 div pWaveFormat.wBitsPerSample;
if mmioWrite(mmfp, PAnsiChar(@dwTotalSamples), sizeof(dwTotalSamples)) = sizeof(dwTotalSamples) then
begin
// back out of fact chunk...
mmioAscend(mmfp, @mminfosub, 0);
// now create and write the wave data chunk...
mminfosub.ckid := FOURCC_DATA;
mminfosub.cksize := 0; // let the function determine the size
if mmioCreateChunk(mmfp, @mminfosub, 0) = 0 then
begin
if mmioWrite(mmfp, PAnsiChar(pvAudioPtr1), dwAudioBytes1) <> -1 then
begin
if pvAudioPtr2 <> nil then
mmioWrite(mmfp, PAnsiChar(pvAudioPtr2), dwAudioBytes2);
// back out and cause the size of the data buffer to be written...
mmioAscend(mmfp, @mminfosub , 0);
// ascend out of the RIFF chunk...
mmioAscend(mmfp, @mminfopar, 0);
//Считываем длину получившегося файла
Result := mmioSeek(mmfp, 0, SEEK_END)
end;
end;
end;
end;
end;
end;
end;
finally
mmioClose(mmfp, 0);
end;
end;
end;
destructor TPlStimModule.Destroy;
begin
if (FPTempMem <> nil) then
FreeMem(FPTempMem);
FIDSPlugin := nil;
FIImagePlugin := nil;
inherited;
end;
function TPlStimModule.Effect_Duplicate(AEffect: HEFFECT): HEFFECT;
begin
if (FIDSPlugin <> nil) then
Result := FIDSPlugin.DSEffect_Duplicate(AEffect)
else
Result := 0;
end;
procedure TPlStimModule.Effect_Free(AEffect: HEFFECT);
begin
if (FIDSPlugin <> nil) then
FIDSPlugin.DSEffect_Free(AEffect);
end;
function TPlStimModule.Effect_GetData(AEffect: HEFFECT; var PData: Pointer;
var DataSize: Integer): HRESULT;
var
es: DWord;
wf: TWaveFormatEX;
audioPtr1, audioPtr2: Pointer;
audioBytes1, AudioBytes2: DWord;
begin
if (FIDSPlugin <> nil) then
begin
Result := FIDSPlugin.DSEffect_GetSize(AEffect, @es);
if (Result = S_OK) then
begin
Result := FIDSPlugin.DSEffect_GetFormat(AEffect, @wf);
if (Result = S_OK) then
begin
Result := FIDSPlugin.DSEffect_Lock(AEffect, 0, es, @audioPtr1, @audioBytes1,
@audioPtr2, @audioBytes2, 0);
if (Result = S_OK) then
begin
try
// DataSize := CreateTempMemAudio(@wf, audioPtr1, audioBytes1, audioPtr2, audioBytes2);
GetMem(FPTempMem, audioBytes1);
Move(audioPtr1^, FPTempMem^, audioBytes1);
// FPTempMem := audioPtr1;
DataSize := audioBytes1;
if DataSize > 0 then
PData := FPTempMem
else
Result := E_FAIL;
finally
FIDSPlugin.DSEffect_Unlock(AEffect, audioPtr1, audioBytes1, audioPtr2, audioBytes2);
end;
end;
end;
end;
end
else
Result := S_FALSE;
end;
function TPlStimModule.Effect_GetStatus(AEffect: HEFFECT;
var pdwStatus: Cardinal): HRESULT;
begin
if (FIDSPlugin <> nil) then
Result := FIDSPlugin.DSEffect_GetStatus(AEffect, pdwStatus)
else
Result := E_FAIL;
end;
function TPlStimModule.Effect_GetTime(AEffect: HEFFECT): Integer;
var
es: DWord;
wf: TWaveFormatEX;
begin
if (FIDSPlugin <> nil) and
(FIDSPlugin.DSEffect_GetSize(AEffect, @es) = S_OK) and
(FIDSPlugin.DSEffect_GetFormat(AEffect, @wf) = S_OK) then
begin
Result := es * 1000 div wf.nAvgBytesPerSec;
end
else
Result := 0;
end;
function TPlStimModule.Effect_LoadFromFile(const FileNameW: PWideChar): HEFFECT;
var
fs: TFileStream;
data: Pointer;
begin
Result := 0;
if FileExists(WideString(FileNameW)) then
begin
fs := TFileStream.Create(WideString(FileNameW), fmShareDenyNone{fmOpenRead});
try
GetMem(data, fs.Size);
try
fs.Position := 0;
fs.ReadBuffer(data^, fs.Size);
Result := Effect_LoadFromPointer(data, fs.Size);
finally
FreeMem(data);
end;
finally
fs.Free;
end;
end;
end;
function TPlStimModule.Effect_LoadFromPointer(var wf: tWAVEFORMATEX; PData: Pointer;
DataSize: Integer): HEFFECT;
var
bufSize: Integer;
begin
Result := 0;
if (FIDSPlugin <> nil) and
(PData <> nil) and
(DataSize > 0) then
begin
bufSize := DataSize;
if bufSize > 0 then
begin
Result := FIDSPlugin.DSEffect_Load(@wf, PData, bufSize);
end;
end;
end;
function TPlStimModule.Effect_LoadFromPointer(PData: Pointer;
DataSize: Integer): HEFFECT;
var
mi: MMIOINFO;
mmfp: HMMIO;
mminfopar : TMMCKINFO;
mminfosub : TMMCKINFO;
wf: tWAVEFORMATEX;
buf: Pointer;
bufSize: Cardinal;
begin
Result := 0;
if (FIDSPlugin <> nil) and
(PData <> nil) and
(DataSize > 0) then
begin
FillChar(mi, sizeof(mi), 0);
mi.pchBuffer := PData;
mi.cchBuffer := DataSize;
mi.fccIOProc := FOURCC_MEM;
mmfp := mmioOpen(nil, @mi, MMIO_READ);
if (mmfp <> 0) then
begin
try
//Читаем формат
// search for wave type and format chunks...
mminfopar.fccType := FOURCC_WAVE;
if mmioDescend(mmfp, @mminfopar, nil, MMIO_FINDRIFF) <> 0 then
Exit;
mminfosub.ckid := FOURCC_FMT;
if mmioDescend(mmfp, @mminfosub, @mminfopar, MMIO_FINDCHUNK) <> 0 then
Exit;
// read the wave format...
if mmioRead(mmfp, PAnsiChar(@wf), mminfosub.cksize) <> LongInt(mminfosub.cksize) then
Exit;
mmioAscend(mmfp, @mminfosub, 0);
//Читаем данные
// search for data
mminfosub.ckid := FOURCC_DATA;
if mmioDescend(mmfp, @mminfosub, @mminfopar, MMIO_FINDCHUNK) <> 0 then
Exit;
bufSize := mminfosub.cksize;
if bufSize > 0 then
begin
GetMem(buf, bufSize);
try
if mmioRead(mmfp, PAnsiChar(buf), bufSize) > 0 then
Result := FIDSPlugin.DSEffect_Load(@wf, buf, bufSize);
finally
FreeMem(buf);
end;
end;
finally
mmioClose(mmfp, 0);
end;
end;
end;
end;
function TPlStimModule.Effect_StartPlay(AEffect: HEFFECT; PlayLooping: Boolean): HRESULT;
begin
if (FIDSPlugin <> nil) then
Result := FIDSPlugin.DSEffect_StartPlay(AEffect, PlayLooping)
else
Result := E_FAIL;
end;
function TPlStimModule.Effect_StartCapture: HEFFECT;
begin
if (FIDSPlugin <> nil) then
Result := FIDSPlugin.DSEffect_StartCapture
else
Result := 0;
end;
function TPlStimModule.Effect_StopCapture(AEffect: HEFFECT): HRESULT;
begin
if (FIDSPlugin <> nil) then
Result := FIDSPlugin.DSEffect_StopCapture(AEffect)
else
Result := S_FALSE;
end;
function TPlStimModule.Effect_StopPlay(AEffect: HEFFECT): HRESULT;
begin
if (FIDSPlugin <> nil) then
Result := FIDSPlugin.DSEffect_StopPlay(AEffect)
else
Result := S_FALSE;
end;
function TPlStimModule.GetGUID: TGUID;
begin
Result := Class_PlStimModule
end;
function TPlStimModule.GetModuleName: WideString;
begin
Result := 'Stim';
end;
function TPlStimModule.Image_Duplicate(AImage: HIMAGE): HIMAGE;
begin
if (FIImagePlugin <> nil) then
Result := FIImagePlugin.IMImage_Duplicate(AImage)
else
Result := 0;
end;
procedure TPlStimModule.Image_Free(AImage: HIMAGE);
begin
if (FIImagePlugin <> nil) then
FIImagePlugin.IMImage_Free(AImage);
end;
procedure TPlStimModule.Image_FreeGLContext(ADC: HDC; ARC: HGLRC);
begin
if (FIImagePlugin <> nil) then
FIImagePlugin.IMImage_FreeGLContext(ADC, ARC);
end;
function TPlStimModule.Image_GetData(AImage: HIMAGE; var PData: Pointer;
var DataSize: Integer): HRESULT;
begin
if (FIImagePlugin <> nil) then
Result := FIImagePlugin.IMImage_GetData(AImage, PData, DataSize)
else
Result := E_FAIL;
end;
function TPlStimModule.Image_GetPreviewTex(AImage: HIMAGE; ADC: HDC;
ARC: HGLRC): GLuint;
begin
if (FIImagePlugin <> nil) then
Result := FIImagePlugin.IMImage_GetPreviewTex(AImage, ADC, ARC)
else
Result := 0;
end;
function TPlStimModule.Image_Hide(AImage: HIMAGE): HRESULT;
begin
if (FIImagePlugin <> nil) then
Result := FIImagePlugin.IMImage_Hide(AImage)
else
Result := E_FAIL;
end;
function TPlStimModule.Image_LoadFromFile(const FileNameW: PWideChar): HIMAGE;
var
fs: TFileStream;
data: Pointer;
begin
Result := 0;
if FileExists(WideString(FileNameW)) then
begin
fs := TFileStream.Create(WideString(FileNameW), fmOpenRead);
try
GetMem(data, fs.Size);
try
fs.Position := 0;
fs.ReadBuffer(data^, fs.Size);
Result := Image_LoadFromPointer(data, fs.Size);
finally
FreeMem(data);
end;
finally
fs.Free;
end;
end;
end;
function TPlStimModule.Image_LoadFromPointer(PData: Pointer;
DataSize: Integer): HIMAGE;
begin
if (FIImagePlugin <> nil) then
Result := FIImagePlugin.IMImage_Load(PData, DataSize)
else
Result := 0;
end;
function TPlStimModule.Image_Show(AImage: HIMAGE): HRESULT;
begin
if (FIImagePlugin <> nil) then
Result := FIImagePlugin.IMImage_Show(AImage)
else
Result := E_FAIL;
end;
function TPlStimModule.Image_ShowPreview(AImage: HIMAGE): HRESULT;
begin
if (FIImagePlugin <> nil) then
Result := FIImagePlugin.IMImage_ShowPreview(AImage)
else
Result := E_FAIL;
end;
function TPlStimModule.Image_WindowHide: HRESULT;
begin
if (FIImagePlugin <> nil) then
Result := FIImagePlugin.IMImage_WindowHide
else
Result := E_FAIL;
end;
function TPlStimModule.Image_WindowShow(MonitorIndex: Integer;
WindowRect: TRect): HWND;
begin
if (FIImagePlugin <> nil) then
Result := FIImagePlugin.IMImage_WindowShow(MonitorIndex, WindowRect)
else
Result := 0;
end;
procedure TPlStimModule.Initialize;
var
ii: IInterface;
begin
inherited;
ii := CreateComObject(Class_PlDirectSoundPlugin);
if (ii <> nil) then
ii.QueryInterface(IPlDirectSoundPluginInterface, FIDSPlugin);
ii := CreateComObject(Class_PlImagePlugin);
if (ii <> nil) then
ii.QueryInterface(IPlImagePluginInterface, FIImagePlugin);
end;
function TPlStimModule.ModuleInitialize: Boolean;
begin
Result := True;
// if FIDSPlugin <> nil then
// begin
// FIDSPlugin.DSSetWindowHandle(FNotifyWindowHandle);
// Result := FIDSPlugin.DSPluginInitialize = S_OK;
// end;
end;
procedure TPlStimModule.SetNotifyWindowHandle(const Value: THandle);
begin
inherited;
Sound_SetWindowHandle(Value);
FIDSPlugin.DSPluginInitialize;
end;
procedure TPlStimModule.Sound_SetWindowHandle(Win: HWND);
begin
if FIDSPlugin <> nil then
FIDSPlugin.DSSetWindowHandle(Win);
end;
initialization
TComObjectFactory.Create(ComServer, TPlStimModule, Class_PlStimModule,
'PlStimModule', '', ciMultiInstance, tmApartment);
end.
|
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium Software
E-Mail: mshkolnik@scalabium.com
mshkolnik@yahoo.com
WEB: http://www.scalabium.com
In this unit I described the design-time editor for TSMLanguage component
}
unit SMLangR;
interface
{$I SMVersion.inc}
uses Classes,
{$IFDEF SMForDelphi6} DesignIntf, DesignEditors {$ELSE} DsgnIntf {$ENDIF};
procedure Register;
implementation
{$R SMLANG.DCR}
uses Dialogs, TypInfo, SMLang;
type
{ TSMLanguageComponentEditor }
TSMLanguageComponentEditor = class(TComponentEditor)
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TSMLanguageFile = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
procedure Register;
begin
RegisterComponents('SMComponents', [TSMLanguage]);
RegisterComponentEditor(TSMLanguage, TSMLanguageComponentEditor);
RegisterPropertyEditor(TypeInfo(string), TSMLanguage, 'ResourceFile', TSMLanguageFile);
end;
{ TSMLanguageComponentEditor }
procedure TSMLanguageComponentEditor.ExecuteVerb(Index: Integer);
function ConvertStrings(const s: string): string;
begin
Result := s
end;
procedure ProcessComponent(AComponent: TComponent; Properties: TStrings; strParentName: string);
var
i, j, k: Integer;
PropList: TPropList;
PropInfo: PPropInfo;
begin
if not Assigned(AComponent) or (AComponent.Name = '') then exit;
i := GetPropList(AComponent.ClassInfo, tkProperties, @PropList);
for j := 0 to i-1 do
begin
if (PropList[j].Name = 'Name') then continue;
if Properties.IndexOf(PropList[j].Name) < 0 then
begin
PropInfo := GetPropInfo(AComponent.ClassInfo, PropList[j].Name);
if (PropInfo <> nil) then
if (PropInfo^.PropType^^.Kind in [tkString, tkLString, tkWString
{$IFDEF SMForDelphi2009} , tkUString {$ENDIF}
{, tkInteger}]) then
begin
try
Properties.Add(strParentName + AComponent.Name + '.' + PropList[j].Name + ' = ' + GetStrProp(AComponent, PropInfo))
except
end
end
else
if (PropInfo^.PropType^^.Kind = tkClass) then
begin
k := GetOrdProp(AComponent, PropInfo);
if (TObject(k) is TStrings) then
Properties.Add(strParentName + AComponent.Name + '.' + PropList[j].Name + ' = ' + ConvertStrings(TStrings(k).Text))
end;
end;
end;
for i := 0 to AComponent.ComponentCount-1 do
ProcessComponent(AComponent.Components[i], Properties, AComponent.Name + '.');
end;
const
strLangFilter = 'Language files (*.lng)|(*.lng)|All files (*.*)|(*.*)';
begin
with (Component as TSMLanguage) do
case Index of
0: begin
with TSaveDialog.Create(nil) do
try
FileName := ResourceFile;
Filter := strLangFilter;
Options := [];
if Execute then
SaveResources(nil, FileName);
finally
Free
end;
end;
1: begin
with TOpenDialog.Create(nil) do
try
FileName := ResourceFile;
Filter := strLangFilter;
Options := [ofPathMustExist];
if Execute then
LoadResources(FileName);
finally
Free
end;
end;
end
end;
function TSMLanguageComponentEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := 'Generate language file...';
1: Result := 'Load from language file...';
end;
end;
function TSMLanguageComponentEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
{ TSMLanguageFile }
procedure TSMLanguageFile.Edit;
begin
with TOpenDialog.Create(nil) do
try
FileName := GetValue;
Filter := 'Language files (*.lng)|(*.lng)|All files (*.*)|(*.*)';
Options := [ofPathMustExist];
if Execute then
SetValue(FileName);
finally
Free
end;
end;
function TSMLanguageFile.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paRevertable];
end;
end. |
{******************************************}
{ TeeChart Surface Series Nearest Tool }
{ Copyright (c) 2003-2004 by David Berneda }
{ All Rights Reserved }
{******************************************}
unit TeeSurfaceTool;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
{$ENDIF}
TeeTools, TeCanvas, TeEngine, Chart, TeeSurfa;
type
TSurfaceNearestTool=class(TTeeCustomToolSeries)
private
FCell : TColor;
FColumn : TColor;
FRow : TColor;
FOnSelect : TNotifyEvent;
procedure SetCell(const Value: TColor);
procedure SetColumn(const Value: TColor);
procedure SetRow(const Value: TColor);
protected
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
class Function GetEditorClass:String; override;
procedure SetSeries(const Value: TChartSeries); override;
public
SelectedCell : Integer;
Constructor Create(AOwner:TComponent); override;
class Function Description:String; override;
Procedure GetRowCol(var Row,Col:Double);
published
property CellColor:TColor read FCell write SetCell default clRed;
property ColumnColor:TColor read FColumn write SetColumn default clGreen;
property RowColor:TColor read FRow write SetRow default clBlue;
property Series;
property OnSelectCell:TNotifyEvent read FOnSelect write FOnSelect;
end;
TSurfaceNearest = class(TForm)
ButtonColor1: TButtonColor;
ButtonColor2: TButtonColor;
ButtonColor3: TButtonColor;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
Label1: TLabel;
CBSeries: TComboBox;
CheckBox4: TCheckBox;
CheckBox5: TCheckBox;
CheckBox6: TCheckBox;
procedure CheckBox1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CheckBox2Click(Sender: TObject);
procedure CheckBox3Click(Sender: TObject);
procedure ButtonColor1Click(Sender: TObject);
procedure ButtonColor2Click(Sender: TObject);
procedure ButtonColor3Click(Sender: TObject);
procedure CBSeriesChange(Sender: TObject);
procedure CheckBox4Click(Sender: TObject);
procedure CheckBox5Click(Sender: TObject);
procedure CheckBox6Click(Sender: TObject);
private
{ Private declarations }
Tool : TSurfaceNearestTool;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
uses TeeProCo;
{ TSurfaceNearestTool }
Constructor TSurfaceNearestTool.Create(AOwner: TComponent);
begin
inherited;
FColumn:=clGreen;
FRow:=clBlue;
FCell:=clRed;
SelectedCell:=-1;
end;
class function TSurfaceNearestTool.Description: String;
begin
result:=TeeMsg_SurfaceNearestTool;
end;
class function TSurfaceNearestTool.GetEditorClass: String;
begin
result:='TSurfaceNearest';
end;
procedure TSurfaceNearestTool.SetSeries(const Value: TChartSeries);
begin
if Value is TSurfaceSeries then inherited
else inherited SetSeries(nil);
end;
Procedure TSurfaceNearestTool.GetRowCol(var Row,Col:Double);
var tmpO : TCellsOrientation;
begin
if SelectedCell=-1 then
begin
Row:=-1;
Col:=-1;
end
else
with TSurfaceSeries(Series) do
begin
tmpO:=CellsOrientation;
Row:=XValues.Value[SelectedCell];
if tmpO.IncX=1 then Row:=Row-1;
Col:=ZValues.Value[SelectedCell];
if tmpO.IncZ=-1 then Col:=Col+1;
end;
end;
procedure TSurfaceNearestTool.ChartMouseEvent(AEvent: TChartMouseEvent;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var tmp,t : Integer;
tmpRow,tmpCol : Double;
begin
if (AEvent=cmeMove) and Assigned(Series) then
begin
tmp:=Series.Clicked(x,y);
if tmp<>SelectedCell then
begin
SelectedCell:=tmp;
Series.ParentChart.AutoRepaint:=False;
with TCustom3DSeries(Series) do
if SelectedCell=-1 then
for t:=0 to Count-1 do
ValueColor[t]:=clTeeColor
else
begin
GetRowCol(tmpRow,tmpCol);
for t:=0 to Count-1 do
if (XValues.Value[t]=tmpRow) and (ZValues.Value[t]=tmpCol) then
ValueColor[t]:=CellColor
else
if XValues.Value[t]=tmpRow then
ValueColor[t]:=RowColor
else
if ZValues.Value[t]=tmpCol then
ValueColor[t]:=ColumnColor
else
ValueColor[t]:=clTeeColor;
end;
Series.ParentChart.AutoRepaint:=True;
Series.ParentChart.Invalidate;
if Assigned(FOnSelect) then FOnSelect(Self);
end;
end;
end;
procedure TSurfaceNearestTool.SetColumn(const Value: TColor);
begin
SetColorProperty(FColumn,Value);
end;
procedure TSurfaceNearestTool.SetRow(const Value: TColor);
begin
SetColorProperty(FRow,Value);
end;
procedure TSurfaceNearestTool.SetCell(const Value: TColor);
begin
SetColorProperty(FCell,Value);
end;
procedure TSurfaceNearest.CheckBox1Click(Sender: TObject);
begin
Tool.CellColor:=clTeeColor;
ButtonColor1.Invalidate;
end;
procedure TSurfaceNearest.FormShow(Sender: TObject);
Procedure FillSeries(AItems:TStrings);
var t : Integer;
begin
With Tool.ParentChart do
for t:=0 to SeriesCount-1 do
if Series[t] is TSurfaceSeries then
AItems.AddObject(SeriesTitleOrName(Series[t]),Series[t]);
end;
begin
Tool:=TSurfaceNearestTool({$IFDEF CLR}TObject{$ENDIF}(Tag));
if Assigned(Tool) then
begin
FillSeries(CBSeries.Items);
CBSeries.Enabled:=Tool.ParentChart.SeriesCount>0;
CBSeries.ItemIndex:=CBSeries.Items.IndexOfObject(Tool.Series);
ButtonColor1.LinkProperty(Tool,'CellColor');
ButtonColor2.LinkProperty(Tool,'RowColor');
ButtonColor3.LinkProperty(Tool,'ColumnColor');
CheckBox1.Checked:=Tool.CellColor=clTeeColor;
CheckBox2.Checked:=Tool.RowColor=clTeeColor;
CheckBox3.Checked:=Tool.ColumnColor=clTeeColor;
CheckBox4.Checked:=Tool.CellColor=clNone;
CheckBox5.Checked:=Tool.RowColor=clNone;
CheckBox6.Checked:=Tool.ColumnColor=clNone;
end;
Label1.Caption:=TeeMsg_GallerySurface;
end;
procedure TSurfaceNearest.CheckBox2Click(Sender: TObject);
begin
Tool.RowColor:=clTeeColor;
ButtonColor2.Invalidate;
end;
procedure TSurfaceNearest.CheckBox3Click(Sender: TObject);
begin
Tool.ColumnColor:=clTeeColor;
ButtonColor3.Invalidate;
end;
procedure TSurfaceNearest.ButtonColor1Click(Sender: TObject);
begin
CheckBox1.Checked:=False;
end;
procedure TSurfaceNearest.ButtonColor2Click(Sender: TObject);
begin
CheckBox2.Checked:=False;
end;
procedure TSurfaceNearest.ButtonColor3Click(Sender: TObject);
begin
CheckBox3.Checked:=False;
end;
procedure TSurfaceNearest.CBSeriesChange(Sender: TObject);
begin
if CBSeries.ItemIndex=-1 then
Tool.Series:=nil
else
Tool.Series:=TChartSeries(CBSeries.Items.Objects[CBSeries.ItemIndex]);
end;
procedure TSurfaceNearest.CheckBox4Click(Sender: TObject);
begin
Tool.CellColor:=clNone;
end;
procedure TSurfaceNearest.CheckBox5Click(Sender: TObject);
begin
Tool.RowColor:=clNone;
end;
procedure TSurfaceNearest.CheckBox6Click(Sender: TObject);
begin
Tool.ColumnColor:=clNone;
end;
initialization
RegisterClass(TSurfaceNearest);
RegisterTeeTools([TSurfaceNearestTool]);
finalization
UnRegisterTeeTools([TSurfaceNearestTool]);
end.
|
unit UFRMWalletKeys;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{ Copyright (c) 2016 by Albert Molina
Distributed under the MIT software license, see the accompanying file LICENSE
or visit http://www.opensource.org/licenses/mit-license.php.
This unit is a part of Pascal Coin, a P2P crypto currency without need of
historical operations.
If you like it, consider a donation using BitCoin:
16K3HCZRhFUtM8GdWRcfKeaa6KsuyxZaYk
}
interface
uses
Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, UWalletKeys, Buttons,
{$IFDEF FPC}LMessages, {$ENDIF}
clipbrd, UConst;
Const
CM_PC_WalletKeysChanged = {$IFDEF FPC}LM_USER{$ELSE}WM_USER{$ENDIF} + 1;
type
TFRMWalletKeys = class(TForm)
lbWalletKeys: TListBox;
bbExportPrivateKey: TBitBtn;
lblEncryptionTypeCaption: TLabel;
lblEncryptionType: TLabel;
lblKeyNameCaption: TLabel;
lblKeyName: TLabel;
lblPrivateKeyCaption: TLabel;
memoPrivateKey: TMemo;
bbChangeName: TBitBtn;
bbImportPrivateKey: TBitBtn;
bbExportPublicKey: TBitBtn;
bbImportPublicKey: TBitBtn;
bbGenerateNewKey: TBitBtn;
lblPrivateKeyCaption2: TLabel;
bbDelete: TBitBtn;
lblKeysEncrypted: TLabel;
bbUpdatePassword: TBitBtn;
bbExportAllWalletKeys: TBitBtn;
SaveDialog: TSaveDialog;
bbImportKeysFile: TBitBtn;
OpenDialog: TOpenDialog;
bbLock: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure bbChangeNameClick(Sender: TObject);
procedure bbExportPrivateKeyClick(Sender: TObject);
procedure bbImportPrivateKeyClick(Sender: TObject);
procedure lbWalletKeysClick(Sender: TObject);
procedure bbGenerateNewKeyClick(Sender: TObject);
procedure bbExportPublicKeyClick(Sender: TObject);
procedure bbDeleteClick(Sender: TObject);
procedure bbImportPublicKeyClick(Sender: TObject);
procedure bbUpdatePasswordClick(Sender: TObject);
procedure bbExportAllWalletKeysClick(Sender: TObject);
procedure bbImportKeysFileClick(Sender: TObject);
procedure bbLockClick(Sender: TObject);
private
FOldOnChanged: TNotifyEvent;
FWalletKeys: TWalletKeys;
procedure SetWalletKeys(const Value: TWalletKeys);
procedure OnWalletKeysChanged(Sender: TObject);
{ Private declarations }
Procedure UpdateWalletKeys;
Procedure UpdateSelectedWalletKey;
Function GetSelectedWalletKey(var WalletKey: TWalletKey): Boolean;
Function GetSelectedWalletKeyAndIndex(var WalletKey: TWalletKey; var index: Integer): Boolean;
Procedure CheckIsWalletKeyValidPassword;
procedure CM_WalletChanged(var Msg: TMessage); message CM_PC_WalletKeysChanged;
public
{ Public declarations }
Property WalletKeys: TWalletKeys read FWalletKeys write SetWalletKeys;
Destructor Destroy; override;
end;
implementation
uses
{$IFNDEF FPC}
Windows,
{$ELSE}
LCLIntf, LCLType,
{$ENDIF}
UCrypto, UAccounts, UFRMNewPrivateKeyType, UAES;
{$IFNDEF FPC}
{$R *.dfm}
{$ELSE}
{$R *.lfm}
{$ENDIF}
{ TFRMWalletKeys }
procedure TFRMWalletKeys.bbChangeNameClick(Sender: TObject);
Var
wk: TWalletKey;
s: String;
index: Integer;
begin
if not GetSelectedWalletKeyAndIndex(wk, index) then
exit;
s := wk.Name;
if InputQuery('Change name', 'Input new key name:', s) then
begin
WalletKeys.SetName(index, s);
UpdateWalletKeys;
end;
end;
procedure TFRMWalletKeys.bbDeleteClick(Sender: TObject);
Var
wk: TWalletKey;
index: Integer;
s: String;
begin
if Not GetSelectedWalletKeyAndIndex(wk, index) then
exit;
s := 'Are you sure you want to delete the selected private key?' + #10 + wk.Name + #10 + #10 +
'Please note that this will forever remove access to accounts using this key...';
if Application.MessageBox(Pchar(s), Pchar('Delete key'), MB_YESNO + MB_DEFBUTTON2 + MB_ICONWARNING) <> Idyes then
exit;
if Application.MessageBox(Pchar('Are you sure you want to delete?'), Pchar('Delete key'), MB_YESNO + MB_DEFBUTTON2 + MB_ICONWARNING) <> Idyes then
exit;
WalletKeys.Delete(index);
UpdateWalletKeys;
end;
procedure TFRMWalletKeys.bbExportAllWalletKeysClick(Sender: TObject);
Var
efn: String;
fs: TFileStream;
begin
if WalletKeys.Count <= 0 then
raise Exception.Create('Your wallet is empty. No keys!');
if ((WalletKeys.IsValidPassword) And (WalletKeys.WalletPassword = '')) then
begin
if Application.MessageBox(Pchar('Your wallet has NO PASSWORD' + #10 + #10 +
'It is recommend to protect your wallet with a password prior to exporting it!' + #10 + #10 + 'Continue without password protection?'),
Pchar(Application.Title), MB_YESNO + MB_ICONWARNING + MB_DEFBUTTON2) <> Idyes then
exit;
end;
if Not SaveDialog.Execute then
exit;
efn := SaveDialog.FileName;
if FileExists(efn) then
begin
if Application.MessageBox(Pchar('This file exists:' + #10 + efn + #10#10 + 'Overwrite?'), Pchar(Application.Title),
MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON2) <> Idyes then
exit;
end;
fs := TFileStream.Create(efn, fmCreate);
try
fs.Size := 0;
WalletKeys.SaveToStream(fs);
finally
fs.Free;
end;
Application.MessageBox(Pchar('Wallet key exported to a file:' + #10 + efn), Pchar(Application.Title), MB_OK + MB_ICONINFORMATION);
end;
procedure TFRMWalletKeys.bbExportPrivateKeyClick(Sender: TObject);
Var
wk: TWalletKey;
pwd1, pwd2, enc: String;
begin
CheckIsWalletKeyValidPassword;
if Not GetSelectedWalletKey(wk) then
exit;
if Assigned(wk.PrivateKey) then
begin
if InputQuery('Export private key', 'Insert a password to export', pwd1) then
begin
if InputQuery('Export private key', 'Repeat the password to export', pwd2) then
begin
if pwd1 <> pwd2 then
raise Exception.Create('Passwords does not match!');
enc := TCrypto.ToHexaString(TAESComp.EVP_Encrypt_AES256(wk.PrivateKey.ExportToRaw, pwd1));
Clipboard.AsText := enc;
Application.MessageBox(Pchar('The password has been encrypted with your password and copied to the clipboard.' + #10 + #10 + 'Password: "' +
pwd1 + '"' + #10 + #10 + 'Encrypted key value (Copied to the clipboard):' + #10 + enc + #10 + #10 + 'Length=' + Inttostr(length(enc)) +
' bytes'), Pchar(Application.Title), MB_OK + MB_ICONINFORMATION);
end
else
raise Exception.Create('Cancelled operation');
end;
end;
end;
procedure TFRMWalletKeys.bbExportPublicKeyClick(Sender: TObject);
Var
wk: TWalletKey;
s: String;
begin
CheckIsWalletKeyValidPassword;
if Not GetSelectedWalletKey(wk) then
exit;
s := TAccountComp.AccountPublicKeyExport(wk.AccountKey);
Clipboard.AsText := s;
Application.MessageBox(Pchar('The public key has been copied to the clipboard' + #10 + #10 + 'Public key value:' + #10 + s + #10 + #10 + 'Length=' +
Inttostr(length(s)) + ' bytes'), Pchar(Application.Title), MB_OK + MB_ICONINFORMATION);
end;
procedure TFRMWalletKeys.bbGenerateNewKeyClick(Sender: TObject);
Var
FRM: TFRMNewPrivateKeyType;
begin
CheckIsWalletKeyValidPassword;
FRM := TFRMNewPrivateKeyType.Create(Self);
try
FRM.WalletKeys := WalletKeys;
FRM.ShowModal;
UpdateWalletKeys;
finally
FRM.Free;
end;
end;
procedure TFRMWalletKeys.bbImportKeysFileClick(Sender: TObject);
Var
wki: TWalletKeys;
ifn, pwd: String;
i: Integer;
cPrivatekeys, cPublicKeys: Integer;
begin
if Not OpenDialog.Execute then
exit;
ifn := OpenDialog.FileName;
if Not FileExists(ifn) then
raise Exception.Create('Cannot find file ' + ifn);
wki := TWalletKeys.Create(Self);
try
wki.WalletFileName := ifn;
if wki.Count <= 0 then
raise Exception.Create('Wallet file has no valid data');
pwd := '';
While (Not wki.IsValidPassword) do
begin
if Not InputQuery('Import', 'Enter the wallet file password:', pwd) then
exit;
wki.WalletPassword := pwd;
if not wki.IsValidPassword then
begin
If Application.MessageBox(Pchar('Password entered is not valid, retry?'), Pchar(Application.Title), MB_ICONERROR + MB_YESNO) <> Idyes then
exit;
end;
end;
cPrivatekeys := 0;
cPublicKeys := 0;
if wki.IsValidPassword then
begin
for i := 0 to wki.Count - 1 do
begin
if WalletKeys.IndexOfAccountKey(wki.Key[i].AccountKey) < 0 then
begin
If Assigned(wki.Key[i].PrivateKey) then
begin
WalletKeys.AddPrivateKey(wki.Key[i].Name, wki.Key[i].PrivateKey);
inc(cPrivatekeys);
end
else
begin
WalletKeys.AddPublicKey(wki.Key[i].Name, wki.Key[i].AccountKey);
inc(cPublicKeys);
end;
end;
end;
end;
if (cPrivatekeys > 0) Or (cPublicKeys > 0) then
begin
Application.MessageBox(Pchar('Wallet file imported successfully' + #10 + #10 + 'File:' + ifn + #10 + #10 + 'Total keys in wallet: ' +
Inttostr(wki.Count) + #10 + 'Imported private keys: ' + Inttostr(cPrivatekeys) + #10 + 'Imported public keys only: ' + Inttostr(cPublicKeys) + #10
+ 'Duplicated (not imported): ' + Inttostr(wki.Count - cPrivatekeys - cPublicKeys)), Pchar(Application.Title), MB_OK + MB_ICONINFORMATION);
end
else
begin
Application.MessageBox(Pchar('Wallet file keys were already in your wallet. Nothing imported' + #10 + #10 + 'File:' + ifn + #10 + #10 +
'Total keys in wallet: ' + Inttostr(wki.Count)), Pchar(Application.Title), MB_OK + MB_ICONWARNING);
end;
finally
wki.Free;
end;
end;
procedure TFRMWalletKeys.bbImportPrivateKeyClick(Sender: TObject);
var
s: String;
desenc, enc: AnsiString;
EC: TECPrivateKey;
i: Integer;
wk: TWalletKey;
parseResult: Boolean;
function ParseRawKey(EC_OpenSSL_NID: Word): Boolean;
begin
FreeAndNil(EC);
ParseRawKey := False;
EC := TECPrivateKey.Create;
Try
EC.SetPrivateKeyFromHexa(EC_OpenSSL_NID, TCrypto.ToHexaString(enc));
ParseRawKey := True;
Except
On E: Exception do
begin
FreeAndNil(EC);
Raise;
end;
end;
end;
function ParseEncryptedKey: Boolean;
begin
Repeat
s := '';
desenc := '';
if InputQuery('Import private key', 'Enter the password:', s) then
begin
If (TAESComp.EVP_Decrypt_AES256(enc, s, desenc)) then
begin
if (desenc <> '') then
begin
EC := TECPrivateKey.ImportFromRaw(desenc);
ParseEncryptedKey := True;
exit;
end
else
begin
if Application.MessageBox(Pchar('Invalid password!'), '', MB_RETRYCANCEL + MB_ICONERROR) <> IDRETRY then
begin
ParseEncryptedKey := False;
exit;
end;
desenc := '';
end;
end
else
begin
if Application.MessageBox(Pchar('Invalid password or corrupted data!'), '', MB_RETRYCANCEL + MB_ICONERROR) <> IDRETRY then
begin
ParseEncryptedKey := False;
exit;
end;
end;
end
else
begin
ParseEncryptedKey := False;
exit;
end;
Until (desenc <> '');
end;
begin
EC := Nil;
CheckIsWalletKeyValidPassword;
if Not Assigned(WalletKeys) then
exit;
if InputQuery('Import private key', 'Insert the password protected private key or raw private key', s) then
begin
s := trim(s);
if (s = '') then
raise Exception.Create('No valid key');
enc := TCrypto.HexaToRaw(s);
if (enc = '') then
raise Exception.Create('Invalid text... You must enter an hexadecimal value ("0".."9" or "A".."F")');
case length(enc) of
32:
parseResult := ParseRawKey(CT_NID_secp256k1);
35, 36:
parseResult := ParseRawKey(CT_NID_sect283k1);
48:
parseResult := ParseRawKey(CT_NID_secp384r1);
65, 66:
parseResult := ParseRawKey(CT_NID_secp521r1);
64, 80, 96:
parseResult := ParseEncryptedKey;
else
Exception.Create('Invalidly formatted private key string. Ensure it is an encrypted private key export or raw private key hexstring.');
end;
if (parseResult = False) then
exit;
Try
// EC is assigned by ParseRawKey/ImportEncryptedKey
if Not Assigned(EC) then
begin
Application.MessageBox(Pchar('Invalid password and/or corrupted data!'), '', MB_OK);
exit;
end;
i := WalletKeys.IndexOfAccountKey(EC.PublicKey);
if (i >= 0) then
begin
wk := WalletKeys.Key[i];
if Assigned(wk.PrivateKey) And (Assigned(wk.PrivateKey.PrivateKey)) then
raise Exception.Create('This key is already in your wallet!');
end;
s := 'Imported ' + DateTimeToStr(now);
s := InputBox('Set a name', 'Name for this private key:', s);
i := WalletKeys.AddPrivateKey(s, EC);
Application.MessageBox(Pchar('Imported private key'), Pchar(Application.Title), MB_OK + MB_ICONINFORMATION);
Finally
EC.Free;
End;
UpdateWalletKeys;
end;
end;
procedure TFRMWalletKeys.bbImportPublicKeyClick(Sender: TObject);
var
s: String;
raw: AnsiString;
EC: TECPrivateKey;
account: TAccountKey;
errors: AnsiString;
begin
CheckIsWalletKeyValidPassword;
if Not Assigned(WalletKeys) then
exit;
if Not InputQuery('Import publick key', 'Insert the public key in hexa format or imported format', s) then
exit;
If not TAccountComp.AccountPublicKeyImport(s, account, errors) then
begin
raw := TCrypto.HexaToRaw(s);
if trim(raw) = '' then
raise Exception.Create('Invalid public key value (Not hexa or not an imported format)' + #10 + errors);
account := TAccountComp.RawString2Accountkey(raw);
end;
If not TAccountComp.IsValidAccountKey(account, errors) then
raise Exception.Create('This data is not a valid public key' + #10 + errors);
if WalletKeys.IndexOfAccountKey(account) >= 0 then
raise Exception.Create('This key exists on your wallet');
s := 'Imported public key ' + DateTimeToStr(now);
if InputQuery('Set a name', 'Name for this private key:', s) then
begin
WalletKeys.AddPublicKey(s, account);
UpdateWalletKeys;
Application.MessageBox(Pchar('Imported public key'), Pchar(Application.Title), MB_OK + MB_ICONINFORMATION);
end;
end;
procedure TFRMWalletKeys.bbLockClick(Sender: TObject);
begin
FWalletKeys.LockWallet;
end;
procedure TFRMWalletKeys.bbUpdatePasswordClick(Sender: TObject);
Var
s, s2: String;
begin
if FWalletKeys.IsValidPassword then
begin
s := '';
s2 := '';
if Not InputQuery('Change password', 'Enter new password', s) then
exit;
if trim(s) <> s then
raise Exception.Create('Password cannot start or end with a space character');
if Not InputQuery('Change password', 'Enter new password again', s2) then
exit;
if s <> s2 then
raise Exception.Create('Two passwords are different!');
FWalletKeys.WalletPassword := s;
Application.MessageBox(Pchar('Password changed!' + #10 + #10 + 'Please note that your new password is "' + s + '"' + #10 + #10 +
'(If you lose this password, you will lose your wallet forever!)'), Pchar(Application.Title), MB_ICONWARNING + MB_OK);
UpdateWalletKeys;
end
else
begin
s := '';
Repeat
if Not InputQuery('Wallet password', 'Enter wallet password', s) then
exit;
FWalletKeys.WalletPassword := s;
if Not FWalletKeys.IsValidPassword then
Application.MessageBox(Pchar('Invalid password'), Pchar(Application.Title), MB_ICONERROR + MB_OK);
Until FWalletKeys.IsValidPassword;
UpdateWalletKeys;
end;
end;
procedure TFRMWalletKeys.CheckIsWalletKeyValidPassword;
begin
if Not Assigned(FWalletKeys) then
exit;
if Not FWalletKeys.IsValidPassword then
begin
Application.MessageBox(Pchar('Wallet key is encrypted!' + #10 + #10 + 'You must enter password to continue...'), Pchar(Application.Title),
MB_OK + MB_ICONWARNING);
bbUpdatePasswordClick(Nil);
if Not FWalletKeys.IsValidPassword then
raise Exception.Create('Cannot continue without valid password');
end;
end;
procedure TFRMWalletKeys.CM_WalletChanged(var Msg: TMessage);
begin
UpdateWalletKeys;
end;
destructor TFRMWalletKeys.Destroy;
begin
if Assigned(FWalletKeys) then
FWalletKeys.OnChanged := FOldOnChanged;
inherited;
end;
procedure TFRMWalletKeys.FormCreate(Sender: TObject);
begin
lbWalletKeys.Sorted := True;
FWalletKeys := Nil;
UpdateWalletKeys;
end;
function TFRMWalletKeys.GetSelectedWalletKey(var WalletKey: TWalletKey): Boolean;
Var
i: Integer;
begin
Result := GetSelectedWalletKeyAndIndex(WalletKey, i);
end;
function TFRMWalletKeys.GetSelectedWalletKeyAndIndex(var WalletKey: TWalletKey; var index: Integer): Boolean;
begin
index := -1;
Result := False;
if Not Assigned(WalletKeys) then
exit;
if lbWalletKeys.ItemIndex < 0 then
exit;
index := Integer(lbWalletKeys.Items.Objects[lbWalletKeys.ItemIndex]);
if (index >= 0) And (index < WalletKeys.Count) then
begin
WalletKey := WalletKeys.Key[index];
Result := True;
end;
end;
procedure TFRMWalletKeys.lbWalletKeysClick(Sender: TObject);
begin
UpdateSelectedWalletKey;
end;
procedure TFRMWalletKeys.OnWalletKeysChanged(Sender: TObject);
begin
PostMessage(Self.Handle, CM_PC_WalletKeysChanged, 0, 0);
if Assigned(FOldOnChanged) then
FOldOnChanged(Sender);
end;
procedure TFRMWalletKeys.SetWalletKeys(const Value: TWalletKeys);
begin
if FWalletKeys = Value then
exit;
if Assigned(FWalletKeys) then
FWalletKeys.OnChanged := FOldOnChanged;
FWalletKeys := Value;
if Assigned(FWalletKeys) then
begin
FOldOnChanged := FWalletKeys.OnChanged;
FWalletKeys.OnChanged := OnWalletKeysChanged;
end;
UpdateWalletKeys;
end;
procedure TFRMWalletKeys.UpdateSelectedWalletKey;
Var
wk: TWalletKey;
ok: Boolean;
begin
ok := False;
wk := CT_TWalletKey_NUL;
try
if Not GetSelectedWalletKey(wk) then
exit;
ok := True;
lblEncryptionType.Caption := TAccountComp.GetECInfoTxt(wk.AccountKey.EC_OpenSSL_NID);
if wk.Name = '' then
lblKeyName.Caption := '(No name)'
else
lblKeyName.Caption := wk.Name;
if Assigned(wk.PrivateKey) then
begin
memoPrivateKey.Lines.Text := TCrypto.PrivateKey2Hexa(wk.PrivateKey.PrivateKey);
memoPrivateKey.Font.Color := clBlack;
end
else
begin
memoPrivateKey.Lines.Text := '(No private key)';
memoPrivateKey.Font.Color := clRed;
end;
finally
lblEncryptionTypeCaption.Enabled := ok;
lblEncryptionType.Enabled := ok;
lblKeyNameCaption.Enabled := ok;
lblKeyName.Enabled := (ok) And (wk.Name <> '');
lblPrivateKeyCaption.Enabled := ok;
memoPrivateKey.Enabled := ok;
bbExportPrivateKey.Enabled := ok;
bbExportPublicKey.Enabled := ok;
bbChangeName.Enabled := ok;
lblPrivateKeyCaption2.Enabled := ok;
bbDelete.Enabled := ok;
if not ok then
begin
lblEncryptionType.Caption := '';
lblKeyName.Caption := '';
memoPrivateKey.Lines.Clear;
end;
end;
end;
procedure TFRMWalletKeys.UpdateWalletKeys;
Var
lasti, i: Integer;
selected_wk, wk: TWalletKey;
s: AnsiString;
begin
GetSelectedWalletKeyAndIndex(wk, lasti);
lbWalletKeys.Items.BeginUpdate;
Try
lbWalletKeys.Items.Clear;
lblKeysEncrypted.Caption := '';
if not Assigned(FWalletKeys) then
exit;
bbLock.Enabled := (FWalletKeys.IsValidPassword) And (FWalletKeys.WalletPassword <> '');
If FWalletKeys.IsValidPassword then
begin
if FWalletKeys.WalletPassword = '' then
lblKeysEncrypted.Caption := 'Wallet without password'
else
lblKeysEncrypted.Caption := 'Wallet is password protected';
lblKeysEncrypted.Font.Color := clGreen;
bbUpdatePassword.Caption := 'Change password';
end
else
begin
lblKeysEncrypted.Caption := 'Wallet is encrypted... need password!';
lblKeysEncrypted.Font.Color := clRed;
bbUpdatePassword.Caption := 'Input password';
end;
for i := 0 to WalletKeys.Count - 1 do
begin
wk := WalletKeys.Key[i];
if (wk.Name = '') then
begin
s := 'Sha256=' + TCrypto.ToHexaString(TCrypto.DoSha256(TAccountComp.AccountKey2RawString(wk.AccountKey)));
end
else
begin
s := wk.Name;
end;
if Not Assigned(wk.PrivateKey) then
begin
if wk.CryptedKey <> '' then
s := s + ' (Encrypted, need password)';
s := s + ' (* without key)';
end;
lbWalletKeys.Items.AddObject(s, TObject(i));
end;
i := lbWalletKeys.Items.IndexOfObject(TObject(lasti));
lbWalletKeys.ItemIndex := i;
Finally
lbWalletKeys.Items.EndUpdate;
End;
UpdateSelectedWalletKey;
end;
end.
|
unit IdSocks;
interface
uses
Classes,
IdStack;
type
TIdSocksRequest = record
Version: Byte;
OpCode: Byte;
Port: Word;
IpAddr: TIdInAddr;
UserId: string[255];
end;
TIdSocksResponse = record
Version: Byte;
OpCode: Byte;
Port: Word;
IpAddr: TIdInAddr;
end;
TSocksVersion = (svNoSocks, svSocks4, svSocks4A, svSocks5);
TSocksAuthentication = (saNoAuthentication, saUsernamePassword);
const
ID_SOCKS_AUTH = saNoAuthentication;
ID_SOCKS_VER = svNoSocks;
ID_SOCKS_PORT = 0;
type
TSocksInfo = class(TPersistent)
protected
FAuthentication: TSocksAuthentication;
FHost: string;
FPassword: string;
FPort: Integer;
FUserID: string;
FVersion: TSocksVersion;
public
constructor Create;
procedure Assign(Source: TPersistent); override;
published
property Authentication: TSocksAuthentication read FAuthentication write
FAuthentication default ID_SOCKS_AUTH;
property Host: string read FHost write FHost;
property Password: string read FPassword write FPassword;
property Port: Integer read FPort write FPort default ID_SOCKS_PORT;
property UserID: string read FUserID write FUserID;
property Version: TSocksVersion read FVersion write FVersion default
ID_SOCKS_VER;
end;
implementation
{ TSocksInfo }
procedure TSocksInfo.Assign(Source: TPersistent);
begin
if Source is TSocksInfo then
with Source as TSocksInfo do
begin
Self.Authentication := Authentication;
Self.Host := Host;
Self.Password := Password;
Self.Port := Port;
Self.UserID := UserID;
Self.Version := Version;
end
else
inherited;
end;
constructor TSocksInfo.Create;
begin
inherited;
Authentication := ID_SOCKS_AUTH;
Version := ID_SOCKS_VER;
Port := ID_SOCKS_PORT;
end;
end.
|
unit adot.Grammar;
{ Uniform grammar presentation classes/record types }
interface
uses
adot.Types,
adot.Collections,
adot.Collections.Vectors,
adot.Collections.Sets,
adot.Tools,
adot.Tools.IO,
adot.Strings,
adot.Grammar.Types,
adot.Tools.RTTI,
System.Generics.Collections,
System.Generics.Defaults,
System.SysUtils,
System.Character,
System.StrUtils,
System.Math;
type
{ Record type for grammar definition. Construct grammar rules with help of Ex/Rep functions:
var
Number,Digit: TGrammar;
begin
Number := Ex(Digit) + Ex(Digit)*Rep;
Digit := Ex('1') or Ex('2');
end; }
PGrammar = ^TGrammar;
TGrammar = record
public
type
{# repeater range (range of allowed repetitions for expression) }
TRange = record
MinCount, MaxCount: integer;
end;
{# Delphi doesn't provide any way to catch copy operator, we introduce separate
type for all expression operations (right side of assigment) and Implicit operator
to proceed assigment to TGrammar correctly. }
TMedia = record
private
MediaGrm: IInterfacedObject<TGrammarClass>;
public
{ Repeater: B*, A+, A[2;5] }
class operator Multiply(A: TMedia; const R: TRange): TMedia;
{ Sequence: A "abc" B}
class operator Add(A,B: TMedia): TMedia;
{ Selection: A | "abc" }
class operator LogicalOr(A,B: TMedia): TMedia;
{ Logical not: A + not "abc"}
class operator LogicalNot(A: TMedia): TMedia;
end;
var
Grm: IInterfacedObject<TGrammarClass>;
private
function GetId: int64;
function GetName: string;
procedure SetName(const Value: string);
function GetIncludeIntoParseTree: Boolean;
procedure SetIncludeIntoParseTree(const Value: Boolean);
public
class operator Implicit(A : TMedia) : TGrammar;
{ It is important to call Release for main rule (at least), because
grammar classes usually have lot of cross references and can not be automatically
destroyed when TGrammar records go out of scope. }
procedure Release;
{ expose some poperties from Grm.Data:TGrammarClass }
property Id: int64 read GetId;
property Name: string read GetName write SetName;
property IncludeIntoParseTree: Boolean read GetIncludeIntoParseTree write SetIncludeIntoParseTree;
end;
{ abstract class for expression with no operands (string, char, EOF etc) }
TGrammarClassOp0 = class abstract(TGrammarClass)
protected
procedure DoRelease; override;
public
procedure GetOperands(var Dst: TVector<IInterfacedObject<TGrammarClass>>); override;
end;
{ abstract class for expression with one operand (link, repeater, NOT etc) }
TGrammarClassOp1 = class abstract(TGrammarClass)
protected
FOp: IInterfacedObject<TGrammarClass>;
function GetInfo: string; override;
procedure DoRelease; override;
public
procedure GetOperands(var Dst: TVector<IInterfacedObject<TGrammarClass>>); override;
property Op: IInterfacedObject<TGrammarClass> read FOp;
end;
{ abstract class for expression with two operand (sequence, selection etc) }
TGrammarClassOp2 = class abstract(TGrammarClass)
protected
FOp1: IInterfacedObject<TGrammarClass>;
FOp2: IInterfacedObject<TGrammarClass>;
function GetInfo: string; override;
procedure DoRelease; override;
public
procedure GetOperands(var Dst: TVector<IInterfacedObject<TGrammarClass>>); override;
property Op1: IInterfacedObject<TGrammarClass> read FOp1;
property Op2: IInterfacedObject<TGrammarClass> read FOp2;
end;
{ When rule used link, we create TGrammarLink and initialize pointer FLink,
but Op=nil, because it can be not initialized yet. Later, when all rules
are initialized, SetMainRule will set Op. }
TGrammarLink = class(TGrammarClassOp1)
protected
FLink: PGrammar;
function GetInfo: string; override;
public
constructor Create(var ALink: TGrammar);
procedure SetupRule; override;
end;
TGrammarString = class(TGrammarClassOp0)
private
protected
FValue: String;
FCaseSensitive: boolean;
FSkipCaseCheck: boolean;
function GetInfo: string; override;
procedure SetCaseSensitive(const Value: boolean);
procedure SetValue(const Value: string);
procedure Update;
public
constructor Create(const Value: String; CaseSensitive: boolean);
{ input accepted: return length of accepted block
input rejected: -1}
function GetAcceptedBlock(var Buffer: TBuffer): integer;
property CaseSensitive: boolean read FCaseSensitive write SetCaseSensitive;
property Value: string read FValue write SetValue;
end;
TGrammarChar = class(TGrammarClassOp0)
private
protected
AFrom,ATo,BFrom,BTo: Char;
FValueFrom,FValueTo: Char;
FCaseSensitive: boolean;
procedure SetCaseSensitive(const Value: boolean);
procedure SetValueFrom(const Value: char);
procedure SetValueTo(const Value: char);
function GetInfo: string; override;
procedure Update;
public
constructor Create(ValueFrom,ValueTo: Char; CaseSensitive: boolean);
{ input accepted: return length of accepted block
input rejected: -1}
function GetAcceptedBlock(var Buffer: TBuffer): integer;
property CaseSensitive: boolean read FCaseSensitive write SetCaseSensitive;
property ValueFrom: char read FValueFrom write SetValueFrom;
property ValueTo: char read FValueTo write SetValueTo;
end;
TCharClass = (ccControl, ccDigit, ccLetter, ccLetterOrDigit, ccLower, ccPunctuation, ccSeparator, ccSymbol, ccUpper, ccWhiteSpace, ccAny);
TGrammarCharClass = class(TGrammarClassOp0)
protected
FCharClass: TCharClass;
function GetInfo: string; override;
public
constructor Create(ACharClass: TCharClass);
{ input accepted: return length of accepted block
input rejected: -1}
function GetAcceptedBlock(var Buffer: TBuffer): integer;
property CharClass: TCharClass read FCharClass write FCharClass;
end;
TGrammarCharSetClass = class(TGrammarClassOp0)
protected
function GetInfo: string; override;
public
CharSet: TSet<Char>;
constructor Create(const Chars: array of Char; CaseSensitive: boolean = False); overload;
constructor Create(Chars: TEnumerable<Char>; CaseSensitive: boolean = False); overload;
constructor Create(Chars: TSet<Char>; CaseSensitive: boolean = False); overload;
{ input accepted: return length of accepted block
input rejected: -1}
function GetAcceptedBlock(var Buffer: TBuffer): integer;
end;
TGrammarBytesClass = class(TGrammarClassOp0)
protected
function GetInfo: string; override;
public
Bytes: TArray<Byte>;
constructor Create(const ABytes: TArray<Byte>); overload;
constructor Create(const ABytes: array of Byte); overload;
constructor Create(ABytes: TEnumerable<Byte>); overload;
{ input accepted: return length of accepted block
input rejected: -1}
function GetAcceptedBlock(var Buffer: TBuffer): integer;
end;
TGrammarSequence = class(TGrammarClassOp2)
protected
public
constructor Create(AOp1, AOp2: IInterfacedObject<TGrammarClass>);
end;
TGrammarSelection = class(TGrammarClassOp2)
protected
public
constructor Create(AOp1, AOp2: IInterfacedObject<TGrammarClass>);
end;
TGrammarGreedyRepeater = class(TGrammarClassOp1)
protected
FMinCount, FMaxCount: integer;
function GetInfo: string; override;
public
constructor Create(AOp: IInterfacedObject<TGrammarClass>; AMinCount,AMaxCount: integer);
property MinCount: integer read FMinCount;
property MaxCount: integer read FMaxCount;
end;
TGrammarNot = class(TGrammarClassOp1)
protected
public
constructor Create(AOp: IInterfacedObject<TGrammarClass>);
end;
TGrammarEOF = class(TGrammarClassOp0)
protected
public
constructor Create;
end;
TCustomLanguage = class
protected
function Ex(var AGrammar: TGrammar): TGrammar.TMedia; overload; virtual;
function Ex(Value: String; CaseSensitive: boolean = False): TGrammar.TMedia; overload; virtual;
function Ex(CharRangeFrom,CharRangeTo: Char; CaseSensitive: boolean = False): TGrammar.TMedia; overload; virtual;
function Ex(ACharClass: TCharClass): TGrammar.TMedia; overload; virtual;
function Ex(const Chars: array of Char; CaseSensitive: boolean = False): TGrammar.TMedia; overload; virtual;
function Ex(Chars: TEnumerable<Char>; CaseSensitive: boolean = False): TGrammar.TMedia; overload; virtual;
function Ex(Chars: TSet<Char>; CaseSensitive: boolean = False): TGrammar.TMedia; overload; virtual;
function Ex(Value: TArray<Byte>): TGrammar.TMedia; overload; virtual;
function Ex(Value: TEnumerable<Byte>): TGrammar.TMedia; overload; virtual;
function EOF: TGrammar.TMedia; overload; virtual;
{ all possible repeaters for TGrammar (used as multiplyer of expression in right side of rule definiton) }
function Rep(AMinCount,AMaxCount: integer): TGrammar.TRange; overload; virtual;
function Rep(AExactCount: integer): TGrammar.TRange; overload; virtual;
function Rep: TGrammar.TRange; overload; virtual;
function Rep1: TGrammar.TRange; overload; virtual;
function Opt: TGrammar.TRange; overload; virtual;
{ optional - set readable names for grammar rules }
procedure SetNames(const Rules: array of TGrammar; const Names: array of string); virtual;
{ Should be called after initialization of all rules, but before main rule will be used.
Fixes internal links etc. }
procedure SetMainRule(var Rule: TGrammar); virtual;
end;
TCustomTextLang = class abstract(TCustomLanguage)
protected
WS: TGrammar;
public
constructor Create;
{ Short notation for text expressions with optional leading whitespaces:
tex(A)
or
(Ex(WS)*Rep + Ex(A))
}
function tEx(var AGrammar: TGrammar): TGrammar.TMedia; overload; virtual;
function tEx(Value: String; CaseSensitive: boolean = False): TGrammar.TMedia; overload; virtual;
function tEx(CharRangeFrom,CharRangeTo: Char; CaseSensitive: boolean = False): TGrammar.TMedia; overload; virtual;
function tEx(ACharClass: TCharClass): TGrammar.TMedia; overload; virtual;
function tEx(const Chars: array of Char; CaseSensitive: boolean = False): TGrammar.TMedia; overload; virtual;
function tEx(Chars: TEnumerable<Char>; CaseSensitive: boolean = False): TGrammar.TMedia; overload; virtual;
function tEx(Chars: TSet<Char>; CaseSensitive: boolean = False): TGrammar.TMedia; overload; virtual;
end;
implementation
{ TGrammar }
function TGrammar.GetId: int64;
begin
result := Grm.Data.Id;
end;
function TGrammar.GetIncludeIntoParseTree: Boolean;
begin
result := Grm.Data.IncludeIntoParseTree;
end;
procedure TGrammar.SetIncludeIntoParseTree(const Value: Boolean);
begin
Grm.Data.IncludeIntoParseTree := Value;
end;
function TGrammar.GetName: string;
begin
result := Grm.Data.Name;
end;
procedure TGrammar.SetName(const Value: string);
begin
Grm.Data.Name := Value;
end;
class operator TGrammar.Implicit(A: TMedia): TGrammar;
begin
Result.Grm := A.MediaGrm;
A.MediaGrm.Data.IncludeIntoParseTree := True;
end;
procedure TGrammar.Release;
begin
if Grm<>nil then
Grm.Data.Release;
end;
{ TMedia }
class operator TGrammar.TMedia.Add(A, B: TMedia): TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarSequence.Create(A.MediaGrm, B.MediaGrm));
end;
class operator TGrammar.TMedia.LogicalNot(A: TMedia): TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarNot.Create(A.MediaGrm));
end;
class operator TGrammar.TMedia.LogicalOr(A, B: TMedia): TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarSelection.Create(A.MediaGrm, B.MediaGrm));
end;
class operator TGrammar.TMedia.Multiply(A: TMedia; const R: TRange): TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarGreedyRepeater.Create(A.MediaGrm, R.MinCount,R.MaxCount));
end;
{ TGrammarClass }
{ TGrammarClassOp0 }
procedure TGrammarClassOp0.GetOperands(var Dst: TVector<IInterfacedObject<TGrammarClass>>);
begin
{ nothing to do here }
end;
procedure TGrammarClassOp0.DoRelease;
begin
{ nothing to do here }
end;
{ TGrammarClassOp1 }
function TGrammarClassOp1.GetInfo: string;
begin
result := inherited + ' ' + GetOperandInfo(FOp);
end;
procedure TGrammarClassOp1.GetOperands(var Dst: TVector<IInterfacedObject<TGrammarClass>>);
begin
if FOp<>nil then
Dst.Add(FOp);
end;
procedure TGrammarClassOp1.DoRelease;
begin
FOp := nil;
end;
{ TGrammarClassOp2 }
function TGrammarClassOp2.GetInfo: string;
begin
result := inherited + ' ' + GetOperandInfo(FOp1) + ' ' + GetOperandInfo(FOp2);
end;
procedure TGrammarClassOp2.GetOperands(var Dst: TVector<IInterfacedObject<TGrammarClass>>);
begin
if FOp1<>nil then
Dst.Add(FOp1);
if FOp2<>nil then
Dst.Add(FOp2);
end;
procedure TGrammarClassOp2.DoRelease;
begin
FOp1 := nil;
FOp2 := nil;
end;
{ TGrammarLink }
constructor TGrammarLink.Create(var ALink: TGrammar);
begin
inherited Create(gtLink);
FLink := @ALink;
end;
function TGrammarLink.GetInfo: string;
begin
result := inherited + ' linked:' + FOp.Data.Info;
end;
procedure TGrammarLink.SetupRule;
begin
inherited;
Assert(FLink.Grm<>nil, 'link is not initialized');
if FOp=nil then
FOp := FLink.Grm;
end;
{ TGrammarString }
constructor TGrammarString.Create(const Value: String; CaseSensitive: boolean);
begin
inherited Create(gtString);
FValue := Value;
FCaseSensitive := CaseSensitive;
Update;
end;
function TGrammarString.GetAcceptedBlock(var Buffer: TBuffer): integer;
begin
{ empty string is always matched }
if Value='' then
Exit(0);
{ not enough of data to match }
Result := Length(Value)*SizeOf(Char);
if Buffer.Left < Result then
Exit(-1);
{ we have enough of data, it is safe to compare }
if FSkipCaseCheck then
{$IF Defined(MSWindows)}
if not CompareMem(Pointer(Value), Buffer.CurrentData, result) then
{$ELSE}
if not CompareMem(@Value[Low(Value)], Buffer.CurrentData, result) then
{$ENDIF}
result := -1
else
else
if not TStr.SameText(@Value[Low(Value)], Buffer.CurrentData, Length(Value)) then
result := -1;
end;
function BoolToStr(Value: boolean): string;
begin
if Value then result := 'True'
else result := 'False';
end;
function TGrammarString.GetInfo: string;
begin
result := inherited + Format(' Value:"%s", CaseSensitive:%s', [TEnc.GetPrintable(FValue), BoolToStr(FCaseSensitive)]);
end;
procedure TGrammarString.SetCaseSensitive(const Value: boolean);
begin
FCaseSensitive := Value;
Update;
end;
procedure TGrammarString.SetValue(const Value: string);
begin
FValue := Value;
Update;
end;
procedure TGrammarString.Update;
begin
{ we try to use case sensitive check when possible (faster). }
FSkipCaseCheck := FCaseSensitive or (TStr.LowerCase(FValue)=TStr.UpperCase(FValue));
end;
{ TGrammarChar }
constructor TGrammarChar.Create(ValueFrom, ValueTo: Char; CaseSensitive: boolean);
begin
inherited Create(gtChar);
FValueFrom := ValueFrom;
FValueTo := ValueTo;
FCaseSensitive := CaseSensitive;
Update;
end;
function TGrammarChar.GetAcceptedBlock(var Buffer: TBuffer): integer;
var
C: Char;
begin
{ not enough of data to match }
if Buffer.Left < SizeOf(Char) then
Exit(-1);
C := Char(Buffer.CurrentData^);
if (C >= AFrom) and (C <= ATo) or (C >= BFrom) and (C <= BTo) then
result := SizeOF(Char)
else
result := -1;
end;
function TGrammarChar.GetInfo: string;
begin
result := inherited + Format(' Value:"%s", CaseSensitive:%s', [
TEnc.GetPrintable(IfThen(FValueFrom=FValueTo, FValueFrom, '['+FValueFrom+'..'+FValueFrom+']')),
BoolToStr(FCaseSensitive)
]);
end;
procedure TGrammarChar.SetCaseSensitive(const Value: boolean);
begin
FCaseSensitive := Value;
Update;
end;
procedure TGrammarChar.SetValueFrom(const Value: char);
begin
FValueFrom := Value;
Update;
end;
procedure TGrammarChar.SetValueTo(const Value: char);
begin
FValueTo := Value;
Update;
end;
procedure TGrammarChar.Update;
begin
if FCaseSensitive then
begin
AFrom := FValueFrom;
ATo := FValueTo;
BFrom := AFrom;
BTo := ATo;
end
else
begin
AFrom := TStr.LowerCaseChar(FValueFrom);
ATo := TStr.LowerCaseChar(FValueTo);
BFrom := TStr.UpperCaseChar(FValueFrom);
BTo := TStr.UpperCaseChar(FValueTo);
end
end;
{ TGrammarCharClass }
constructor TGrammarCharClass.Create(ACharClass: TCharClass);
begin
inherited Create(gtCharClass);
FCharClass := ACharClass;
end;
function TGrammarCharClass.GetAcceptedBlock(var Buffer: TBuffer): integer;
var
C: Char;
begin
{ not enough of data to match }
if Buffer.Left < SizeOf(Char) then
Exit(-1);
C := Char(Buffer.CurrentData^);
case FCharClass of
ccControl : if C.IsControl then result := SizeOf(Char) else result := -1;
ccDigit : if C.IsDigit then result := SizeOf(Char) else result := -1;
ccLetter : if C.IsLetter then result := SizeOf(Char) else result := -1;
ccLetterOrDigit : if C.IsLetterOrDigit then result := SizeOf(Char) else result := -1;
ccLower : if C.IsLower then result := SizeOf(Char) else result := -1;
ccPunctuation : if C.IsPunctuation then result := SizeOf(Char) else result := -1;
ccSeparator : if C.IsSeparator then result := SizeOf(Char) else result := -1;
ccSymbol : if C.IsSymbol then result := SizeOf(Char) else result := -1;
ccUpper : if C.IsUpper then result := SizeOf(Char) else result := -1;
ccWhiteSpace : if C.IsWhiteSpace then result := SizeOf(Char) else result := -1;
ccAny : result := SizeOf(Char);
else result := -1;
end;
end;
function TGrammarCharClass.GetInfo: string;
begin
result := inherited + Format(' CharClass:"%s"', [TEnumeration<TCharClass>.ToString(FCharClass)]);
end;
{ TGrammarCharSetClass }
constructor TGrammarCharSetClass.Create(const Chars: array of Char; CaseSensitive: boolean);
var C: Char;
begin
inherited Create(gtCharSet);
CharSet.Init;
if CaseSensitive then
for C in Chars do
CharSet.Add(C)
else
for C in Chars do
begin
CharSet.Add(C.ToLower);
CharSet.Add(C.ToUpper);
end;
end;
constructor TGrammarCharSetClass.Create(Chars: TEnumerable<Char>; CaseSensitive: boolean);
var C: Char;
begin
inherited Create(gtCharSet);
CharSet.Init;
if CaseSensitive then
for C in Chars do
CharSet.Add(C)
else
for C in Chars do
begin
CharSet.Add(C.ToLower);
CharSet.Add(C.ToUpper);
end;
end;
constructor TGrammarCharSetClass.Create(Chars: TSet<Char>; CaseSensitive: boolean);
var C: Char;
begin
inherited Create(gtCharSet);
CharSet.Init;
if CaseSensitive then
for C in Chars do
CharSet.Add(C)
else
for C in Chars do
begin
CharSet.Add(C.ToLower);
CharSet.Add(C.ToUpper);
end;
end;
function TGrammarCharSetClass.GetAcceptedBlock(var Buffer: TBuffer): integer;
begin
if (Buffer.Left >= SizeOf(Char)) and (Char(Buffer.CurrentData^) in CharSet) then
Result := SizeOf(Char)
else
Result := -1;
end;
function TGrammarCharSetClass.GetInfo: string;
var
C: Char;
begin
result := '';
for C in CharSet do
if Length(Result)>=20 then begin
result := result + ',...';
break;
end else
if result='' then
result := '[' + C
else
result := result + ',' + C;
if result='' then result := '[]' else result := result + ']';
result := inherited + Format(' CharSet: %s', [TEnc.GetPrintable(result)]);
end;
{ TGrammarBytesClass }
constructor TGrammarBytesClass.Create(const ABytes: TArray<Byte>);
begin
inherited Create(gtBytes);
Bytes := ABytes;
end;
constructor TGrammarBytesClass.Create(const ABytes: array of Byte);
var
L: Integer;
begin
inherited Create(gtBytes);
L := Length(ABytes);
SetLength(Bytes, L);
System.Move(ABytes[Low(ABytes)], Bytes[0], L);
end;
constructor TGrammarBytesClass.Create(ABytes: TEnumerable<Byte>);
var
B: TBuffer;
I: Byte;
begin
B.Clear;
for I in ABytes do
B.Write(I, SizeOf(I));
B.TrimExcess;
Bytes := B.Data;
end;
function TGrammarBytesClass.GetAcceptedBlock(var Buffer: TBuffer): integer;
begin
Result := Length(Bytes);
if (Buffer.Left < Result) or not CompareMem(Buffer.CurrentData, @Bytes[0], Result) then
Result := -1;
end;
function TGrammarBytesClass.GetInfo: string;
var
N,L: integer;
begin
L := Length(Bytes);
N := Min(32, L);
if N=0 then result := '[]' else
result := '[' + THex.Encode(Bytes[0], N) + IfThen(N<L,'...','') + ']';
result := inherited + ' Bytes: ' + Result;
end;
{ TGrammarSequence }
constructor TGrammarSequence.Create(AOp1, AOp2: IInterfacedObject<TGrammarClass>);
begin
inherited Create(gtSequence);
FOp1 := AOp1;
FOp2 := AOp2;
end;
{ TGrammarSelection }
constructor TGrammarSelection.Create(AOp1, AOp2: IInterfacedObject<TGrammarClass>);
begin
inherited Create(gtSelection);
FOp1 := AOp1;
FOp2 := AOp2;
end;
{ TGrammarGreedyRepeater }
constructor TGrammarGreedyRepeater.Create(AOp: IInterfacedObject<TGrammarClass>; AMinCount, AMaxCount: integer);
begin
inherited Create(gtRepeat);
FOp := AOp;
FMinCount := AMinCount;
FMaxCount := AMaxCount;
end;
function TGrammarGreedyRepeater.GetInfo: string;
function CntToStr(n: Integer): string;
begin
if n=High(n) then result := 'infinite' else result := IntToStr(n);
end;
begin
result := inherited + Format(' Repeat:%s', [
IfThen(FMinCount=FMaxCount, IntToStr(FMinCount), '['+CntToStr(FMinCount)+'..'+CntToStr(FMaxCount)+']')
]);
end;
{ TGrammarNot }
constructor TGrammarNot.Create(AOp: IInterfacedObject<TGrammarClass>);
begin
inherited Create(gtNot);
FOp := AOp;
end;
{ TGrammarEOF }
constructor TGrammarEOF.Create;
begin
inherited Create(gtEOF);
end;
{ TCustomLanguage }
function TCustomLanguage.EOF: TGrammar.TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarEOF.Create);
end;
function TCustomLanguage.Ex(Chars: TEnumerable<Char>; CaseSensitive: boolean): TGrammar.TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarCharSetClass.Create(Chars, CaseSensitive));
end;
function TCustomLanguage.Ex(const Chars: array of Char; CaseSensitive: boolean): TGrammar.TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarCharSetClass.Create(Chars, CaseSensitive));
end;
function TCustomLanguage.Ex(Value: TArray<Byte>): TGrammar.TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarBytesClass.Create(Value));
end;
function TCustomLanguage.Ex(Chars: TSet<Char>; CaseSensitive: boolean): TGrammar.TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarCharSetClass.Create(Chars, CaseSensitive));
end;
function TCustomLanguage.Ex(CharRangeFrom, CharRangeTo: Char; CaseSensitive: boolean): TGrammar.TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarChar.Create(CharRangeFrom,CharRangeTo, CaseSensitive));
end;
function TCustomLanguage.Ex(Value: String; CaseSensitive: boolean): TGrammar.TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarString.Create(Value, CaseSensitive));
end;
function TCustomLanguage.Ex(var AGrammar: TGrammar): TGrammar.TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarLink.Create(AGrammar));
end;
function TCustomLanguage.Ex(ACharClass: TCharClass): TGrammar.TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarCharClass.Create(ACharClass));
end;
function TCustomLanguage.Ex(Value: TEnumerable<Byte>): TGrammar.TMedia;
begin
result.MediaGrm := TInterfacedObject<TGrammarClass>.Create(TGrammarBytesClass.Create(Value));
end;
function TCustomLanguage.Opt: TGrammar.TRange;
begin
result.MinCount := 0;
result.MaxCount := 1;
end;
function TCustomLanguage.Rep: TGrammar.TRange;
begin
result.MinCount := 0;
result.MaxCount := High(result.MaxCount);
end;
function TCustomLanguage.Rep(AMinCount, AMaxCount: integer): TGrammar.TRange;
begin
result.MinCount := AMinCount;
if AMaxCount=integer(infinite)
then result.MaxCount := High(AMaxCount)
else result.MaxCount := AMaxCount;
end;
function TCustomLanguage.Rep(AExactCount: integer): TGrammar.TRange;
begin
result.MinCount := AExactCount;
result.MaxCount := AExactCount;
end;
function TCustomLanguage.Rep1: TGrammar.TRange;
begin
result.MinCount := 1;
result.MaxCount := High(result.MaxCount);
end;
procedure TCustomLanguage.SetMainRule(var Rule: TGrammar);
var
Queue: TVector<TGrammarClass>;
QueuedIds: TSet<int64>;
Operands: TVector<IInterfacedObject<TGrammarClass>>;
Item: TGrammarClass;
I: integer;
begin
Assert(Rule.Grm<>nil, 'rule is not initialized');
Queue.Clear;
Queue.Add(Rule.Grm.Data);
QueuedIds.Init;
QueuedIds.Add(Rule.Id);
repeat
{ process next rule }
Item := Queue.ExtractLast;
if Item is TGrammarLink then
begin
Assert(TGrammarLink(Item).FLink.Grm<>nil, 'link is not initialized');
if TGrammarLink(Item).Op=nil then
TGrammarLink(Item).FOp := TGrammarLink(Item).FLink.Grm;
end;
{ process operands of the rule }
Operands.Clear;
Item.GetOperands(Operands);
for I := 0 to Operands.Count-1 do
begin
Assert(Operands[I]<>nil, 'Operand is not initialized');
Item := Operands[I].Data;
if Item.Id in QueuedIds then
Continue;
QueuedIds.Add(Item.Id);
Queue.Add(Item);
end;
until Queue.Count=0;
end;
procedure TCustomLanguage.SetNames(const Rules: array of TGrammar; const Names: array of string);
var
I: Integer;
begin
Assert(Length(Rules)=Length(Names));
for I := Low(Rules) to High(Rules) do
Rules[I].Name := Names[I];
end;
{ TCustomTextLang }
constructor TCustomTextLang.Create;
begin
WS := Ex(ccWhiteSpace)*Rep;
WS.IncludeIntoParseTree := False;
end;
function TCustomTextLang.tEx(CharRangeFrom, CharRangeTo: Char; CaseSensitive: boolean): TGrammar.TMedia;
begin
result := Ex(WS)*Rep + Ex(CharRangeFrom, CharRangeTo, CaseSensitive);
end;
function TCustomTextLang.tEx(ACharClass: TCharClass): TGrammar.TMedia;
begin
result := Ex(WS)*Rep + Ex(ACharClass);
end;
function TCustomTextLang.tEx(var AGrammar: TGrammar): TGrammar.TMedia;
begin
result := Ex(WS)*Rep + Ex(AGrammar);
end;
function TCustomTextLang.tEx(Value: String; CaseSensitive: boolean): TGrammar.TMedia;
begin
result := Ex(WS)*Rep + Ex(Value, CaseSensitive);
end;
function TCustomTextLang.tEx(const Chars: array of Char; CaseSensitive: boolean): TGrammar.TMedia;
begin
result := Ex(WS)*Rep + Ex(Chars, CaseSensitive);
end;
function TCustomTextLang.tEx(Chars: TEnumerable<Char>; CaseSensitive: boolean): TGrammar.TMedia;
begin
result := Ex(WS)*Rep + Ex(Chars, CaseSensitive);
end;
function TCustomTextLang.tEx(Chars: TSet<Char>; CaseSensitive: boolean): TGrammar.TMedia;
begin
result := Ex(WS)*Rep + Ex(Chars, CaseSensitive);
end;
end.
|
unit Fonetiza.Intf;
interface
type
IFonetiza = interface
['{B906D0E0-1BD1-4D90-BB17-39FE665DBD7C}']
/// <summary>
/// Gerar conteúdo fonético
/// </summary>
/// <param name="AValue">
/// Conteúdo que será processado para geração fonética
/// </param>
/// <returns>
/// Retorna o conteúdo fonético
/// </returns>
function Fonetizar(const AValue: string): string;
/// <summary>
/// Gerar código fonético
/// </summary>
/// <para>
/// Conteúdo que será processado para geração do código fonético
/// </para>
/// <returns>
/// Retorna um código fonético
/// </returns>
function GerarCodigoFonetico(const AValue: string): string;
/// <summary>
/// Gerar lista de códigos fonéticos
/// </summary>
/// <param name="AValue">
/// Conteúdo que será processado para geração dos códigos fonéticos
/// </param>
/// <returns>
/// Retorna uma lista dos códigos fonéticos
/// </returns>
function GerarListaCodigosFoneticos(const AValue: string): TArray<string>;
end;
implementation
end.
|
unit Ths.Erp.Database.Table.AyarHaneSayisi;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TAyarHaneSayisi = class(TTable)
private
FHesapBakiye: TFieldDB;
FAlisMiktar: TFieldDB;
FAlisFiyat: TFieldDB;
FAlisTutar: TFieldDB;
FSatisMiktar: TFieldDB;
FSatisFiyat: TFieldDB;
FSatisTutar: TFieldDB;
FStokMiktar: TFieldDB;
FStokFiyat: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
property HesapBakiye: TFieldDB read FHesapBakiye write FHesapBakiye;
property AlisMiktar: TFieldDB read FAlisMiktar write FAlisMiktar;
property AlisFiyat: TFieldDB read FAlisFiyat write FAlisFiyat;
property AlisTutar: TFieldDB read FAlisTutar write FAlisTutar;
property SatisMiktar: TFieldDB read FSatisMiktar write FSatisMiktar;
property SatisFiyat: TFieldDB read FSatisFiyat write FSatisFiyat;
property SatisTutar: TFieldDB read FSatisTutar write FSatisTutar;
property StokMiktar: TFieldDB read FStokMiktar write FStokMiktar;
property StokFiyat: TFieldDB read FStokFiyat write FStokFiyat;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TAyarHaneSayisi.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'ayar_hane_sayisi';
SourceCode := '1000';
FHesapBakiye := TFieldDB.Create('hesap_bakiye', ftInteger, 2);
FAlisMiktar := TFieldDB.Create('alis_miktar', ftInteger, 2);
FAlisFiyat := TFieldDB.Create('alis_fiyat', ftInteger, 2);
FAlisTutar := TFieldDB.Create('alis_tutar', ftInteger, 2);
FSatisMiktar := TFieldDB.Create('satis_miktar', ftInteger, 2);
FSatisFiyat := TFieldDB.Create('satis_fiyat', ftInteger, 2);
FSatisTutar := TFieldDB.Create('satis_tutar', ftInteger, 2);
FStokMiktar := TFieldDB.Create('stok_miktar', ftInteger, 2);
FStokFiyat := TFieldDB.Create('stok_fiyat', ftInteger, 2);
end;
procedure TAyarHaneSayisi.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FHesapBakiye.FieldName,
TableName + '.' + FAlisMiktar.FieldName,
TableName + '.' + FAlisFiyat.FieldName,
TableName + '.' + FAlisTutar.FieldName,
TableName + '.' + FSatisMiktar.FieldName,
TableName + '.' + FSatisFiyat.FieldName,
TableName + '.' + FSatisTutar.FieldName,
TableName + '.' + FStokMiktar.FieldName,
TableName + '.' + FStokFiyat.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FHesapBakiye.FieldName).DisplayLabel := 'HESAP BAKİYE';
Self.DataSource.DataSet.FindField(FAlisMiktar.FieldName).DisplayLabel := 'ALIŞ MİKTAR';
Self.DataSource.DataSet.FindField(FAlisFiyat.FieldName).DisplayLabel := 'ALIŞ FİYAT';
Self.DataSource.DataSet.FindField(FAlisTutar.FieldName).DisplayLabel := 'ALIŞ TUTAR';
Self.DataSource.DataSet.FindField(FSatisMiktar.FieldName).DisplayLabel := 'SATIŞ MİKTAR';
Self.DataSource.DataSet.FindField(FSatisFiyat.FieldName).DisplayLabel := 'SATIŞ FİYAT';
Self.DataSource.DataSet.FindField(FSatisTutar.FieldName).DisplayLabel := 'SATIŞ TUTAR';
Self.DataSource.DataSet.FindField(FStokMiktar.FieldName).DisplayLabel := 'STOK MİKTAR';
Self.DataSource.DataSet.FindField(FStokFiyat.FieldName).DisplayLabel := 'STOK FİYAT';
end;
end;
end;
procedure TAyarHaneSayisi.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FHesapBakiye.FieldName,
TableName + '.' + FAlisMiktar.FieldName,
TableName + '.' + FAlisFiyat.FieldName,
TableName + '.' + FAlisTutar.FieldName,
TableName + '.' + FSatisMiktar.FieldName,
TableName + '.' + FSatisFiyat.FieldName,
TableName + '.' + FSatisTutar.FieldName,
TableName + '.' + FStokMiktar.FieldName,
TableName + '.' + FStokFiyat.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FHesapBakiye.Value := FormatedVariantVal(FieldByName(FHesapBakiye.FieldName).DataType, FieldByName(FHesapBakiye.FieldName).Value);
FAlisMiktar.Value := FormatedVariantVal(FieldByName(FAlisMiktar.FieldName).DataType, FieldByName(FAlisMiktar.FieldName).Value);
FAlisFiyat.Value := FormatedVariantVal(FieldByName(FAlisFiyat.FieldName).DataType, FieldByName(FAlisFiyat.FieldName).Value);
FAlisTutar.Value := FormatedVariantVal(FieldByName(FAlisTutar.FieldName).DataType, FieldByName(FAlisTutar.FieldName).Value);
FSatisMiktar.Value := FormatedVariantVal(FieldByName(FSatisMiktar.FieldName).DataType, FieldByName(FSatisMiktar.FieldName).Value);
FSatisFiyat.Value := FormatedVariantVal(FieldByName(FSatisFiyat.FieldName).DataType, FieldByName(FSatisFiyat.FieldName).Value);
FSatisTutar.Value := FormatedVariantVal(FieldByName(FSatisTutar.FieldName).DataType, FieldByName(FSatisTutar.FieldName).Value);
FStokMiktar.Value := FormatedVariantVal(FieldByName(FStokMiktar.FieldName).DataType, FieldByName(FStokMiktar.FieldName).Value);
FStokFiyat.Value := FormatedVariantVal(FieldByName(FStokFiyat.FieldName).DataType, FieldByName(FStokFiyat.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TAyarHaneSayisi.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FHesapBakiye.FieldName,
FAlisMiktar.FieldName,
FAlisFiyat.FieldName,
FAlisTutar.FieldName,
FSatisMiktar.FieldName,
FSatisFiyat.FieldName,
FSatisTutar.FieldName,
FStokMiktar.FieldName,
FStokFiyat.FieldName
]);
NewParamForQuery(QueryOfInsert, FHesapBakiye);
NewParamForQuery(QueryOfInsert, FAlisMiktar);
NewParamForQuery(QueryOfInsert, FAlisFiyat);
NewParamForQuery(QueryOfInsert, FAlisTutar);
NewParamForQuery(QueryOfInsert, FSatisMiktar);
NewParamForQuery(QueryOfInsert, FSatisFiyat);
NewParamForQuery(QueryOfInsert, FSatisTutar);
NewParamForQuery(QueryOfInsert, FStokMiktar);
NewParamForQuery(QueryOfInsert, FStokFiyat);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TAyarHaneSayisi.Update(pPermissionControl: Boolean=True);
begin
if Self.IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Self.Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FHesapBakiye.FieldName,
FAlisMiktar.FieldName,
FAlisFiyat.FieldName,
FAlisTutar.FieldName,
FSatisMiktar.FieldName,
FSatisFiyat.FieldName,
FSatisTutar.FieldName,
FStokMiktar.FieldName,
FStokFiyat.FieldName
]);
NewParamForQuery(QueryOfUpdate, FHesapBakiye);
NewParamForQuery(QueryOfUpdate, FAlisMiktar);
NewParamForQuery(QueryOfUpdate, FAlisFiyat);
NewParamForQuery(QueryOfUpdate, FAlisTutar);
NewParamForQuery(QueryOfUpdate, FSatisMiktar);
NewParamForQuery(QueryOfUpdate, FSatisFiyat);
NewParamForQuery(QueryOfUpdate, FSatisTutar);
NewParamForQuery(QueryOfUpdate, FStokMiktar);
NewParamForQuery(QueryOfUpdate, FStokFiyat);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TAyarHaneSayisi.Clone():TTable;
begin
Result := TAyarHaneSayisi.Create(Database);
Self.Id.Clone(TAyarHaneSayisi(Result).Id);
FHesapBakiye.Clone(TAyarHaneSayisi(Result).FHesapBakiye);
FAlisMiktar.Clone(TAyarHaneSayisi(Result).FAlisMiktar);
FAlisFiyat.Clone(TAyarHaneSayisi(Result).FAlisFiyat);
FAlisTutar.Clone(TAyarHaneSayisi(Result).FAlisTutar);
FSatisMiktar.Clone(TAyarHaneSayisi(Result).FSatisMiktar);
FSatisFiyat.Clone(TAyarHaneSayisi(Result).FSatisFiyat);
FSatisTutar.Clone(TAyarHaneSayisi(Result).FSatisTutar);
FStokMiktar.Clone(TAyarHaneSayisi(Result).FStokMiktar);
FStokFiyat.Clone(TAyarHaneSayisi(Result).FStokFiyat);
end;
end.
|
program bubblesort;
const maximum = 20;
var x: array [1..maximum] of integer; {array to sort}
outer, inner, size: integer;
procedure order (var x, y: integer);
var h: integer;
begin
if x > y then begin h := x; x := y; y := h end
end;
begin
{Read unsorted numbers}
read (size); outer := 1;
while (outer <= size) and (outer <= maximum) do
begin read (x[outer]); outer := outer + 1 end;
{Sort the array}
outer := 1;
while outer < size do
begin inner := 1;
while inner <= size - outer do
begin
order (x[inner], x[inner+1]);
inner := inner + 1
end;
outer := outer + 1
end;
{Print the sorted array}
outer := 1;
while outer <= size do
begin write (x[outer]); outer := outer + 1 end
end.
|
unit ColorEditor;
interface
uses Graphics, ExtCtrls;
// Функция загружает нашу политру цветов
procedure LoadColors(aColorListBox: TColorListBox);
implementation
procedure LoadColors(aColorListBox: TColorListBox);
var
aColor: TColor;
begin
aColorListBox.Items.Clear;
aColor := clRed;
aColorListBox.Items.AddObject('Красный',TObject(aColor));
aColor := clGreen;
aColorListBox.Items.AddObject('Зеленый',TObject(aColor));
aColor := clBlue;
aColorListBox.Items.AddObject('Синий',TObject(aColor));
aColor := clYellow;
aColorListBox.Items.AddObject('Желтый',TObject(aColor));
end;
end.
|
unit MainForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, ActnList, Buttons, DataPortSerial, DataPort, DataPortIP,
DataPortHTTP, DataPortFile, LCLType, ComCtrls;
type
{ TFormMain }
TFormMain = class(TForm)
actConnect: TAction;
actClear: TAction;
alMain: TActionList;
btnFileConnect: TBitBtn;
btnSerialConnect: TBitBtn;
btnHTTPConnect: TBitBtn;
btnUDPConnect: TBitBtn;
btnTCPConnect: TBitBtn;
cbSerialBitrate: TComboBox;
cbSerialPort: TComboBox;
chkLocalEcho: TCheckBox;
dpFile: TDataPortFile;
dpHTTP: TDataPortHTTP;
dpUDP: TDataPortUDP;
dpTCP: TDataPortTCP;
dpSerial: TDataPortSerial;
edFileName: TEdit;
edTCPHost: TEdit;
edHTTPHost: TEdit;
edUDPHost: TEdit;
edTCPPort: TEdit;
edUDPPort: TEdit;
lbFileName: TLabel;
lbTCPHost: TLabel;
lbSerialBitrate: TLabel;
lbSerialPort: TLabel;
lbHTTPHost: TLabel;
lbUDPHost: TLabel;
lbTCPPort: TLabel;
lbUDPPort: TLabel;
memoTerminal: TMemo;
pgcMain: TPageControl;
tsTCP: TTabSheet;
tsUDP: TTabSheet;
tsHTTP: TTabSheet;
tsFile: TTabSheet;
tsSerial: TTabSheet;
procedure actClearExecute(Sender: TObject);
procedure actConnectExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure memoTerminalKeyPress(Sender: TObject; var Key: char);
procedure pgcMainChange(Sender: TObject);
private
{ private declarations }
FDataPort: TDataPort;
procedure SetDataPort(AValue: TDataPort);
procedure UpdateSerialPortList();
procedure AppendToTerminal(const s: string);
procedure OnDataAppearHandler(Sender: TObject);
procedure OnErrorHandler(Sender: TObject; const AMsg: string);
procedure OnOpenHandler(Sender: TObject);
procedure OnCloseHandler(Sender: TObject);
public
{ public declarations }
property DataPort: TDataPort read FDataPort write SetDataPort;
end;
var
FormMain: TFormMain;
implementation
{$R *.lfm}
{ TFormMain }
procedure TFormMain.memoTerminalKeyPress(Sender: TObject; var Key: char);
begin
if Assigned(DataPort) then
begin
DataPort.Push(Key);
if chkLocalEcho.Checked then
begin
AppendToTerminal(Key);
end;
end;
end;
procedure TFormMain.pgcMainChange(Sender: TObject);
begin
if pgcMain.ActivePage = tsSerial then
begin
DataPort := dpSerial;
UpdateSerialPortList();
end
else
if pgcMain.ActivePage = tsTCP then
begin
DataPort := dpTCP;
end
else
if pgcMain.ActivePage = tsUDP then
begin
DataPort := dpUDP;
end
else
if pgcMain.ActivePage = tsHTTP then
begin
DataPort := dpHTTP;
end
else
if pgcMain.ActivePage = tsFile then
begin
DataPort := dpFile;
end;
end;
procedure TFormMain.UpdateSerialPortList();
var
sl: TStringList;
begin
cbSerialPort.Items.Clear();
sl := TStringList.Create();
try
sl.CommaText := dpSerial.GetSerialPortNames();
cbSerialPort.Items.AddStrings(sl);
finally
sl.Free();
end;
if cbSerialPort.Items.Count > 0 then
cbSerialPort.ItemIndex := 0
else
cbSerialPort.Text := '';
end;
procedure TFormMain.SetDataPort(AValue: TDataPort);
begin
if FDataPort = AValue then Exit;
if Assigned(FDataPort) then
begin
FDataPort.Close();
FDataPort.OnOpen := nil;
FDataPort.OnClose := nil;
FDataPort.OnDataAppear := nil;
FDataPort.OnError := nil;
FDataPort := nil;
end;
FDataPort := AValue;
if Assigned(FDataPort) then
begin
FDataPort.OnOpen := @OnOpenHandler;
FDataPort.OnClose := @OnCloseHandler;
FDataPort.OnDataAppear := @OnDataAppearHandler;
FDataPort.OnError := @OnErrorHandler;
end;
end;
procedure TFormMain.AppendToTerminal(const s: string);
begin
memoTerminal.Lines.BeginUpdate();
memoTerminal.Text := memoTerminal.Text + s;
if memoTerminal.Lines.Count > 1200 then
begin
while memoTerminal.Lines.Count > 1000 do
memoTerminal.Lines.Delete(0);
end;
memoTerminal.SelStart := MaxInt;
memoTerminal.Lines.EndUpdate();
memoTerminal.ScrollBy(0, -100000);
end;
procedure TFormMain.OnDataAppearHandler(Sender: TObject);
var
sData: AnsiString;
begin
sData := DataPort.Pull();
AppendToTerminal(sData);
end;
procedure TFormMain.OnErrorHandler(Sender: TObject; const AMsg: string);
begin
actConnect.Caption := 'Connect';
AppendToTerminal('Error: ' + AMsg + sLineBreak);
end;
procedure TFormMain.OnOpenHandler(Sender: TObject);
begin
actConnect.Caption := 'Disconnect';
end;
procedure TFormMain.OnCloseHandler(Sender: TObject);
begin
actConnect.Caption := 'Connect';
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
memoTerminal.Clear();
// bitrates
cbSerialBitrate.Items.Clear();
cbSerialBitrate.Items.Append('300');
cbSerialBitrate.Items.Append('1200');
cbSerialBitrate.Items.Append('9600');
cbSerialBitrate.Items.Append('19200');
cbSerialBitrate.Items.Append('57600');
cbSerialBitrate.Items.Append('115200');
cbSerialBitrate.Items.Append('230400');
cbSerialBitrate.Items.Append('923076');
cbSerialBitrate.ItemIndex := 2;
pgcMain.ActivePage := tsSerial;
pgcMainChange(pgcMain);
end;
procedure TFormMain.actConnectExecute(Sender: TObject);
begin
if not Assigned(DataPort) then Exit;
if DataPort.Active then
begin
DataPort.Close();
end
else
begin
if pgcMain.ActivePage = tsSerial then
begin
dpSerial.Port := cbSerialPort.Text;
dpSerial.BaudRate := StrToIntDef(cbSerialBitrate.Text, 9600);
end
else
if pgcMain.ActivePage = tsTCP then
begin
dpTCP.RemoteHost := edTCPHost.Text;
dpTCP.RemotePort := edTCPPort.Text;
end
else
if pgcMain.ActivePage = tsUDP then
begin
dpUDP.RemoteHost := edUDPHost.Text;
dpUDP.RemotePort := edUDPPort.Text;
end
else
if pgcMain.ActivePage = tsHTTP then
begin
dpHTTP.Url := edHTTPHost.Text;
end
else
if pgcMain.ActivePage = tsFile then
begin
dpFile.FileName := edFileName.Text;
end;
actConnect.Caption := 'Connecting..';
DataPort.Open();
if pgcMain.ActivePage = tsHTTP then
begin
// send HTTP request
DataPort.Push('');
end;
end;
end;
procedure TFormMain.actClearExecute(Sender: TObject);
begin
memoTerminal.Clear();
end;
end.
|
unit testbdssunit;
interface
uses Math, Sysutils, Ap, tsort, descriptivestatistics, bdss;
function TestBDSS(Silent : Boolean):Boolean;
function testbdssunit_test_silent():Boolean;
function testbdssunit_test():Boolean;
implementation
procedure Unset2D(var A : TComplex2DArray);forward;
procedure Unset1D(var A : TReal1DArray);forward;
procedure Unset1DI(var A : TInteger1DArray);forward;
procedure TestSortResults(const ASorted : TReal1DArray;
const P1 : TInteger1DArray;
const P2 : TInteger1DArray;
const AOriginal : TReal1DArray;
N : AlglibInteger;
var WasErrors : Boolean);forward;
(*************************************************************************
Testing BDSS operations
*************************************************************************)
function TestBDSS(Silent : Boolean):Boolean;
var
N : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
Pass : AlglibInteger;
PassCount : AlglibInteger;
MaxN : AlglibInteger;
MaxNQ : AlglibInteger;
A : TReal1DArray;
A0 : TReal1DArray;
AT : TReal1DArray;
P : TReal2DArray;
Thresholds : TReal1DArray;
NI : AlglibInteger;
C : TInteger1DArray;
P1 : TInteger1DArray;
P2 : TInteger1DArray;
Ties : TInteger1DArray;
PT1 : TInteger1DArray;
PT2 : TInteger1DArray;
TieCount : AlglibInteger;
C1 : AlglibInteger;
C0 : AlglibInteger;
NC : AlglibInteger;
Tmp : TReal1DArray;
PAL : Double;
PBL : Double;
PAR : Double;
PBR : Double;
CVE : Double;
CVR : Double;
Info : AlglibInteger;
Threshold : Double;
TieBuf : TInteger1DArray;
CntBuf : TInteger1DArray;
RMS : Double;
CVRMS : Double;
WasErrors : Boolean;
TiesErrors : Boolean;
Split2Errors : Boolean;
OptimalSplitKErrors : Boolean;
SplitKErrors : Boolean;
begin
WasErrors := False;
TiesErrors := False;
Split2Errors := False;
SplitKErrors := False;
OptimalSplitKErrors := False;
MaxN := 100;
MaxNQ := 49;
PassCount := 10;
//
// Test ties
//
N:=1;
while N<=MaxN do
begin
Pass:=1;
while Pass<=PassCount do
begin
//
// untied data, test DSTie
//
Unset1DI(P1);
Unset1DI(P2);
Unset1DI(PT1);
Unset1DI(PT2);
SetLength(A, N-1+1);
SetLength(A0, N-1+1);
SetLength(AT, N-1+1);
SetLength(Tmp, N-1+1);
A[0] := 2*RandomReal-1;
Tmp[0] := RandomReal;
I:=1;
while I<=N-1 do
begin
//
// A is randomly permuted
//
A[I] := A[I-1]+0.1*RandomReal+0.1;
Tmp[I] := RandomReal;
Inc(I);
end;
TagSortFastR(Tmp, A, N);
I:=0;
while I<=N-1 do
begin
A0[I] := A[I];
AT[I] := A[I];
Inc(I);
end;
DSTie(A0, N, Ties, TieCount, P1, P2);
TagSort(AT, N, PT1, PT2);
I:=0;
while I<=N-1 do
begin
TiesErrors := TiesErrors or (P1[I]<>PT1[I]);
TiesErrors := TiesErrors or (P2[I]<>PT2[I]);
Inc(I);
end;
TiesErrors := TiesErrors or (TieCount<>N);
if TieCount=N then
begin
I:=0;
while I<=N do
begin
TiesErrors := TiesErrors or (Ties[I]<>I);
Inc(I);
end;
end;
//
// tied data, test DSTie
//
Unset1DI(P1);
Unset1DI(P2);
Unset1DI(PT1);
Unset1DI(PT2);
SetLength(A, N-1+1);
SetLength(A0, N-1+1);
SetLength(AT, N-1+1);
C1 := 0;
C0 := 0;
I:=0;
while I<=N-1 do
begin
A[I] := RandomInteger(2);
if AP_FP_Eq(A[I],0) then
begin
C0 := C0+1;
end
else
begin
C1 := C1+1;
end;
A0[I] := A[I];
AT[I] := A[I];
Inc(I);
end;
DSTie(A0, N, Ties, TieCount, P1, P2);
TagSort(AT, N, PT1, PT2);
I:=0;
while I<=N-1 do
begin
TiesErrors := TiesErrors or (P1[I]<>PT1[I]);
TiesErrors := TiesErrors or (P2[I]<>PT2[I]);
Inc(I);
end;
if (C0=0) or (C1=0) then
begin
TiesErrors := TiesErrors or (TieCount<>1);
if TieCount=1 then
begin
TiesErrors := TiesErrors or (Ties[0]<>0);
TiesErrors := TiesErrors or (Ties[1]<>N);
end;
end
else
begin
TiesErrors := TiesErrors or (TieCount<>2);
if TieCount=2 then
begin
TiesErrors := TiesErrors or (Ties[0]<>0);
TiesErrors := TiesErrors or (Ties[1]<>C0);
TiesErrors := TiesErrors or (Ties[2]<>N);
end;
end;
Inc(Pass);
end;
Inc(N);
end;
//
// split-2
//
//
// General tests for different N's
//
N:=1;
while N<=MaxN do
begin
SetLength(A, N-1+1);
SetLength(C, N-1+1);
//
// one-tie test
//
if N mod 2=0 then
begin
I:=0;
while I<=N-1 do
begin
A[I] := N;
C[I] := I mod 2;
Inc(I);
end;
DSOptimalSplit2(A, C, N, Info, Threshold, PAL, PBL, PAR, PBR, CVE);
if Info<>-3 then
begin
Split2Errors := True;
Inc(N);
Continue;
end;
end;
//
// two-tie test
//
//
// test #1
//
if N>1 then
begin
I:=0;
while I<=N-1 do
begin
A[I] := I div ((N+1) div 2);
C[I] := I div ((N+1) div 2);
Inc(I);
end;
DSOptimalSplit2(A, C, N, Info, Threshold, PAL, PBL, PAR, PBR, CVE);
if Info<>1 then
begin
Split2Errors := True;
Inc(N);
Continue;
end;
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(Threshold-0.5),100*MachineEpsilon);
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(PAL-1),100*MachineEpsilon);
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(PBL-0),100*MachineEpsilon);
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(PAR-0),100*MachineEpsilon);
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(PBR-1),100*MachineEpsilon);
end;
Inc(N);
end;
//
// Special "CREDIT"-test (transparency coefficient)
//
N := 110;
SetLength(A, N-1+1);
SetLength(C, N-1+1);
A[0] := 0.000;
C[0] := 0;
A[1] := 0.000;
C[1] := 0;
A[2] := 0.000;
C[2] := 0;
A[3] := 0.000;
C[3] := 0;
A[4] := 0.000;
C[4] := 0;
A[5] := 0.000;
C[5] := 0;
A[6] := 0.000;
C[6] := 0;
A[7] := 0.000;
C[7] := 1;
A[8] := 0.000;
C[8] := 0;
A[9] := 0.000;
C[9] := 1;
A[10] := 0.000;
C[10] := 0;
A[11] := 0.000;
C[11] := 0;
A[12] := 0.000;
C[12] := 0;
A[13] := 0.000;
C[13] := 0;
A[14] := 0.000;
C[14] := 0;
A[15] := 0.000;
C[15] := 0;
A[16] := 0.000;
C[16] := 0;
A[17] := 0.000;
C[17] := 0;
A[18] := 0.000;
C[18] := 0;
A[19] := 0.000;
C[19] := 0;
A[20] := 0.000;
C[20] := 0;
A[21] := 0.000;
C[21] := 0;
A[22] := 0.000;
C[22] := 1;
A[23] := 0.000;
C[23] := 0;
A[24] := 0.000;
C[24] := 0;
A[25] := 0.000;
C[25] := 0;
A[26] := 0.000;
C[26] := 0;
A[27] := 0.000;
C[27] := 1;
A[28] := 0.000;
C[28] := 0;
A[29] := 0.000;
C[29] := 1;
A[30] := 0.000;
C[30] := 0;
A[31] := 0.000;
C[31] := 1;
A[32] := 0.000;
C[32] := 0;
A[33] := 0.000;
C[33] := 1;
A[34] := 0.000;
C[34] := 0;
A[35] := 0.030;
C[35] := 0;
A[36] := 0.030;
C[36] := 0;
A[37] := 0.050;
C[37] := 0;
A[38] := 0.070;
C[38] := 1;
A[39] := 0.110;
C[39] := 0;
A[40] := 0.110;
C[40] := 1;
A[41] := 0.120;
C[41] := 0;
A[42] := 0.130;
C[42] := 0;
A[43] := 0.140;
C[43] := 0;
A[44] := 0.140;
C[44] := 0;
A[45] := 0.140;
C[45] := 0;
A[46] := 0.150;
C[46] := 0;
A[47] := 0.150;
C[47] := 0;
A[48] := 0.170;
C[48] := 0;
A[49] := 0.190;
C[49] := 1;
A[50] := 0.200;
C[50] := 0;
A[51] := 0.200;
C[51] := 0;
A[52] := 0.250;
C[52] := 0;
A[53] := 0.250;
C[53] := 0;
A[54] := 0.260;
C[54] := 0;
A[55] := 0.270;
C[55] := 0;
A[56] := 0.280;
C[56] := 0;
A[57] := 0.310;
C[57] := 0;
A[58] := 0.310;
C[58] := 0;
A[59] := 0.330;
C[59] := 0;
A[60] := 0.330;
C[60] := 0;
A[61] := 0.340;
C[61] := 0;
A[62] := 0.340;
C[62] := 0;
A[63] := 0.370;
C[63] := 0;
A[64] := 0.380;
C[64] := 1;
A[65] := 0.380;
C[65] := 0;
A[66] := 0.410;
C[66] := 0;
A[67] := 0.460;
C[67] := 0;
A[68] := 0.520;
C[68] := 0;
A[69] := 0.530;
C[69] := 0;
A[70] := 0.540;
C[70] := 0;
A[71] := 0.560;
C[71] := 0;
A[72] := 0.560;
C[72] := 0;
A[73] := 0.570;
C[73] := 0;
A[74] := 0.600;
C[74] := 0;
A[75] := 0.600;
C[75] := 0;
A[76] := 0.620;
C[76] := 0;
A[77] := 0.650;
C[77] := 0;
A[78] := 0.660;
C[78] := 0;
A[79] := 0.680;
C[79] := 0;
A[80] := 0.700;
C[80] := 0;
A[81] := 0.750;
C[81] := 0;
A[82] := 0.770;
C[82] := 0;
A[83] := 0.770;
C[83] := 0;
A[84] := 0.770;
C[84] := 0;
A[85] := 0.790;
C[85] := 0;
A[86] := 0.810;
C[86] := 0;
A[87] := 0.840;
C[87] := 0;
A[88] := 0.860;
C[88] := 0;
A[89] := 0.870;
C[89] := 0;
A[90] := 0.890;
C[90] := 0;
A[91] := 0.900;
C[91] := 1;
A[92] := 0.900;
C[92] := 0;
A[93] := 0.910;
C[93] := 0;
A[94] := 0.940;
C[94] := 0;
A[95] := 0.950;
C[95] := 0;
A[96] := 0.952;
C[96] := 0;
A[97] := 0.970;
C[97] := 0;
A[98] := 0.970;
C[98] := 0;
A[99] := 0.980;
C[99] := 0;
A[100] := 1.000;
C[100] := 0;
A[101] := 1.000;
C[101] := 0;
A[102] := 1.000;
C[102] := 0;
A[103] := 1.000;
C[103] := 0;
A[104] := 1.000;
C[104] := 0;
A[105] := 1.020;
C[105] := 0;
A[106] := 1.090;
C[106] := 0;
A[107] := 1.130;
C[107] := 0;
A[108] := 1.840;
C[108] := 0;
A[109] := 2.470;
C[109] := 0;
DSOptimalSplit2(A, C, N, Info, Threshold, PAL, PBL, PAR, PBR, CVE);
if Info<>1 then
begin
Split2Errors := True;
end
else
begin
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(Threshold-0.195),100*MachineEpsilon);
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(PAL-0.80),0.02);
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(PBL-0.20),0.02);
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(PAR-0.97),0.02);
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(PBR-0.03),0.02);
end;
//
// split-2 fast
//
//
// General tests for different N's
//
N:=1;
while N<=MaxN do
begin
SetLength(A, N-1+1);
SetLength(C, N-1+1);
SetLength(TieBuf, N+1);
SetLength(CntBuf, 3+1);
//
// one-tie test
//
if N mod 2=0 then
begin
I:=0;
while I<=N-1 do
begin
A[I] := N;
C[I] := I mod 2;
Inc(I);
end;
DSOptimalSplit2Fast(A, C, TieBuf, CntBuf, N, 2, 0.00, Info, Threshold, RMS, CVRMS);
if Info<>-3 then
begin
Split2Errors := True;
Inc(N);
Continue;
end;
end;
//
// two-tie test
//
//
// test #1
//
if N>1 then
begin
I:=0;
while I<=N-1 do
begin
A[I] := I div ((N+1) div 2);
C[I] := I div ((N+1) div 2);
Inc(I);
end;
DSOptimalSplit2Fast(A, C, TieBuf, CntBuf, N, 2, 0.00, Info, Threshold, RMS, CVRMS);
if Info<>1 then
begin
Split2Errors := True;
Inc(N);
Continue;
end;
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(Threshold-0.5),100*MachineEpsilon);
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(RMS-0),100*MachineEpsilon);
if N=2 then
begin
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(CVRMS-0.5),100*MachineEpsilon);
end
else
begin
if N=3 then
begin
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(CVRMS-Sqrt((2*0+2*0+2*0.25)/6)),100*MachineEpsilon);
end
else
begin
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(CVRMS),100*MachineEpsilon);
end;
end;
end;
Inc(N);
end;
//
// special tests
//
N := 10;
SetLength(A, N-1+1);
SetLength(C, N-1+1);
SetLength(TieBuf, N+1);
SetLength(CntBuf, 2*3-1+1);
I:=0;
while I<=N-1 do
begin
A[I] := I;
if I<=N-3 then
begin
C[I] := 0;
end
else
begin
C[I] := I-(N-3);
end;
Inc(I);
end;
DSOptimalSplit2Fast(A, C, TieBuf, CntBuf, N, 3, 0.00, Info, Threshold, RMS, CVRMS);
if Info<>1 then
begin
Split2Errors := True;
end
else
begin
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(Threshold-(N-2.5)),100*MachineEpsilon);
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(RMS-Sqrt((0.25+0.25+0.25+0.25)/(3*N))),100*MachineEpsilon);
Split2Errors := Split2Errors or AP_FP_Greater(AbsReal(CVRMS-Sqrt(AP_Double((1+1+1+1))/(3*N))),100*MachineEpsilon);
end;
//
// Optimal split-K
//
//
// General tests for different N's
//
N:=1;
while N<=MaxNQ do
begin
SetLength(A, N-1+1);
SetLength(C, N-1+1);
//
// one-tie test
//
if N mod 2=0 then
begin
I:=0;
while I<=N-1 do
begin
A[I] := Pass;
C[I] := I mod 2;
Inc(I);
end;
DSOptimalSplitK(A, C, N, 2, 2+RandomInteger(5), Info, Thresholds, NI, CVE);
if Info<>-3 then
begin
OptimalSplitKErrors := True;
Inc(N);
Continue;
end;
end;
//
// two-tie test
//
//
// test #1
//
if N>1 then
begin
C0 := 0;
C1 := 0;
I:=0;
while I<=N-1 do
begin
A[I] := I div ((N+1) div 2);
C[I] := I div ((N+1) div 2);
if C[I]=0 then
begin
C0 := C0+1;
end;
if C[I]=1 then
begin
C1 := C1+1;
end;
Inc(I);
end;
DSOptimalSplitK(A, C, N, 2, 2+RandomInteger(5), Info, Thresholds, NI, CVE);
if Info<>1 then
begin
OptimalSplitKErrors := True;
Inc(N);
Continue;
end;
OptimalSplitKErrors := OptimalSplitKErrors or (NI<>2);
OptimalSplitKErrors := OptimalSplitKErrors or AP_FP_Greater(AbsReal(Thresholds[0]-0.5),100*MachineEpsilon);
OptimalSplitKErrors := OptimalSplitKErrors or AP_FP_Greater(AbsReal(CVE-(-C0*Ln(AP_Double(C0)/(C0+1))-C1*Ln(AP_Double(C1)/(C1+1)))),100*MachineEpsilon);
end;
//
// test #2
//
if N>2 then
begin
C0 := 1+RandomInteger(N-1);
C1 := N-C0;
I:=0;
while I<=N-1 do
begin
if I<C0 then
begin
A[I] := 0;
C[I] := 0;
end
else
begin
A[I] := 1;
C[I] := 1;
end;
Inc(I);
end;
DSOptimalSplitK(A, C, N, 2, 2+RandomInteger(5), Info, Thresholds, NI, CVE);
if Info<>1 then
begin
OptimalSplitKErrors := True;
Inc(N);
Continue;
end;
OptimalSplitKErrors := OptimalSplitKErrors or (NI<>2);
OptimalSplitKErrors := OptimalSplitKErrors or AP_FP_Greater(AbsReal(Thresholds[0]-0.5),100*MachineEpsilon);
OptimalSplitKErrors := OptimalSplitKErrors or AP_FP_Greater(AbsReal(CVE-(-C0*Ln(AP_Double(C0)/(C0+1))-C1*Ln(AP_Double(C1)/(C1+1)))),100*MachineEpsilon);
end;
//
// multi-tie test
//
if N>=16 then
begin
//
// Multi-tie test.
//
// First NC-1 ties have C0 entries, remaining NC-th tie
// have C1 entries.
//
NC := Round(Sqrt(N));
C0 := N div NC;
C1 := N-C0*(NC-1);
I:=0;
while I<=NC-2 do
begin
J:=C0*I;
while J<=C0*(I+1)-1 do
begin
A[J] := J;
C[J] := I;
Inc(J);
end;
Inc(I);
end;
J:=C0*(NC-1);
while J<=N-1 do
begin
A[J] := J;
C[J] := NC-1;
Inc(J);
end;
DSOptimalSplitK(A, C, N, NC, NC+RandomInteger(NC), Info, Thresholds, NI, CVE);
if Info<>1 then
begin
OptimalSplitKErrors := True;
Inc(N);
Continue;
end;
OptimalSplitKErrors := OptimalSplitKErrors or (NI<>NC);
if NI=NC then
begin
I:=0;
while I<=NC-2 do
begin
OptimalSplitKErrors := OptimalSplitKErrors or AP_FP_Greater(AbsReal(Thresholds[I]-(C0*(I+1)-1+0.5)),100*MachineEpsilon);
Inc(I);
end;
CVR := -((NC-1)*C0*Ln(AP_Double(C0)/(C0+NC-1))+C1*Ln(AP_Double(C1)/(C1+NC-1)));
OptimalSplitKErrors := OptimalSplitKErrors or AP_FP_Greater(AbsReal(CVE-CVR),100*MachineEpsilon);
end;
end;
Inc(N);
end;
//
// Non-optimal split-K
//
//
// General tests for different N's
//
N:=1;
while N<=MaxNQ do
begin
SetLength(A, N-1+1);
SetLength(C, N-1+1);
//
// one-tie test
//
if N mod 2=0 then
begin
I:=0;
while I<=N-1 do
begin
A[I] := Pass;
C[I] := I mod 2;
Inc(I);
end;
DSSplitK(A, C, N, 2, 2+RandomInteger(5), Info, Thresholds, NI, CVE);
if Info<>-3 then
begin
SplitKErrors := True;
Inc(N);
Continue;
end;
end;
//
// two-tie test
//
//
// test #1
//
if N>1 then
begin
C0 := 0;
C1 := 0;
I:=0;
while I<=N-1 do
begin
A[I] := I div ((N+1) div 2);
C[I] := I div ((N+1) div 2);
if C[I]=0 then
begin
C0 := C0+1;
end;
if C[I]=1 then
begin
C1 := C1+1;
end;
Inc(I);
end;
DSSplitK(A, C, N, 2, 2+RandomInteger(5), Info, Thresholds, NI, CVE);
if Info<>1 then
begin
SplitKErrors := True;
Inc(N);
Continue;
end;
SplitKErrors := SplitKErrors or (NI<>2);
if NI=2 then
begin
SplitKErrors := SplitKErrors or AP_FP_Greater(AbsReal(Thresholds[0]-0.5),100*MachineEpsilon);
SplitKErrors := SplitKErrors or AP_FP_Greater(AbsReal(CVE-(-C0*Ln(AP_Double(C0)/(C0+1))-C1*Ln(AP_Double(C1)/(C1+1)))),100*MachineEpsilon);
end;
end;
//
// test #2
//
if N>2 then
begin
C0 := 1+RandomInteger(N-1);
C1 := N-C0;
I:=0;
while I<=N-1 do
begin
if I<C0 then
begin
A[I] := 0;
C[I] := 0;
end
else
begin
A[I] := 1;
C[I] := 1;
end;
Inc(I);
end;
DSSplitK(A, C, N, 2, 2+RandomInteger(5), Info, Thresholds, NI, CVE);
if Info<>1 then
begin
SplitKErrors := True;
Inc(N);
Continue;
end;
SplitKErrors := SplitKErrors or (NI<>2);
if NI=2 then
begin
SplitKErrors := SplitKErrors or AP_FP_Greater(AbsReal(Thresholds[0]-0.5),100*MachineEpsilon);
SplitKErrors := SplitKErrors or AP_FP_Greater(AbsReal(CVE-(-C0*Ln(AP_Double(C0)/(C0+1))-C1*Ln(AP_Double(C1)/(C1+1)))),100*MachineEpsilon);
end;
end;
//
// multi-tie test
//
C0:=4;
while C0<=N do
begin
if (N mod C0=0) and (N div C0<=C0) and (N div C0>1) then
begin
NC := N div C0;
I:=0;
while I<=NC-1 do
begin
J:=C0*I;
while J<=C0*(I+1)-1 do
begin
A[J] := J;
C[J] := I;
Inc(J);
end;
Inc(I);
end;
DSSplitK(A, C, N, NC, NC+RandomInteger(NC), Info, Thresholds, NI, CVE);
if Info<>1 then
begin
SplitKErrors := True;
Inc(C0);
Continue;
end;
SplitKErrors := SplitKErrors or (NI<>NC);
if NI=NC then
begin
I:=0;
while I<=NC-2 do
begin
SplitKErrors := SplitKErrors or AP_FP_Greater(AbsReal(Thresholds[I]-(C0*(I+1)-1+0.5)),100*MachineEpsilon);
Inc(I);
end;
CVR := -NC*C0*Ln(AP_Double(C0)/(C0+NC-1));
SplitKErrors := SplitKErrors or AP_FP_Greater(AbsReal(CVE-CVR),100*MachineEpsilon);
end;
end;
Inc(C0);
end;
Inc(N);
end;
//
// report
//
WasErrors := TiesErrors or Split2Errors or OptimalSplitKErrors or SplitKErrors;
if not Silent then
begin
Write(Format('TESTING BASIC DATASET SUBROUTINES'#13#10'',[]));
Write(Format('TIES: ',[]));
if not TiesErrors then
begin
Write(Format('OK'#13#10'',[]));
end
else
begin
Write(Format('FAILED'#13#10'',[]));
end;
Write(Format('SPLIT-2: ',[]));
if not Split2Errors then
begin
Write(Format('OK'#13#10'',[]));
end
else
begin
Write(Format('FAILED'#13#10'',[]));
end;
Write(Format('OPTIMAL SPLIT-K: ',[]));
if not OptimalSplitKErrors then
begin
Write(Format('OK'#13#10'',[]));
end
else
begin
Write(Format('FAILED'#13#10'',[]));
end;
Write(Format('SPLIT-K: ',[]));
if not SplitKErrors then
begin
Write(Format('OK'#13#10'',[]));
end
else
begin
Write(Format('FAILED'#13#10'',[]));
end;
if WasErrors then
begin
Write(Format('TEST FAILED'#13#10'',[]));
end
else
begin
Write(Format('TEST PASSED'#13#10'',[]));
end;
Write(Format(''#13#10''#13#10'',[]));
end;
Result := not WasErrors;
end;
(*************************************************************************
Unsets 2D array.
*************************************************************************)
procedure Unset2D(var A : TComplex2DArray);
begin
SetLength(A, 0+1, 0+1);
A[0,0] := C_Complex(2*RandomReal-1);
end;
(*************************************************************************
Unsets 1D array.
*************************************************************************)
procedure Unset1D(var A : TReal1DArray);
begin
SetLength(A, 0+1);
A[0] := 2*RandomReal-1;
end;
(*************************************************************************
Unsets 1D array.
*************************************************************************)
procedure Unset1DI(var A : TInteger1DArray);
begin
SetLength(A, 0+1);
A[0] := RandomInteger(3)-1;
end;
procedure TestSortResults(const ASorted : TReal1DArray;
const P1 : TInteger1DArray;
const P2 : TInteger1DArray;
const AOriginal : TReal1DArray;
N : AlglibInteger;
var WasErrors : Boolean);
var
I : AlglibInteger;
A2 : TReal1DArray;
T : Double;
F : TInteger1DArray;
begin
SetLength(A2, N-1+1);
SetLength(F, N-1+1);
//
// is set ordered?
//
I:=0;
while I<=N-2 do
begin
WasErrors := WasErrors or AP_FP_Greater(ASorted[I],ASorted[I+1]);
Inc(I);
end;
//
// P1 correctness
//
I:=0;
while I<=N-1 do
begin
WasErrors := WasErrors or AP_FP_Neq(ASorted[I],AOriginal[P1[I]]);
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
F[I] := 0;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
F[P1[I]] := F[P1[I]]+1;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
WasErrors := WasErrors or (F[I]<>1);
Inc(I);
end;
//
// P2 correctness
//
I:=0;
while I<=N-1 do
begin
A2[I] := AOriginal[I];
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
if P2[I]<>I then
begin
T := A2[I];
A2[I] := A2[P2[I]];
A2[P2[I]] := T;
end;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
WasErrors := WasErrors or AP_FP_Neq(ASorted[I],A2[I]);
Inc(I);
end;
end;
(*************************************************************************
Silent unit test
*************************************************************************)
function testbdssunit_test_silent():Boolean;
begin
Result := TestBDSS(True);
end;
(*************************************************************************
Unit test
*************************************************************************)
function testbdssunit_test():Boolean;
begin
Result := TestBDSS(False);
end;
end. |
unit uTestuGenericCommands;
{
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, uGenericCommands, uExceptionCodes, uStrings, uExceptions, Forms,
SysUtils, uEnvironment, uRootForm, uBaseCommand, uBase, uEventModel;
type
// Test methods for class TLaunchCommand
TestTLaunchCommand = class(TTestCase)
strict private
FLaunchCommand: TLaunchCommand;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestExecute;
procedure TestUnExecute;
end;
implementation
procedure TestTLaunchCommand.SetUp;
begin
FLaunchCommand := TLaunchCommand.Create;
end;
procedure TestTLaunchCommand.TearDown;
begin
FLaunchCommand.Free;
FLaunchCommand := nil;
end;
procedure TestTLaunchCommand.TestExecute;
begin
Check( Env = nil, 'LaunchCommanExecute Envirement 1' );
FLaunchCommand.Execute;
Check( Env <> nil, 'LaunchCommanExecute Envirement 2' );
Check( Env.EventModel <> nil, 'LaunchCommanExecute Env.EventModel' );
Check( Env.RootForm <> nil, 'LaunchCommanExecute Env.RootForm' );
end;
procedure TestTLaunchCommand.TestUnExecute;
begin
Check( Env <> nil, 'LaunchCommandUnexecute 1' );
FLaunchCommand.UnExecute;
Check( Env = nil, 'LaunchCommandUnexecute 2' );
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTLaunchCommand.Suite);
end.
|
{*********************************************}
{ TeeBI Software Library }
{ DataEditor VCL }
{ Copyright (c) 2015-2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit VCLBI.DataEditor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCLBI.DataViewer, Data.DB, BI.Dataset,
Vcl.Menus, Vcl.Grids, VCLBI.DataControl, VCLBI.Grid, Vcl.DBCtrls,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
BI.DataItem;
type
TDataItemEditor = class(TDataViewer)
PanelButtons: TPanel;
Panel7: TPanel;
BOK: TButton;
BCancel: TButton;
PopupNode: TPopupMenu;
Rename1: TMenuItem;
N2: TMenuItem;
AddField1: TMenuItem;
AddTable1: TMenuItem;
Kind1: TMenuItem;
Integer32bit1: TMenuItem;
Integer64bit1: TMenuItem;
FloatSingle1: TMenuItem;
FloatDouble1: TMenuItem;
FloatExtended1: TMenuItem;
Text1: TMenuItem;
DateTime1: TMenuItem;
Boolean1: TMenuItem;
AddFolder1: TMenuItem;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure Rename1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BOKClick(Sender: TObject);
procedure PopupNodePopup(Sender: TObject);
procedure AddTable1Click(Sender: TObject);
procedure AddFolder1Click(Sender: TObject);
procedure DataSource2UpdateData(Sender: TObject);
procedure ItemsBeforeDelete(DataSet: TDataSet);
procedure AddField1Click(Sender: TObject);
procedure Boolean1Click(Sender: TObject);
private
{ Private declarations }
FOriginal : TDataItem;
IModified : Boolean;
procedure AskSave;
function ConvertKind(const AItem:TDataItem; const AKind:TDataKind):Boolean;
procedure EditButtonClick(Sender: TObject);
procedure Modified;
procedure SaveData;
procedure SelectedEdited(Sender: TObject; Node: TTreeNode; var S: string);
function SelectedItem:TDataItem;
procedure UpdatedData(Sender: TObject);
procedure TryAddNewItem(const ATitle,APrefix:String;
const IsTable:Boolean;
const AKind:TDataKind);
protected
procedure TryAddInfoEditors(const AGrid:TObject); override;
public
{ Public declarations }
class function Edit(const AOwner: TComponent; const AData: TDataItem):Boolean; static;
end;
implementation
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC FireMonkey Login dialog }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.FMXUI.Login;
interface
{$SCOPEDENUMS ON}
uses
{$IFDEF MSWINDOWS}
Winapi.Messages, Winapi.Windows,
{$ENDIF}
System.SysUtils, System.Classes, FMX.Forms, FMX.Dialogs, FMX.Edit, FMX.ListBox,
FMX.Controls, FMX.Objects, FMX.Types, FMX.Effects, FMX.StdCtrls,
FireDAC.Stan.Intf,
FireDAC.UI.Intf, FireDAC.UI, FireDAC.FMXUI.OptsBase;
type
TFDGUIxFMXLoginDialogImpl = class;
TfrmFDGUIxFMXLogin = class;
TFDGUIxFMXLoginDialogImpl = class(TFDGUIxLoginDialogImplBase)
private
function CreateDlg: TfrmFDGUIxFMXLogin;
protected
function ExecuteLogin: Boolean; override;
function ExecuteChngPwd: Boolean; override;
end;
TfrmFDGUIxFMXLogin = class(TfrmFDGUIxFMXOptsBase)
pnlLogin: TPanel;
pnlControls: TPanel;
pnlHistory: TPanel;
Label1: TLabel;
cbxProfiles: TComboBox;
pnlChngPwd: TPanel;
Label2: TLabel;
Label3: TLabel;
edtNewPassword: TEdit;
edtNewPassword2: TEdit;
OpenDialog1: TOpenDialog;
Line5: TLine;
Line6: TLine;
imgEnabled: TImage;
imgDisabled: TImage;
imgOpen: TImage;
pnlButton: TPanel;
pnlCombo: TPanel;
ShadowEffect1: TShadowEffect;
procedure FormCreate(Sender: TObject);
procedure cbxProfilesClick(Sender: TObject);
procedure edtNewPasswordChange(Sender: TObject);
procedure cbxProfilesChange(Sender: TObject);
procedure FileEditClick(Sender: TObject);
procedure imgEnabledClick(Sender: TObject);
private
FDlg: TFDGUIxFMXLoginDialogImpl;
FAddToOptionsHeight: Integer;
FResult: Boolean;
procedure PostprocessLoginDialog(AOk: Boolean);
public
function ExecuteLogin: Boolean;
function ExecuteChngPwd: Boolean;
end;
var
frmFDGUIxFormsLogin: TfrmFDGUIxFMXLogin;
implementation
uses
System.UITypes,
FireDAC.Stan.Consts, FireDAC.Stan.Error, FireDAC.Stan.Util, FireDAC.Stan.Factory,
FireDAC.Stan.ResStrs,
FireDAC.Phys.Intf;
{$R *.fmx}
{-------------------------------------------------------------------------------}
{ TfrmFDGUIxFMXLogin }
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXLogin.PostprocessLoginDialog(AOk: Boolean);
var
i: Integer;
oCtrl: TFmxObject;
begin
try
if AOk then begin
for i := 0 to pnlControls.ChildrenCount - 1 do begin
if not (pnlControls.Children[i] is TPanel) then
Continue;
oCtrl := pnlControls.Children[i].Children[2];
if oCtrl is TCheckBox then
if FDlg.FParams[oCtrl.Tag].FType = '@Y' then
FDlg.FConnectionDef.AsYesNo[FDlg.FParams[oCtrl.Tag].FParam] := TCheckBox(oCtrl).IsChecked
else
FDlg.FConnectionDef.AsBoolean[FDlg.FParams[oCtrl.Tag].FParam] := TCheckBox(oCtrl).IsChecked
else if oCtrl is TEdit then
FDlg.FConnectionDef.AsString[FDlg.FParams[oCtrl.Tag].FParam] := TEdit(oCtrl).Text
else if oCtrl is TComboBox then
if TComboBox(oCtrl).ItemIndex <> -1 then
FDlg.FConnectionDef.AsString[FDlg.FParams[oCtrl.Tag].FParam] := TComboBox(oCtrl).Selected.Text;
end;
end;
finally
Hide;
end;
end;
{-------------------------------------------------------------------------------}
function TfrmFDGUIxFMXLogin.ExecuteLogin: Boolean;
var
i, j: Integer;
rTmp: TFDLoginItem;
oPanel: TPanel;
oLabel: TLabel;
oCombo: TComboBox;
oEdit: TEdit;
oChk: TSwitch;
oBEdit: TEdit;
oImg: TImage;
oEff: TShadowEffect;
oStream: TMemoryStream;
oActiveCtrl: TStyledControl;
oWait: IFDGUIxWaitCursor;
oObj: TFmxObject;
begin
pnlChngPwd.Visible := False;
pnlLogin.Align := TAlignLayout.Client;
pnlLogin.Visible := True;
lblPrompt.Text := S_FD_LoginCredentials;
for i := pnlControls.ChildrenCount - 1 downto 0 do begin
oObj := pnlControls.Children[i];
if oObj is TPanel then
FDFree(oObj);
end;
for i := 0 to Length(FDlg.FParams) - 1 do
for j := i to Length(FDlg.FParams) - 2 do
if FDlg.FParams[j].FOrder > FDlg.FParams[j + 1].FOrder then begin
rTmp := FDlg.FParams[j + 1];
FDlg.FParams[j + 1] := FDlg.FParams[j];
FDlg.FParams[j] := rTmp;
end;
oActiveCtrl := nil;
for i := 0 to Length(FDlg.FParams) - 1 do begin
oPanel := TPanel.Create(Self);
oPanel.StyleLookup := 'backgroundstyle';
oPanel.Parent := pnlControls;
oPanel.Position.Y := i * 26;
oPanel.Position.X := 3;
oPanel.Height := 26;
oPanel.Width := pnlControls.Width;
oLabel := TLabel.Create(Self);
oLabel.Parent := oPanel;
oLabel.Position.Y := 5;
oLabel.Position.X := 3;
oLabel.Text := FDlg.FParams[i].FCaption + ':';
if (FDlg.FParams[i].FType = '@L') or (FDlg.FParams[i].FType = '@Y') then begin
oChk := TSwitch.Create(Self);
oChk.Parent := oPanel;
oChk.Position.Y := 2;
oChk.Position.X := 206;
oChk.Width := 40;
oChk.Height := 20;
oChk.Tag := i;
oChk.IsChecked := (CompareText(FDlg.FParams[i].FValue, S_FD_True) = 0) or
(CompareText(FDlg.FParams[i].FValue, S_FD_Yes) = 0);
end
else if Copy(FDlg.FParams[i].FType, 1, 2) = '@F' then begin
oBEdit := TEdit.Create(Self);
oBEdit.Parent := oPanel;
oBEdit.Position.Y := 2;
oBEdit.Position.X := 80;
oBEdit.Width := 166;
oBEdit.Tag := i;
oImg := TImage.Create(Self);
oImg.Parent := oBEdit;
oImg.Width := 22;
oImg.Align := TAlignLayout.Right;
oImg.OnClick := FileEditClick;
oImg.Cursor := crArrow;
oEff := TShadowEffect.Create(Self);
oEff.Parent := oImg;
oEff.Trigger := 'IsMouseOver=true';
oStream := TMemoryStream.Create;
try
imgOpen.Bitmap.SaveToStream(oStream);
oImg.Bitmap.LoadFromStream(oStream);
finally
FDFree(oStream);
end;
FDGUIxFMXSetupEditor(nil, nil, oBEdit, OpenDialog1, FDlg.FParams[i].FType);
oBEdit.Text := FDlg.FParams[i].FValue;
if (oBEdit.Text = '') and (oActiveCtrl = nil) then
oActiveCtrl := oBEdit;
end
else if (FDlg.FParams[i].FType <> '@S') and (FDlg.FParams[i].FType <> '@I') and
(FDlg.FParams[i].FType <> '@P') then begin
oCombo := TComboBox.Create(Self);
oCombo.Parent := oPanel;
oCombo.Position.Y := 2;
oCombo.Position.X := 80;
oCombo.Width := 166;
oCombo.Tag := i;
FDGUIxFMXSetupEditor(oCombo, nil, nil, nil, FDlg.FParams[i].FType);
oCombo.ItemIndex := oCombo.Items.IndexOf(FDlg.FParams[i].FValue);
if (oCombo.ItemIndex = -1) and (FDlg.FParams[i].FValue <> '') then begin
oCombo.Items.Add(FDlg.FParams[i].FValue);
oCombo.ItemIndex := oCombo.Items.Count - 1;
end;
if (oCombo.ItemIndex = -1) and (oActiveCtrl = nil) then
oActiveCtrl := oCombo;
end
else begin
oEdit := TEdit.Create(Self);
oEdit.Password := FDlg.FParams[i].FType = '@P';
oEdit.Parent := oPanel;
oEdit.Position.Y := 2;
oEdit.Position.X := 80;
oEdit.Width := 166;
oEdit.Tag := i;
oEdit.Text := FDlg.FParams[i].FValue;
if (oEdit.Text = '') and (oActiveCtrl = nil) then
oActiveCtrl := oEdit;
end;
end;
ClientHeight := FAddToOptionsHeight + Length(FDlg.FParams) * 26;
Width := 100 + 160;
if oActiveCtrl = nil then
ActiveControl := btnOk
else
ActiveControl := oActiveCtrl;
if FDlg.FHistoryEnabled then begin
cbxProfiles.Items := FDlg.FHistory;
cbxProfiles.ItemIndex := FDlg.FHistoryIndex;
cbxProfiles.OnChange(nil);
end
else begin
cbxProfiles.Items.Clear;
Height := Height - Trunc(pnlHistory.Height);
pnlHistory.Visible := False;
end;
FDCreateInterface(IFDGUIxWaitCursor, oWait);
try
oWait.PopWait;
{$IFNDEF ANDROID}
FResult := (ShowModal = mrOK);
PostprocessLoginDialog(FResult);
{$ELSE}
ShowModal(procedure(AModalResult: TModalResult)
begin
FResult := AModalResult = mrOK;
PostprocessLoginDialog(FResult);
end);
WaitModal;
{$ENDIF}
Result := FResult;
finally
oWait.PushWait;
end;
end;
{-------------------------------------------------------------------------------}
function TfrmFDGUIxFMXLogin.ExecuteChngPwd: Boolean;
begin
ClientHeight := Trunc(pnlButtons.Height + pnlTop.Height + pnlChngPwd.Height);
Width := 250;
pnlLogin.Visible := False;
pnlChngPwd.Align := TAlignLayout.Client;
pnlChngPwd.Visible := True;
lblPrompt.Text := S_FD_LoginNewPassword;
btnOk.Enabled := False;
ActiveControl := edtNewPassword;
{$IFNDEF ANDROID}
FResult := ShowModal = mrOK;
if FResult then
FDlg.FConnectionDef.Params.NewPassword := edtNewPassword.Text;
{$ELSE}
ShowModal(procedure(AModalResult: TModalResult)
begin
FResult := AModalResult = mrOK;
if FResult then
FDlg.FConnectionDef.Params.NewPassword := edtNewPassword.Text;
Hide;
end);
WaitModal;
{$ENDIF}
Result := FResult;
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXLogin.FormCreate(Sender: TObject);
begin
FAddToOptionsHeight := Trunc(pnlButtons.Height + pnlTop.Height +
pnlHistory.Height);
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXLogin.imgEnabledClick(Sender: TObject);
begin
if cbxProfiles.ItemIndex = -1 then
Exit;
FDlg.RemoveHistory(cbxProfiles.Selected.Text);
cbxProfiles.Items.Delete(cbxProfiles.ItemIndex);
cbxProfiles.ItemIndex := -1;
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXLogin.cbxProfilesClick(Sender: TObject);
var
i: Integer;
oCtrl: TFmxObject;
sVal: String;
oList: TStrings;
oCombo: TComboBox;
begin
if cbxProfiles.ItemIndex = -1 then
Exit;
oList := TFDStringList.Create;
try
FDlg.ReadHistory(cbxProfiles.Selected.Text, oList);
for i := 0 to pnlControls.ChildrenCount - 1 do begin
if not (pnlControls.Children[i] is TPanel) then
Continue;
oCtrl := pnlControls.Children[i].Children[2];
if oCtrl is TCheckBox then
TCheckBox(oCtrl).IsChecked := StrToIntDef(oList.Values[FDlg.FParams[oCtrl.Tag].FParam], 0) <> 0
else begin
sVal := oList.Values[FDlg.FParams[oCtrl.Tag].FParam];
if oCtrl is TEdit then
TEdit(oCtrl).Text := sVal
else if oCtrl is TComboBox then begin
oCombo := TComboBox(oCtrl);
oCombo.ItemIndex := oCombo.Items.IndexOf(sVal);
end;
end;
end;
finally
FDFree(oList);
end;
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXLogin.cbxProfilesChange(Sender: TObject);
begin
imgEnabled.Visible := cbxProfiles.ItemIndex <> -1;
imgDisabled.Enabled := not imgEnabled.Visible;
if Visible then
cbxProfilesClick(nil);
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXLogin.edtNewPasswordChange(Sender: TObject);
begin
btnOk.Enabled := (edtNewPassword.Text = edtNewPassword2.Text);
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXLogin.FileEditClick(Sender: TObject);
var
oEdit: TEdit;
begin
oEdit := TEdit(TImage(Sender).Parent);
OpenDialog1.FileName := oEdit.Text;
if OpenDialog1.Execute then
oEdit.Text := OpenDialog1.FileName;
end;
{-------------------------------------------------------------------------------}
{ TFDGUIxFMXLoginDialogImpl }
{-------------------------------------------------------------------------------}
function TFDGUIxFMXLoginDialogImpl.CreateDlg: TfrmFDGUIxFMXLogin;
begin
Result := TfrmFDGUIxFMXLogin.Create(Application);
Result.FDlg := Self;
Result.Caption := FCaption;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFMXLoginDialogImpl.ExecuteLogin: Boolean;
var
oLogin: TfrmFDGUIxFMXLogin;
begin
oLogin := CreateDlg;
try
Result := oLogin.ExecuteLogin;
finally
FDFree(oLogin);
end;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFMXLoginDialogImpl.ExecuteChngPwd: Boolean;
var
oLogin: TfrmFDGUIxFMXLogin;
begin
oLogin := CreateDlg;
try
Result := oLogin.ExecuteChngPwd;
finally
FDFree(oLogin);
end;
end;
{-------------------------------------------------------------------------------}
var
oFact: TFDFactory;
initialization
oFact := TFDMultyInstanceFactory.Create(TFDGUIxFMXLoginDialogImpl,
IFDGUIxLoginDialog, C_FD_GUIxFMXProvider);
finalization
FDReleaseFactory(oFact);
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLMeshCSG<p>
Constructive Solid Geometry in GLScene.
The CSG system uses BSP to optimize what triangles it considers.
Its kept on a mesh basis to simplyfy things, it allways generates new BSP's,
even if the meshes allready had BSP optimization.
Author: Joen Joensen.
Contributed to the GLScene community.
Features: CSG_Union, CSG_Subtraction, CSG_Intersection.
<b>History : </b><font size=-1><ul>
<li>06/06/10 - Yar - Added GLVectorTypes to uses
<li>30/03/07 - DaStr - Added $I GLScene.inc
<li>18/07/04 - JAJ - Bug fix, causing triangles to dissapear, once in a while.
<li>29/11/03 - JAJ - Created and Submitted to GLScene.
</ul></font>
}
unit GLMeshCSG;
interface
{$I GLScene.inc}
uses
SysUtils, Classes, Math,
//GLS
GLScene, GLVectorTypes, GLVectorFileObjects,
GLVectorGeometry, GLBSP, GLVectorLists;
type
TCSGOperation = (CSG_Union, CSG_Subtraction, CSG_Intersection);
procedure CSG_Operation(obj1, obj2: TMeshObject; Operation: TCSGOperation; Res: TMeshObject; const MaterialName1, MaterialName2: string);
implementation
const
cOwnTriangleEpsilon = 1e-5;
function IntersectPointToPointLinePlane(const point1, point2: TAffineVector; const plane: THmgPlane; intersectPoint: PAffineVector = nil): Boolean;
var
a, b: Extended;
t: Single;
Direction: TAffineVector;
begin
Result := False;
VectorSubtract(Point2, Point1, Direction);
a := VectorDotProduct(plane, Direction); // direction projected to plane normal
if a <> 0 then
begin // direction is parallel to plane
b := PlaneEvaluatePoint(plane, point1); // distance to plane
t := -b / a; // parameter of intersection
Result := (t - EPSILON2 > 0) and (t + EPSILON2 < 1);
if Result and (intersectPoint <> nil) then
begin
intersectPoint^ := VectorCombine(Point1, Direction, 1, t);
if VectorEquals(intersectPoint^, point1) or VectorEquals(intersectPoint^, point2) then
Result := False;
end;
end;
end;
type
TCSGTri = array[0..2] of PAffineVector;
function MakeCSGTri(const V1, V2, V3: PAffineVector): TCSGTri;
begin
Result[0] := v1;
Result[1] := v2;
Result[2] := v3;
end;
procedure CSG_Iterate_tri(const vec, nor: TCSGTri; BSP: TBSPMeshObject; Node: TFGBSPNode; ResMesh: TMeshObject; ResFG: TFGVertexNormalTexIndexList; keepinside, keepoutside, inverttriangle: Boolean);
var
vertex_offset: Integer;
function Iterate_further(const vec, nor: TCSGTri; Node: TFGBSPNode): Boolean;
function MustSplit(d1, d2, d3: Single): Integer;
var
side: Integer;
function Ok(Int: Single): Boolean;
begin
Result := False;
if Int < 0 then
begin
if Side > 0 then
begin
Result := True;
Exit;
end
else
Side := -1;
end
else if Int > 0 then
begin
if Side < 0 then
begin
Result := True;
Exit;
end
else
Side := 1;
end;
end;
begin
Result := 0; // no split
side := 0;
Ok(D1); // can't go wrong yet...
if Ok(D2) then
begin
Result := 1; // pure split.
Exit;
end;
if Ok(D3) then
begin
Result := 1; // pure split.
Exit;
end;
if side = 0 then
begin
Result := 2; // on plane.
Exit;
end;
end;
var
d: array[0..2] of Single;
i, i1: Integer;
b1, b2, b3: Boolean;
intersect_points: array[0..2] of TAffineVector;
intersect_lines: array[0..2] of Integer;
intersect_count: Integer;
p0, p1: Integer;
NextNode: TFGBSPNode;
plane: THmgPlane;
begin
// This have no effect, however it removes a warning...
Result := False;
b1 := False;
b2 := False;
b3 := False;
// This have no effect, however it removes a warning...
// normally we use the Node.SplitPlane, however on the last branch this is a NullPlane, so we have to calculate it.
if VectorEquals(Node.SplitPlane, NullHmgVector) then
plane := PlaneMake(BSP.Vertices[Node.VertexIndices[0]], BSP.Vertices[Node.VertexIndices[1]], BSP.Vertices[Node.VertexIndices[2]])
else
plane := Node.SplitPlane;
// check the three points in the triangle against the plane
for i := 0 to 2 do
begin
d[i] := PlaneEvaluatePoint(plane, Vec[i]^);
if Abs(d[i]) < cOwnTriangleEpsilon then
d[i] := 0;
end;
// based on points placement determine action
case MustSplit(d[0], d[1], d[2]) of
0: // no split
if (d[0] + d[1] + d[2] >= 0) then
begin
// check for sub node, and either iterate them or stop if none.
if Node.PositiveSubNodeIndex = 0 then
Result := keepoutside
else
Result := Iterate_further(Vec, nor, TFGBSPNode(BSP.FaceGroups[Node.PositiveSubNodeIndex]));
end
else
begin
// check for sub node, and either iterate them or stop if none.
if Node.NegativeSubNodeIndex = 0 then
Result := keepinside
else
Result := Iterate_further(Vec, nor, TFGBSPNode(BSP.FaceGroups[Node.NegativeSubNodeIndex]));
end;
1: // must split.
begin
// determine if 2 or 3 triangles are needed for the split.
intersect_count := 0;
for i := 0 to 2 do
begin
i1 := (i + 1) mod 3;
if IntersectPointToPointLinePlane(Vec[i]^, Vec[i1]^, plane, @intersect_points[intersect_count]) then
begin
intersect_lines[intersect_count] := i;
Inc(intersect_count);
end;
end;
// from here of its not thoroughly commented
// the base concept is isolate the two or three triangles, findout which to keep.
// If all is kept we can simply return true and the original triangle wont be split.
// however if only some are needed, we have to return false and add them ourselves...
case intersect_count of
1:
begin
// simple split, two tri's
i := intersect_lines[0];
i1 := (i + 2) mod 3;
// cannot be 0, as then intersect_lines[0] would have other value
if (d[i] > 0) then
if Node.PositiveSubNodeIndex = 0 then
begin
NextNode := nil;
b1 := keepoutside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.PositiveSubNodeIndex])
else if Node.NegativeSubNodeIndex = 0 then
begin
NextNode := nil;
b1 := keepinside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.NegativeSubNodeIndex]);
if NextNode <> nil then
b1 := Iterate_further(MakeCSGTri(Vec[i], @intersect_points[0], Vec[i1]), MakeCSGTri(Nor[i], Nor[i {}], Nor[i1]), NextNode);
i := (intersect_lines[0] + 1) mod 3;
i1 := (i + 1) mod 3;
// cannot be 0, as then intersect_lines[0] would have other value
if (d[i] > 0) then
if Node.PositiveSubNodeIndex = 0 then
begin
NextNode := nil;
b2 := keepoutside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.PositiveSubNodeIndex])
else if Node.NegativeSubNodeIndex = 0 then
begin
NextNode := nil;
b2 := keepinside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.NegativeSubNodeIndex]);
if NextNode <> nil then
b2 := Iterate_further(MakeCSGTri(Vec[i], Vec[i1], @intersect_points[0]), MakeCSGTri(Nor[i], Nor[i1], Nor[i {}]), NextNode);
Result := b1 and b2;
if not Result then
begin
if B1 then
begin
i := intersect_lines[0];
i1 := (i + 2) mod 3;
vertex_offset := ResMesh.Vertices.count;
ResMesh.Vertices.Add(Vec[i]^, intersect_points[0], Vec[i1]^);
ResMesh.TexCoords.Add(Vec[i]^, intersect_points[0], Vec[i1]^);
if inverttriangle then
begin
ResMesh.Normals.Add(VectorScale(Nor[i]^, -1), VectorScale(Nor[i {}]^, -1), VectorScale(Nor[i1]^, -1));
ResFG.VertexIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.NormalIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.TexCoordIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
end
else
begin
ResMesh.Normals.Add(Nor[i]^, Nor[i {}]^, Nor[i1]^);
ResFG.VertexIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.NormalIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.TexCoordIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
end;
end
else if B2 then
begin
i := (intersect_lines[0] + 1) mod 3;
i1 := (i + 1) mod 3;
vertex_offset := ResMesh.Vertices.count;
ResMesh.Vertices.Add(Vec[i]^, Vec[i1]^, intersect_points[0]);
ResMesh.TexCoords.Add(Vec[i]^, Vec[i1]^, intersect_points[0]);
if inverttriangle then
begin
ResMesh.Normals.Add(VectorScale(Nor[i]^, -1), VectorScale(Nor[i {}]^, -1), VectorScale(Nor[i1]^, -1));
ResFG.VertexIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.NormalIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.TexCoordIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
end
else
begin
ResMesh.Normals.Add(Nor[i]^, Nor[i {}]^, Nor[i1]^);
ResFG.VertexIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.NormalIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.TexCoordIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
end;
end;
end;
end;
2:
begin
// complex split, three tri's
if intersect_lines[0] + 1 = intersect_lines[1] then
begin
p0 := 0;
p1 := 1;
end
else
begin
p0 := 1;
p1 := 0;
end;
i := intersect_lines[p0];
i1 := (i + 2) mod 3;
// cannot be 0 as then there would be no intersection
if (d[i] > 0) then
if Node.PositiveSubNodeIndex = 0 then
begin
NextNode := nil;
b1 := keepoutside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.PositiveSubNodeIndex])
else if Node.NegativeSubNodeIndex = 0 then
begin
NextNode := nil;
b1 := keepinside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.NegativeSubNodeIndex]);
if NextNode <> nil then
b1 := Iterate_further(MakeCSGTri(Vec[i], @intersect_points[p0], Vec[i1]), MakeCSGTri(Nor[i], Nor[i {}], Nor[i1]), NextNode);
i1 := (i + 1) mod 3;
// cannot be 0 as then there would be no intersection
if (d[i1] > 0) then
if Node.PositiveSubNodeIndex = 0 then
begin
NextNode := nil;
b2 := keepoutside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.PositiveSubNodeIndex])
else if Node.NegativeSubNodeIndex = 0 then
begin
NextNode := nil;
b2 := keepinside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.NegativeSubNodeIndex]);
if NextNode <> nil then
b2 := Iterate_further(MakeCSGTri(@intersect_points[p0], Vec[i1], @intersect_points[p1]), MakeCSGTri(Nor[i1 {}], Nor[i1], Nor[i1 {}]), NextNode);
i1 := (i + 2) mod 3;
// cannot be 0 as then there would be no intersection
if (d[i1] > 0) then
if Node.PositiveSubNodeIndex = 0 then
begin
NextNode := nil;
b3 := keepoutside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.PositiveSubNodeIndex])
else if Node.NegativeSubNodeIndex = 0 then
begin
NextNode := nil;
b3 := keepinside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.NegativeSubNodeIndex]);
if NextNode <> nil then
b3 := Iterate_further(MakeCSGTri(@intersect_points[p0], @intersect_points[p1], Vec[i1]), MakeCSGTri(Nor[i1 {}], Nor[i1 {}], Nor[i1]), NextNode);
Result := b1 and b2 and b3;
if not Result then
begin
if B1 then
begin
i1 := (i + 2) mod 3;
vertex_offset := ResMesh.Vertices.count;
ResMesh.Vertices.Add(Vec[i]^, intersect_points[p0], Vec[i1]^);
ResMesh.TexCoords.Add(Vec[i]^, intersect_points[p0], Vec[i1]^);
if inverttriangle then
begin
ResMesh.Normals.Add(VectorScale(Nor[i]^, -1), VectorScale(Nor[i {}]^, -1), VectorScale(Nor[i1]^, -1));
ResFG.VertexIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.NormalIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.TexCoordIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
end
else
begin
ResMesh.Normals.Add(Nor[i]^, Nor[i {}]^, Nor[i1]^);
ResFG.VertexIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.NormalIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.TexCoordIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
end;
end;
if B2 then
begin
i1 := (i + 1) mod 3;
vertex_offset := ResMesh.Vertices.count;
ResMesh.Vertices.Add(intersect_points[p0], Vec[i1]^, intersect_points[p1]);
ResMesh.TexCoords.Add(intersect_points[p0], Vec[i1]^, intersect_points[p1]);
if inverttriangle then
begin
ResMesh.Normals.Add(VectorScale(Nor[i1 {}]^, -1), VectorScale(Nor[i1]^, -1), VectorScale(Nor[i1 {}]^, -1));
ResFG.VertexIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.NormalIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.TexCoordIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
end
else
begin
ResMesh.Normals.Add(Nor[i1 {}]^, Nor[i1]^, Nor[i1 {}]^);
ResFG.VertexIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.NormalIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.TexCoordIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
end;
end;
if B3 then
begin
i1 := (i + 2) mod 3;
vertex_offset := ResMesh.Vertices.count;
ResMesh.Vertices.Add(intersect_points[p0], intersect_points[p1], Vec[i1]^);
ResMesh.TexCoords.Add(intersect_points[p0], intersect_points[p1], Vec[i1]^);
if inverttriangle then
begin
ResMesh.Normals.Add(VectorScale(Nor[i1 {}]^, -1), VectorScale(Nor[i1 {}]^, -1), VectorScale(Nor[i1]^, -1));
ResFG.VertexIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.NormalIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.TexCoordIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
end
else
begin
ResMesh.Normals.Add(Nor[i1 {}]^, Nor[i1 {}]^, Nor[i1]^);
ResFG.VertexIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.NormalIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.TexCoordIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
end;
end;
end;
end;
end;
end;
2: // on plane, no split but special logic
begin
// find out if they point the same direction.
d[0] := PlaneEvaluatePoint(Plane, VectorAdd(Vec[0]^, Nor[0]^));
// check for sub node, and either iterate them or stop if none.
if d[0] >= 0 then
if Node.PositiveSubNodeIndex = 0 then
begin
NextNode := nil;
Result := keepoutside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.PositiveSubNodeIndex])
else if Node.NegativeSubNodeIndex = 0 then
begin
NextNode := nil;
Result := keepinside;
end
else
NextNode := TFGBSPNode(BSP.FaceGroups[Node.NegativeSubNodeIndex]);
if NextNode <> nil then
Result := Iterate_further(Vec, Nor, NextNode);
end;
end;
end;
begin
// check this triangle.
if Iterate_Further(Vec, nor, Node) then
begin
// Keep this triangle, logic based on the (keepinside, keepoutside) booleans.
vertex_offset := ResMesh.Vertices.count;
ResMesh.Vertices.Add(Vec[0]^, Vec[1]^, Vec[2]^);
ResMesh.TexCoords.Add(Vec[0]^, Vec[1]^, Vec[2]^);
if inverttriangle then
begin
ResMesh.Normals.Add(VectorScale(Nor[0]^, -1), VectorScale(Nor[1]^, -1), VectorScale(Nor[2]^, -1));
ResFG.VertexIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.NormalIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
ResFG.TexCoordIndices.Add(vertex_offset + 2, vertex_offset + 1, vertex_offset);
end
else
begin
ResMesh.Normals.Add(Nor[0]^, Nor[1]^, Nor[2]^);
ResFG.VertexIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.NormalIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
ResFG.TexCoordIndices.Add(vertex_offset, vertex_offset + 1, vertex_offset + 2);
end;
end;
end;
procedure CSG_Operation(obj1, obj2: TMeshObject; Operation: TCSGOperation; Res: TMeshObject; const MaterialName1, MaterialName2: string);
var
v1, t1, n1: TAffineVectorList;
v2, t2, n2: TAffineVectorList;
BSP1, BSP2: TBSPMeshObject;
FG1, FG2: TFGBSPNode;
i: Integer;
FGR: TFGVertexNormalTexIndexList;
begin
// prepare containers, fill the triangle list from the objects
BSP1 := TBSPMeshObject.Create;
BSP2 := TBSPMeshObject.Create;
BSP1.Mode := momFaceGroups;
BSP2.Mode := momFaceGroups;
FG1 := TFGBSPNode.CreateOwned(BSP1.FaceGroups);
FG2 := TFGBSPNode.CreateOwned(BSP2.FaceGroups);
t1 := TAffineVectorList.create;
n1 := TAffineVectorList.create;
v1 := obj1.ExtractTriangles(t1, n1);
v1.TransformAsPoints(obj1.Owner.Owner.Matrix);
BSP1.Mode := momTriangles;
BSP1.Vertices := v1;
BSP1.Normals := n1;
BSP1.TexCoords := t1;
FG1.VertexIndices.AddSerie(0, 1, BSP1.Vertices.Count);
t2 := TAffineVectorList.create;
n2 := TAffineVectorList.create;
v2 := obj2.ExtractTriangles(t2, n2);
v2.TransformAsPoints(obj2.Owner.Owner.Matrix);
BSP2.Mode := momTriangles;
BSP2.Vertices := v2;
BSP2.Normals := n2;
BSP2.TexCoords := t2;
FG2.VertexIndices.AddSerie(0, 1, BSP2.Vertices.Count);
// Build BSPs
FG1.PerformSplit(FG1.FindSplitPlane, 1);
FG2.PerformSplit(FG2.FindSplitPlane, 1);
// Start creating result.
FGR := TFGVertexNormalTexIndexList.CreateOwned(Res.FaceGroups);
FGR.MaterialName := MaterialName1;
// should be obj1.FaceGroups iteration for perfection and multiple materials!
// First iterate all triangles of object 1, one at a time, down through the BSP tree of Object 2, the last booleans are the key to what actuelly happends.
i := 0;
while i < v1.Count - 2 do
begin
case Operation of
CSG_Union:
begin
CSG_Iterate_tri(MakeCSGTri(@v1.List^[i], @v1.List^[i + 1], @v1.List^[i + 2]), MakeCSGTri(@n1.List^[i], @n1.List^[i + 1], @n1.List^[i + 2]), BSP2, FG2, Res, FGR, false, true, false);
end;
CSG_Subtraction:
begin
CSG_Iterate_tri(MakeCSGTri(@v1.List^[i], @v1.List^[i + 1], @v1.List^[i + 2]), MakeCSGTri(@n1.List^[i], @n1.List^[i + 1], @n1.List^[i + 2]), BSP2, FG2, Res, FGR, false, true, false);
end;
CSG_Intersection:
begin
CSG_Iterate_tri(MakeCSGTri(@v1.List^[i], @v1.List^[i + 1], @v1.List^[i + 2]), MakeCSGTri(@n1.List^[i], @n1.List^[i + 1], @n1.List^[i + 2]), BSP2, FG2, Res, FGR, true, false, false);
end;
end;
inc(i, 3);
end;
// Then iterate all triangles of object 2, one at a time, down through the BSP tree of Object 1, the last booleans are the key to what actuelly happends.
FGR := TFGVertexNormalTexIndexList.CreateOwned(Res.FaceGroups);
FGR.MaterialName := MaterialName2;
i := 0;
while i < v2.Count - 2 do
begin
case Operation of
CSG_Union:
begin
CSG_Iterate_tri(MakeCSGTri(@v2.List^[i], @v2.List^[i + 1], @v2.List^[i + 2]), MakeCSGTri(@n2.List^[i], @n2.List^[i + 1], @n2.List^[i + 2]), BSP1, FG1, Res, FGR, false, true, false);
end;
CSG_Subtraction:
begin
CSG_Iterate_tri(MakeCSGTri(@v2.List^[i], @v2.List^[i + 1], @v2.List^[i + 2]), MakeCSGTri(@n2.List^[i], @n2.List^[i + 1], @n2.List^[i + 2]), BSP1, FG1, Res, FGR, true, false, true);
end;
CSG_Intersection:
begin
CSG_Iterate_tri(MakeCSGTri(@v2.List^[i], @v2.List^[i + 1], @v2.List^[i + 2]), MakeCSGTri(@n2.List^[i], @n2.List^[i + 1], @n2.List^[i + 2]), BSP1, FG1, Res, FGR, true, false, false);
end;
end;
inc(i, 3);
end;
// clean up.
v1.Free;
n1.Free;
t1.Free;
v2.Free;
n2.Free;
t2.Free;
BSP2.Free;
BSP1.Free;
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Трейдер, работающий в границах канала. Канал определяется границами
Болинджера
History:
-----------------------------------------------------------------------------}
unit FC.Trade.Trader.Channel;
{$I Compiler.inc}
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
IStockTraderChannel = interface
['{3E5F7C15-DD48-451C-A218-3BFF5B7DFFA8}']
end;
//Ссылка на хеджирующий ордер
IStockHedgingLink = interface (ISCAttribute)
['{7EBFAB30-9127-427D-98FA-E3E5C3BFC2F8}']
function GetHedgingOrder: IStockOrder;
end;
//ПРизнак того, что этот ордер хеджирующий
IStockHedgeSign = interface (ISCAttribute)
['{393255E4-DDC9-4134-A1DE-91885D85F7BE}']
end;
TStockTraderChannel = class (TStockTraderBase,IStockTraderChannel)
private
FExpertRSI : ISCExpertRSI;
FBarHeightD1 : ISCIndicatorBarHeight;
FMA21_M1,FMA55_M1: ISCIndicatorMA;
FLastOpenOrderTime : TDateTime;
protected
function CreateExpertRSI(const aChart: IStockChart): ISCExpertRSI;
function CreateBarHeightD1(const aChart: IStockChart): ISCIndicatorBarHeight;
function CreateMA_M1(const aChart: IStockChart; aPeriod: integer): ISCIndicatorMA;
//Считает, на какой примерно цене сработает Stop Loss или Trailing Stop
function GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber;
//Считает, какой убыток будет, если закроется по StopLoss или Trailing Stop
function GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber;
//Дать характеристики хеджирующего ордера для указанного ордера
procedure CalcHedgingValues(const aOrder: IStockOrder; out aOP, aSL,aTP,aTS: TStockRealNumber);
procedure SetHedgingOrderValues(const aOrder,aHedgingOrder: IStockOrder);
//Для указанного ордера дать его хеджирующий ордер (если есть)
function GetHedgingOrder(const aOrder: IStockOrder): IStockOrder;
//Установка Trailing Stop на основании свойств трейдера
procedure SetTrailingStopAccordingProperty(aOrder: IStockOrder); override;
procedure CloseProfitableOrders(aKind: TSCOrderKind;const aComment: string);
function GetRecommendedLots: TStockOrderLots; override;
procedure SetTP(const aOrder: IStockOrder; const aTP: TStockRealNumber; const aComment: string);
public
procedure SetProject(const aValue : IStockProject); override;
procedure OnBeginWorkSession; override;
//Посчитать
procedure UpdateStep2(const aTime: TDateTime); override;
function OpenOrder(aKind: TStockOrderKind;const aComment: string=''): IStockOrder;
constructor Create; override;
destructor Destroy; override;
procedure Dispose; override;
end;
TStockHedgeLink = class (TNameValuePersistentObjectRefCounted,IStockHedgingLink,ISCAttribute)
private
FHedgingOrder: IStockOrder;
public
function GetHedgingOrder: IStockOrder;
constructor Create(aHedgingOrder: IStockOrder);
end;
TStockHedgeSign = class (TNameValuePersistentObjectRefCounted,IStockHedgeSign,ISCAttribute)
end;
implementation
uses DateUtils,Variants,Application.Definitions, FC.Trade.OrderCollection, FC.Trade.Trader.Message,
StockChart.Indicators.Properties.Dialog, FC.Trade.Trader.Factory,
FC.DataUtils;
{ TStockTraderChannel }
procedure TStockTraderChannel.CalcHedgingValues(const aOrder: IStockOrder; out aOP, aSL, aTP, aTS: TStockRealNumber);
begin
//Open
aOP:=GetBroker.RoundPrice(aOrder.GetSymbol,GetExpectedStopLossPrice(aOrder));
//Stop Loss
aSL:=GetBroker.RoundPrice(aOrder.GetSymbol, aOP +(aOrder.GetOpenPrice-aOrder.GetStopLoss) / 2);
//Take Profit
aTP:=GetBroker.RoundPrice(aOrder.GetSymbol, aOP -
OrderKindSign[aOrder.GetKind]*
(GetExpectedLoss(aOrder)+
GetBroker.PointToPrice(aOrder.GetSymbol, GetBroker.GetMarketInfo(GetSymbol).Spread)) / 2);
//Trailing Stop
aTS:=GetBroker.RoundPrice(aOrder.GetSymbol,GetExpectedLoss(aOrder) / 2);
end;
procedure TStockTraderChannel.CloseProfitableOrders(aKind: TSCOrderKind;const aComment: string);
var
i: Integer;
aOrders : IStockOrderCollection;
begin
aOrders:=GetOrders;
for i := aOrders.Count- 1 downto 0 do
begin
if (aOrders[i].GetKind=aKind) and (aOrders[i].GetCurrentProfit>0) then
CloseOrder(aOrders[i],aComment);
end;
end;
constructor TStockTraderChannel.Create;
begin
inherited Create;
//UnRegisterProperties([PropLotDefaultRateSize,PropLotDynamicRate]);
end;
function TStockTraderChannel.CreateBarHeightD1(const aChart: IStockChart): ISCIndicatorBarHeight;
var
aCreated: boolean;
begin
result:=CreateOrFindIndicator(aChart,ISCIndicatorBarHeight,'BarHeightD1',true, aCreated) as ISCIndicatorBarHeight;
//Ничего не нашли, создадим нового эксперта
if aCreated then
begin
Result.SetPeriod(3);
Result.SetBarHeight(bhHighLow);
end;
end;
function TStockTraderChannel.CreateMA_M1(const aChart: IStockChart;aPeriod: integer): ISCIndicatorMA;
var
aCreated: boolean;
begin
result:=CreateOrFindIndicator(aChart,ISCIndicatorMA,'MA'+IntToStr(aPeriod)+'_M1',true, aCreated) as ISCIndicatorMA;
//Ничего не нашли, создадим нового эксперта
if aCreated then
begin
Result.SetPeriod(aPeriod);
end;
end;
destructor TStockTraderChannel.Destroy;
begin
inherited;
end;
procedure TStockTraderChannel.Dispose;
begin
inherited;
end;
function TStockTraderChannel.GetExpectedStopLossPrice(aOrder: IStockOrder): TStockRealNumber;
begin
result:=aOrder.GetStopLoss;
if aOrder.GetState=osOpened then
if aOrder.GetKind=okBuy then
result:=max(result,aOrder.GetBestPrice-aOrder.GetTrailingStop)
else
result:=min(result,aOrder.GetBestPrice+aOrder.GetTrailingStop);
end;
function TStockTraderChannel.GetHedgingOrder(const aOrder: IStockOrder): IStockOrder;
var
i: integer;
begin
result:=nil;
i:=aOrder.GetAttributes.IndexOf(IStockHedgingLink);
if i<>-1 then
result:=(aOrder.GetAttributes[i] as IStockHedgingLink).GetHedgingOrder;
end;
function TStockTraderChannel.GetRecommendedLots: TStockOrderLots;
var
aDayVolatility,aDayVolatilityM,k: TStockRealNumber;
begin
if not PropLotDynamicRate.Value then
exit(inherited GetRecommendedLots);
aDayVolatility:=FBarHeightD1.GetValue(FBarHeightD1.GetInputData.Count-1);
//Считаем какая волатильность в деньгах у нас была последние дни
aDayVolatilityM:=GetBroker.PriceToMoney(GetSymbol,aDayVolatility,1);
//Считаем, сколько таких волатильностей вынесет наш баланс
k:=(GetBroker.GetEquity/aDayVolatilityM);
//Теперь берем допустимый процент
result:=RoundTo(k*PropLotDynamicRateSize.Value/100,-2);
end;
function TStockTraderChannel.GetExpectedLoss(const aOrder: IStockOrder): TStockRealNumber;
begin
if aOrder.GetKind=okBuy then
result:=aOrder.GetOpenPrice-GetExpectedStopLossPrice(aOrder)
else
result:=GetExpectedStopLossPrice(aOrder) - aOrder.GetOpenPrice;
end;
function TStockTraderChannel.CreateExpertRSI(const aChart: IStockChart): ISCExpertRSI;
var
aCreated: boolean;
begin
result:=CreateOrFindIndicator(aChart,ISCExpertRSI,'ExpertRSI',true, aCreated) as ISCExpertRSI;
//Ничего не нашли, создадим нового эксперта
if aCreated then
begin
end;
if IndexOfExpert(result)=-1 then
AddExpert(result);
end;
procedure TStockTraderChannel.SetHedgingOrderValues(const aOrder, aHedgingOrder: IStockOrder);
var
aSL,aTP,aTS,aOP: TStockRealNumber;
begin
if aHedgingOrder.GetState<>osPending then
raise EAlgoError.Create; //надо думать
//Это небольшая оптимизация. Зачем редактировать хеджирующий ордер, если мы в профите
//Есть, конечно, опасность резкого скачка, но иначе тормозит. В реале надо отключать
if aOrder.GetCurrentProfit<0 then
begin
CalcHedgingValues(aOrder,aOP,aSL,aTP,aTS);
if not SameValue(aOP,aHedgingOrder.GetPendingOpenPrice) then
begin
aHedgingOrder.SetPendingOpenPrice(aOP);
aHedgingOrder.SetTakeProfit(aTP);
aHedgingOrder.SetStopLoss(aSL);
aHedgingOrder.SetTrailingStop(aTS);
end;
end;
end;
procedure TStockTraderChannel.SetProject(const aValue: IStockProject);
begin
if GetProject=aValue then
exit;
inherited;
if aValue=nil then
begin
FExpertRSI:=nil;
while ExpertCount>0 do
DeleteExpert(0);
end;
if aValue <> nil then
begin
//Создае нужных нам экспертов
FExpertRSI:=CreateExpertRSI(aValue.GetStockChart(sti60));
FBarHeightD1:=CreateBarHeightD1(aValue.GetStockChart(sti1440));
FMA21_M1:= CreateMA_M1(aValue.GetStockChart(sti1),21);
FMA55_M1:= CreateMA_M1(aValue.GetStockChart(sti1),55);
end;
end;
procedure TStockTraderChannel.SetTP(const aOrder: IStockOrder;const aTP: TStockRealNumber; const aComment: string);
var
aNew : TStockRealNumber;
begin
aNew:=GetBroker.RoundPrice(aOrder.GetSymbol,aTP);
if not SameValue(aNew,aOrder.GetTakeProfit) then
begin
if aComment<>'' then
GetBroker.AddMessage(aOrder,aComment);
aOrder.SetTakeProfit(aNew);
end;
end;
procedure TStockTraderChannel.SetTrailingStopAccordingProperty(aOrder: IStockOrder);
var
i: integer;
begin
for I := 0 to aOrder.GetAttributes.Count- 1 do
if Supports(aOrder.GetAttributes.Items[i],IStockHedgeSign) then
exit;
inherited;
end;
procedure TStockTraderChannel.UpdateStep2(const aTime: TDateTime);
function MACross(idx1: integer): integer;
var
x1,x2: integer;
begin
x1:=Sign(FMA21_M1.GetValue(idx1)-FMA55_M1.GetValue(idx1));
x2:=Sign(FMA21_M1.GetValue(idx1-1)-FMA55_M1.GetValue(idx1-1));
if x1=x2 then exit(0);
result:=x1;
end;
var
idx60,idx1: integer;
aInputData : ISCInputDataCollection;
aChart : IStockChart;
aBarHeight : TSCRealNumber;
aOpenedOrder,aOrder{, aHedgingOrder}: IStockOrder;
i: Integer;
aV: TStockRealNumber;
aOpen : integer;
begin
//Брокер может закрыть ордера и без нас. У нас в списке они останутся,
//но будут уже закрыты. Если их не убрать, то открываться в этоу же сторону мы не
//сможем, пока не будет сигнала от эксперта. Если же их удалить, сигналы
//от эксперта в эту же сторону опять можно отрабатывать
RemoveClosedOrders;
(*
//Корректируем значения хеджирующего ордера
for k := 0 to GetOrders.Count - 1 do
begin
aOrder:=GetOrders[k];
if aOrder.GetState=osOpened then
begin
aHedgingOrder:=GetHedgingOrder(aOrder);
if aHedgingOrder<>nil then
begin
Assert(aHedgingOrder<>aOrder);
Assert(aHedgingOrder.GetKind<>aOrder.GetKind);
if aHedgingOrder.GetState=osOpened then //Бывает редко, когда хеджирующий ордер открыли, а основной не закрыли
begin
aOrder.Close('Close because hedging order was opened (Close price must be )'+
PriceToStr(aOrder,GetExpectedStopLossPrice(aOrder)));
end
else
SetHedgingOrderValues(aOrder,aHedgingOrder);
end;
end;
end;
*)
//Анализируем экcпертные оценки
aChart:=GetParentStockChart(FExpertRSI);
aInputData:=aChart.GetInputData;
//idx1:=-1;
//idx60:=-1;
idx60:=aChart.FindBar(aTime);
idx1:=GetParentStockChart(FMA21_M1).FindBar(aTime);
if (idx60<>-1) and (idx1<>-1) then
begin
//Открываем ордер
if MinutesBetween(GetBroker.GetCurrentTime,FLastOpenOrderTime)>60*3 then
begin
aOpen:=0;
if MinuteOf(aTime) in [55..59] then
begin
if (FExpertRSI.GetGuessOpenBuy(idx60)=egSurely) then
begin
if MACross(idx1)=1 then
aOpen:=1;
end
else if (FExpertRSI.GetGuessOpenSell(idx60)=egSurely) then
begin
if MACross(idx1)=-1 then
aOpen:=-1;
end
end;
if aOpen=0 then
begin
if (FExpertRSI.GetGuessOpenBuy(idx60-1)=egSurely) then
begin
if MACross(idx1)=1 then
aOpen:=1;
end
else if (FExpertRSI.GetGuessOpenSell(idx60-1)=egSurely) then
begin
if MACross(idx1)=-1 then
aOpen:=-1;
end;
end;
//BUY
if aOpen=1 then
begin
CloseProfitableOrders(okSell,('Trader: Open opposite'));
aOpenedOrder:=OpenOrder(okBuy);
FLastOpenOrderTime:=GetBroker.GetCurrentTime;
end
//SELL
else if aOpen=-1 then
begin
CloseProfitableOrders(okBuy,('Trader: Open opposite'));
aOpenedOrder:=OpenOrder(okSell);
FLastOpenOrderTime:=GetBroker.GetCurrentTime;
end;
end;
end;
if not (MinuteOf(aTime) in [55..59])then
idx60:=-1;
if (idx60<>-1) then
begin
//Смотрим, не сказал ли нам Эксперт закрывать позиции
if (FExpertRSI.GetGuessCloseBuy(idx60)=egSurely) then
begin
CloseProfitableOrders(okBuy,('Trader: Signal to close'));
end
else if (FExpertRSI.GetGuessCloseSell(idx60)=egSurely) then
begin
CloseProfitableOrders(okSell,('Trader: Signal to close'));
end;
//Смотрим, не сказал ли нам эксперт ставить безубыток
if FExpertRSI.IsFlag(idx60,efSetNonLoss) then
begin
for i := GetOrders.Count-1 downto 0 do
begin
aOrder:=GetOrders[i];
if aOrder.GetState=osOpened then
begin
if aOrder.GetCurrentProfit>0 then
begin
if (aOrder.GetCurrentProfit>FExpertRSI.GetAverageBarHeight(idx60)) or
(GetBroker.GetCurrentTime-aOrder.GetOpenTime>2/24) then
begin
MoveStopLossCloser(aOrder,aOrder.GetOpenPrice);
end;
end
else begin
if (GetBroker.GetCurrentTime-aOrder.GetOpenTime<2/24) then
//aOrder.SetTakeProfit(aOrder.GetOpenPrice)
else //(aOrder.GetCurrentProfit>-FExpertRSI.GetAverageBarHeight(idx60)) or
CloseOrder(aOrder,'Trader: Close unprofitable order');
end;
end;
end;
end;
//Проверяем на наличие плачевных ордеров
aBarHeight:=FExpertRSI.GetAverageBarHeight(idx60);
for i := GetOrders.Count-1 downto 0 do
begin
aOrder:=GetOrders[i];
if aOrder.GetState=osOpened then
begin
if aOrder.GetCurrentProfit<-aBarHeight*2 then
begin
//Ставим TP, который принесет нам убыток, но деватьcя некуда - надо закрыться хоть как-то
if aOrder.GetKind=okBuy then
begin
if FExpertRSI.GetMainTrend(idx60)<0 then //Тренд вниз
begin
if aOrder.GetCurrentProfit<-aBarHeight*2 then
aV:=aOrder.GetOpenPrice-aBarHeight/4
else
aV:=aOrder.GetOpenPrice-aBarHeight/2;
SetTP(aOrder,aV,'Trader: Heavy situation... Let''s move TP...');
end;
end
else begin
if FExpertRSI.GetMainTrend(idx60)>0 then //Тренд вверх
begin
if aOrder.GetCurrentProfit<-aBarHeight*2 then
aV:=aOrder.GetOpenPrice+aBarHeight/4
else
aV:=aOrder.GetOpenPrice+aBarHeight/2;
SetTP(aOrder,aV,'Trader: Heavy situation... Let''s move TP...');
end;
end;
end;
end;
end;
end;
if aOpenedOrder<>nil then
begin
//Assert(GetOrders.Items[GetOrders.Count-1]=aHedgingOrder);
//GetOrders.Delete(GetOrders.Count-1);
end;
(* with OpenOrderAt(okBuy,GetBroker.GetCurrentPrice(GetSymbol,bpkBid),'1231231323') do
try
Close('');
except
on E:Exception do
GetBroker.AddMessage(E.Message);
end;*)
end;
procedure TStockTraderChannel.OnBeginWorkSession;
begin
inherited;
FLastOpenOrderTime:=0;
end;
function TStockTraderChannel.OpenOrder(aKind: TStockOrderKind;
const aComment: string): IStockOrder;
begin
try
Result:=inherited OpenOrder(aKind,aComment);
except
on E:Exception do
GetBroker.AddMessage(E.Message)
end;
end;
{ TStockHedgeLink }
constructor TStockHedgeLink.Create(aHedgingOrder: IStockOrder);
begin
inherited Create;
FHedgingOrder:=aHedgingOrder;
end;
function TStockHedgeLink.GetHedgingOrder: IStockOrder;
begin
result:=FHedgingOrder;
end;
initialization
FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Basic','Channel',TStockTraderChannel,IStockTraderChannel);
end.
|
unit fOptionsSurrogate;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ORCtrls, ORDtTmRng, ORFn, ExtCtrls, fBase508Form,
VA508AccessibilityManager;
type
TfrmOptionsSurrogate = class(TfrmBase508Form)
lblSurrogate: TLabel;
cboSurrogate: TORComboBox;
btnSurrogateDateRange: TButton;
dlgSurrogateDateRange: TORDateRangeDlg;
lblSurrogateText: TStaticText;
btnRemove: TButton;
lblStart: TStaticText;
lblStop: TStaticText;
pnlBottom: TPanel;
bvlBottom: TBevel;
btnCancel: TButton;
btnOK: TButton;
procedure FormShow(Sender: TObject);
procedure btnSurrogateDateRangeClick(Sender: TObject);
procedure cboSurrogateNeedData(Sender: TObject;
const StartFrom: String; Direction, InsertAt: Integer);
procedure btnOKClick(Sender: TObject);
procedure btnRemoveClick(Sender: TObject);
procedure cboSurrogateChange(Sender: TObject);
procedure cboSurrogateKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
procedure LabelInfo;
public
{ Public declarations }
end;
var
frmOptionsSurrogate: TfrmOptionsSurrogate;
procedure DialogOptionsSurrogate(topvalue, leftvalue, fontsize: integer; var info: string);
implementation
uses rOptions, uOptions, rCore;
var
Surrogate, TempSurrogate: TSurrogate;
{$R *.DFM}
procedure DialogOptionsSurrogate(topvalue, leftvalue, fontsize: integer; var info: string);
// create the form and make it modal
var
frmOptionsSurrogate: TfrmOptionsSurrogate;
begin
frmOptionsSurrogate := TfrmOptionsSurrogate.Create(Application);
Surrogate := TSurrogate.Create; // saved settings
TempSurrogate := TSurrogate.Create; // unsaved settings
try
with frmOptionsSurrogate do
begin
if (topvalue < 0) or (leftvalue < 0) then
Position := poScreenCenter
else
begin
Position := poDesigned;
Top := topvalue;
Left := leftvalue;
end;
ResizeAnchoredFormToFont(frmOptionsSurrogate);
with Surrogate do
begin
IEN := StrToInt64Def(Piece(info, '^', 1), -1);
Name := Piece(info, '^', 2);
Start := MakeFMDateTime(Piece(info, '^', 3));
Stop := MakeFMDateTime(Piece(info, '^', 4));
end;
with TempSurrogate do
begin
IEN := Surrogate.IEN;
Name := Surrogate.Name;
Start := Surrogate.Start;
Stop := Surrogate.Stop;
end;
ShowModal;
info := '';
info := info + IntToStr(Surrogate.IEN) + '^';
info := info + Surrogate.Name + '^';
info := info + FloatToStr(Surrogate.Start) + '^';
info := info + FloatToStr(Surrogate.Stop) + '^';
end;
finally
frmOptionsSurrogate.Release;
Surrogate.Free;
TempSurrogate.Free;
end;
end;
procedure TfrmOptionsSurrogate.FormShow(Sender: TObject);
begin
cboSurrogate.InitLongList(Surrogate.Name);
cboSurrogate.SelectByIEN(Surrogate.IEN);
LabelInfo;
end;
procedure TfrmOptionsSurrogate.btnSurrogateDateRangeClick(Sender: TObject);
var
TempFMDate: TFMDateTime;
ok : boolean;
begin
ok := false;
with dlgSurrogateDateRange do
while not ok do
begin
RequireTime := true; //cq 18349 PSPO 1225
FMDateStart := TempSurrogate.Start;
FMDateStop := TempSurrogate.Stop;
if Execute then
begin
If (FMDateStop <> 0) and (FMDateStart > FMDateStop) then
begin
TempFMDate := FMDateStart;
FMDateStart := FMDateStop;
FMDateStop := TempFMDate;
end;
with TempSurrogate do
begin
Start := FMDateStart;
Stop := FMDateStop;
LabelInfo;
if (Stop <> 0) and (Stop < DateTimeToFMDateTime(Now)) then
begin
beep;
InfoBox('Stop Date must be in the future.', 'Warning', MB_OK or MB_ICONWARNING);
Stop := 0;
end
else
ok := true;
end;
end
else
ok := true;
end;
end;
procedure TfrmOptionsSurrogate.cboSurrogateNeedData(
Sender: TObject; const StartFrom: String; Direction, InsertAt: Integer);
begin
cboSurrogate.ForDataUse(SubSetOfPersons(StartFrom, Direction));
end;
procedure TfrmOptionsSurrogate.btnOKClick(Sender: TObject);
var
info, msg: string;
ok: boolean;
begin
//rpcCheckSurrogate(TempSurrogate.IEN, ok, msg); chack is now in rpcSetSurrogateInfo (v27.29 - RV)
ok := TRUE;
info := '';
info := info + IntToStr(TempSurrogate.IEN) + '^';
info := info + FloatToStr(TempSurrogate.Start) + '^';
info := info + FloatToStr(TempSurrogate.Stop) + '^';
rpcSetSurrogateInfo(info, ok, msg);
if not ok then
begin
beep;
InfoBox(msg, 'Warning', MB_OK or MB_ICONWARNING);
with cboSurrogate do ItemIndex := SetExactByIEN(Surrogate.IEN, Surrogate.Name);
cboSurrogateChange(Self);
ModalResult := mrNone;
end
else
begin
with Surrogate do
begin
IEN := TempSurrogate.IEN;
Name := TempSurrogate.Name;
Start := TempSurrogate.Start;
Stop := TempSurrogate.Stop;
end;
ModalResult := mrOK;
end;
end;
procedure TfrmOptionsSurrogate.btnRemoveClick(Sender: TObject);
begin
cboSurrogate.ItemIndex := -1;
cboSurrogate.Text := '';
with TempSurrogate do
begin
IEN := -1;
Name := '';
Start := 0;
Stop := 0;
end;
LabelInfo;
end;
procedure TfrmOptionsSurrogate.LabelInfo;
begin
with TempSurrogate do
begin
btnRemove.Enabled := length(Name) > 0;
btnSurrogateDateRange.Enabled := length(Name) > 0;
if length(Name) > 0 then
lblSurrogateText.Caption := Name
else
begin
lblSurrogateText.Caption := '<no surrogate designated>';
Start := 0;
Stop := 0;
end;
if Start > 0 then
lblStart.Caption := 'from: ' + FormatFMDateTime('mmm d,yyyy@hh:nn', Start)
else
lblStart.Caption := 'from: <now>';
if Stop > 0 then
lblStop.Caption := 'until: ' + FormatFMDateTime('mmm d,yyyy@hh:nn', Stop)
else
lblStop.Caption := 'until: <changed>';
end;
end;
procedure TfrmOptionsSurrogate.cboSurrogateChange(Sender: TObject);
begin
with cboSurrogate do
if (ItemIndex = -1) or (Text = '') then
begin
TempSurrogate.IEN := -1;
TempSurrogate.Name := '';
ItemIndex := -1;
Text := '';
end
else
begin
TempSurrogate.IEN := ItemIEN;
TempSurrogate.Name := DisplayText[cboSurrogate.ItemIndex];
end;
LabelInfo;
end;
procedure TfrmOptionsSurrogate.cboSurrogateKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if cboSurrogate.ItemIndex = -1 then // allow typing to do change event
Application.ProcessMessages;
end;
end.
|
program GameMain;
uses SwinGame, SysUtils;
const
ARRAY_SIZE = 20;
type
NumberArray = Array [0..19] of Integer;
procedure PopulateArray(var data : NumberArray);
var
i: Integer;
begin
for i := Low(data) to High(data) do
data[i] := Rnd(ScreenHeight());
end;
procedure ShowNumbersInList(var data: NumberArray);
var
i: Integer;
begin
ListClearItems('NumbersList');
For i := Low(data) to High(data) do
ListAddItem('NumbersList', IntToStr(data[i]));
end;
procedure PlotBars(var data: NumberArray);
var
barWidth, i: Integer;
begin
ClearScreen(ColorWhite);
barWidth := Round((ScreenWidth() - PanelWidth('NumberPanel'))/ARRAY_SIZE);
for i := Low(data) to High(data) do
FillRectangle(ColorRed, barWidth * i, 600 - data[i], barWidth, data[i]);
DrawInterface();
RefreshScreen(60);
end;
procedure NumberSwap(var value1: Integer; var value2: Integer);
var
tmp: Integer;
begin
tmp := value1;
value1 := value2;
value2 := tmp;
end;
procedure BubbleSort(var data: NumberArray);
var
i, j: Integer;
begin
for i:= High(data) downto Low(data) do
begin
for j := Low(data) to i - 1 do
if (data[j] > data [j+1]) then
begin
NumberSwap(data[j+1], data[j]);
ShowNumbersInList(data);
PlotBars(data);
Delay(100);
end;
end;
end;
procedure InsertionSort(var data: NumberArray);
var
i, j: Integer;
begin
for i := Low(data) to High(data) - 1 do
begin
for j := i + 1 to High(data) do
if (data[i] > data[j]) then
begin
NumberSwap(data[i], data[j]);
ShowNumbersInList(data);
PlotBars(data);
Delay(100);
end;
end;
end;
procedure DoInsertionSort();
var
data : NumberArray;
begin
PopulateArray(data);
ShowNumbersInList(data);
PlotBars(data);
InsertionSort(data);
end;
procedure DoBubbleSort();
var
data : NumberArray;
begin
PopulateArray(data);
ShowNumbersInList(data);
PlotBars(data);
BubbleSort(data);
end;
procedure Main();
begin
OpenGraphicsWindow('Hello World', 800, 600);
LoadResourceBundle( 'NumberBundle.txt' );
GUISetForegroundColor( ColorBlack );
GUISetBackgroundColor( ColorWhite );
ShowPanel( 'NumberPanel' );
ClearScreen(ColorWhite);
repeat
ProcessEvents();
UpdateInterface();
DrawInterface();
RefreshScreen(60);
if ButtonClicked('InsertionSortButton') then
DoInsertionSort();
if ButtonClicked('BubbleSortButton') then
DoBubbleSort();
until WindowCloseRequested();
Delay(1000);
end;
begin
Main();
end. |
unit uModel.PessoaContatoList;
interface
uses System.SysUtils, System.Classes, uModel.Interfaces;
type
TPessoaContatoList = class(TInterfacedObject, iPessoaContatoList)
private
FList: TList;
public
constructor Create;
destructor Destroy; override;
class function New: iPessoaContatoList;
function Add(Value: iPessoaContatoModel): iPessoaContatoList;
function Get(pIndex: Integer): iPessoaContatoModel;
function Delete(pIndex: Integer): iPessoaContatoList;
function Count: Integer;
function Clear: iPessoaContatoList;
end;
implementation
{ TPessoaContatoList }
function TPessoaContatoList.Add(Value: iPessoaContatoModel): iPessoaContatoList;
begin
Result := Self;
FList.Add(Value);
end;
function TPessoaContatoList.Clear: iPessoaContatoList;
begin
Result := Self;
FList.Clear;
end;
function TPessoaContatoList.Count: Integer;
begin
Result := FList.Count;
end;
constructor TPessoaContatoList.Create;
begin
FList := TList.Create;
end;
function TPessoaContatoList.Delete(pIndex: Integer): iPessoaContatoList;
begin
Result := Self;
FList.Delete(pIndex);
end;
destructor TPessoaContatoList.Destroy;
begin
FreeAndNil(FList);
inherited;
end;
function TPessoaContatoList.Get(pIndex: Integer): iPessoaContatoModel;
begin
Result := iPessoaContatoModel(FList[pIndex]);
end;
class function TPessoaContatoList.New: iPessoaContatoList;
begin
Result := Self.Create;
end;
end.
|
unit uGlobals;
interface
uses
uHIDControl, Classes, FSUIPCcontrol, FSXControl, uBuffer, uGameDevices, uXplControl,
uScriptEngine, uMapForm, CfgForm, KbdMacro, uConfig;
type
TOnLogEvent = procedure(pMessage: String) of object;
THDMGlobals = class (TObject)
private
fOwner: TComponent;
fFSX: TFSXcontrol;
fXpl: TXPLcontrol;
fFSUIPC: TFSUIPCcontrol;
fBuffer: THDMBuffer;
fDebugGroups: String;
fHIDControl: THIDControl;
fMacrosList: TMacrosList;
fMapForm: TMapForm;
fMainForm: THIDMacrosForm;
fTraceLog: TStrings;
fAppConfig: TAppConfig;
fScriptEngine: TScriptEngine;
fOnUserLogEvent: TOnLogEvent;
procedure SetDebugGroups(const Value: String);
public
constructor Create(pOwner: TComponent);
destructor Destroy; Override;
procedure DebugLog(Value: String; pGroup: String);
procedure ForcedDebugLog(Value: String; pGroup: String);
procedure LogError(pValue: String);
procedure LogMessage(pValue, pType: String);
function IsModuleLogged(pName: String): Boolean;
property FSX: TFSXcontrol read fFSX;
property Xpl: TXPLcontrol read fXpl;
property FSUIPC: TFSUIPCcontrol read fFSUIPC;
property Buffer: THDMBuffer read fBuffer;
property DebugGroups: String read fDebugGroups write SetDebugGroups;
property Owner: TComponent read fOwner;
property HIDControl: THIDControl read fHIDControl;
property MacrosList: TMacrosList read fMacrosList;
property ScriptEngine: TScriptEngine read fScriptEngine;
property MapForm: TMapForm read fMapForm write fMapForm;
property MainForm: THIDMacrosForm read fMainForm write fMainForm;
property AppConfig: TAppConfig read fAppConfig;
property OnUserLog: TOnLogEvent read fOnUserLogEvent write fOnUserLogEvent;
end;
var
Glb : THDMGlobals;
function Sto_GetFmtFileVersion(const FileName: String = '';
const Fmt: String = '%d.%d.%d.%d'): String;
implementation
uses SysUtils, Windows;
function Sto_GetFmtFileVersion(const FileName: String = '';
const Fmt: String = '%d.%d.%d.%d'): String;
var
sFileName: String;
iBufferSize: DWORD;
iDummy: DWORD;
pBuffer: Pointer;
pFileInfo: Pointer;
iVer: array[1..4] of Word;
begin
// set default value
Result := '';
// get filename of exe/dll if no filename is specified
sFileName := FileName;
if (sFileName = '') then
begin
// prepare buffer for path and terminating #0
SetLength(sFileName, MAX_PATH + 1);
SetLength(sFileName,
GetModuleFileName(hInstance, PChar(sFileName), MAX_PATH + 1));
end;
// get size of version info (0 if no version info exists)
iBufferSize := GetFileVersionInfoSize(PChar(sFileName), iDummy);
if (iBufferSize > 0) then
begin
GetMem(pBuffer, iBufferSize);
try
// get fixed file info (language independent)
GetFileVersionInfo(PChar(sFileName), 0, iBufferSize, pBuffer);
VerQueryValue(pBuffer, '\', pFileInfo, iDummy);
// read version blocks
iVer[1] := HiWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionMS);
iVer[2] := LoWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionMS);
iVer[3] := HiWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionLS);
iVer[4] := LoWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionLS);
finally
FreeMem(pBuffer);
end;
// format result string
Result := Format(Fmt, [iVer[1], iVer[2], iVer[3], iVer[4]]);
end;
end;
{ THDMGlobals }
constructor THDMGlobals.Create(pOwner: TComponent);
begin
fOwner := pOwner;
fTraceLog := nil;
if (pOwner is THIDMacrosForm) then
fMainForm := THIDMacrosForm(pOwner);
fAppConfig := TAppConfig.Create(self);
fFSX := TFSXcontrol.Create;
fXpl := TXPLcontrol.Create(self);
fFSUIPC := TFSUIPCcontrol.Create;
fBuffer := THDMBuffer.Create(pOwner);
fHIDControl := THIDControl.Create;
fScriptEngine := TScriptEngine.Create(pOwner);
fMacrosList := TMacrosList.Create;
fOnUserLogEvent := nil;
end;
procedure THDMGlobals.DebugLog(Value: String; pGroup: String);
begin
if (fTraceLog <> nil) and (Pos(pGroup, fDebugGroups) > 0) then
begin
ForcedDebugLog(Value, pGroup);
end
end;
destructor THDMGlobals.Destroy;
begin
if fTraceLog <> nil then
begin
fTraceLog.Insert(0, 'Exe build number: ' + Sto_GetFmtFileVersion());
fTraceLog.SaveToFile('debug.log');
fTraceLog.Free;
fTraceLog := nil;
end;
fMacrosList.Free;
fHIDControl.Free;
fBuffer.Free;
fFSUIPC.Free;
fXpl.Free;
fFSX.Free;
fScriptEngine.Free;
fAppConfig.Free;
inherited;
end;
procedure THDMGlobals.ForcedDebugLog(Value, pGroup: String);
// no checking for debug groups - always log
var
tmp: PChar;
lVal: String;
begin
lVal := 'HIDMACROS:'+ pGroup + ':' + Value;
GetMem(tmp, Length(lVal) + 1);
try
StrPCopy(tmp, lVal);
OutputDebugString(tmp);
if (fTraceLog <> nil) then
begin
fTraceLog.Add(Format('%s (%d): %s', [FormatDateTime('hh:nn:ss.zzz', time), GetTickCount, Value]));
// If we have more then 5000, something went wrong. Let's save it to analyze and stop trace
if fTraceLog.Count > 5000 then
begin
fTraceLog.SaveToFile('debug_full.log');
fTraceLog.Free;
fTraceLog := nil;
end;
end;
finally
FreeMem(tmp);
end;
end;
function THDMGlobals.IsModuleLogged(pName: String): Boolean;
begin
Result := (fTraceLog <> nil) and (Pos(pName, fDebugGroups) > 0);
end;
procedure THDMGlobals.SetDebugGroups(const Value: String);
begin
if Value = '' then
fDebugGroups := 'GEN:HOOK:FSX:FSUIPC:BUF:XPL:XML:HID'
else
fDebugGroups := Value;
//OutputDebugString(PChar(Value));
if fTraceLog = nil then
fTraceLog := TStringList.Create;
ForcedDebugLog('Using debug groups ' + fDebugGroups, 'CONF');
end;
procedure THDMGlobals.LogError(pValue: String);
begin
LogMessage(pValue, 'ERR');
end;
procedure THDMGlobals.LogMessage(pValue, pType: String);
begin
if Assigned(fOnUserLogEvent) then
fOnUserLogEvent(pType+':'+pValue);
end;
end.
|
unit SocketIncludes;
interface
//#ifndef RAKNET_SOCKETINCLUDES_H
//#define RAKNET_SOCKETINCLUDES_H
// All this crap just to include type SOCKET
//#ifdef __native_client__
//#define _PP_Instance_ PP_Instance
//#else
type
_PP_Instance_ = Integer;
//
//#if defined(WINDOWS_STORE_RT)
// #include <windows.h>
// #include "WinRTSockAddr.h"
// typedef Windows::Networking::Sockets::DatagramSocket^ __UDPSOCKET__;
// typedef Windows::Networking::Sockets::StreamSocket^ __TCPSOCKET__;
// typedef unsigned int socklen_t;
// #define FORMAT_MESSAGE_ALLOCATE_BUFFER 0
// #define FIONBIO 0
// #define LocalFree(x)
// // using Windows.Networking;
// // using Windows.Networking.Sockets;
// // See http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.sockets.datagramsocketcontrol
//#elif defined(_WIN32)
// // IP_DONTFRAGMENT is different between winsock 1 and winsock 2. Therefore, Winsock2.h must be linked againt Ws2_32.lib
// // winsock.h must be linked against WSock32.lib. If these two are mixed up the flag won't work correctly
// // WinRT: http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.sockets
// // Sample code: http://stackoverflow.com/questions/10290945/correct-use-of-udp-datagramsocket
// #include <winsock2.h>
// typedef SOCKET __UDPSOCKET__;
// typedef SOCKET __TCPSOCKET__;
// typedef int socklen_t;
//#else
// #define closesocket close
// #include <unistd.h>
// #include <sys/types.h>
// #include <sys/socket.h>
// #include <netinet/in.h>
// #include <arpa/inet.h>
// #include <unistd.h>
// #include <fcntl.h>
//
// #ifdef __native_client__
// #include "ppapi/cpp/private/net_address_private.h"
// #include "ppapi/c/pp_bool.h"
// #include "ppapi/c/pp_errors.h"
// #include "ppapi/cpp/completion_callback.h"
// #include "ppapi/cpp/instance_handle.h"
// #include "ppapi/cpp/module.h"
// #include "ppapi/cpp/module_impl.h"
// #include "ppapi/c/pp_errors.h"
// #include "ppapi/c/pp_module.h"
// #include "ppapi/c/pp_var.h"
// #include "ppapi/c/pp_resource.h"
// #include "ppapi/c/ppb.h"
// #include "ppapi/c/ppb_instance.h"
// #include "ppapi/c/ppb_messaging.h"
// #include "ppapi/c/ppb_var.h"
// #include "ppapi/c/ppp.h"
// #include "ppapi/c/ppb_core.h"
// #include "ppapi/c/ppp_instance.h"
// #include "ppapi/c/ppp_messaging.h"
// #include "ppapi/c/pp_input_event.h"
// #include "ppapi/c/pp_completion_callback.h"
// //UDP specific - the 'private' folder was copied from the chromium src/ppapi/c headers folder
// #include "ppapi/c/private/ppb_udp_socket_private.h"
// #include "ppapi/cpp/private/net_address_private.h"
// typedef PP_Resource __UDPSOCKET__;
// typedef PP_Resource __TCPSOCKET__;
// #else
// //#include "RakMemoryOverride.h"
// /// Unix/Linux uses ints for sockets
// typedef int __UDPSOCKET__;
// typedef int __TCPSOCKET__;
//#endif
//
//#endif
//
//#endif // RAKNET_SOCKETINCLUDES_H
//
//
implementation
end.
|
//f09_tambah_buku
//Dev : Sandra
//v1.0.0
unit f09_tambah_buku;
interface
uses banana_csvparser;
procedure tambah_buku;
//prosedur untuk menambah buku baru ke dalam list
//input berupa data buku dari user
//output berupa data baru
type
buku_baru = record
b_id : string;
b_judul : string;
b_author : string;
b_jumlah : string;
b_tahun : string;
b_kategori : string;
end;
var
t : text;
c : char;
n,baris,kol : integer;
buku : buku_baru;
tabel : banana_csvdoc;
implementation
procedure tambah_buku;
begin
//input user
writeln ('Masukkan informasi buku yang ditambahkan:');
write('Masukkan ID buku : ');readln(buku.b_id);
write('Masukkan judul buku : '); readln(buku.b_judul);
write('Masukkan pengarang buku : '); readln(buku.b_author);
write('Masukkan jumlah buku : '); readln(buku.b_jumlah);
write('Masukkan tahun terbit buku : '); readln(buku.b_tahun);
write('Masukkan kategori buku : '); readln(buku.b_kategori);
//load data
tabel := load_csv('buku_tmp.csv');
baris := row_count(tabel);
kol := coll_count(tabel);
//memasukkan ke array data yang baru diinput
tabel[baris+1,1] := buku.b_id;
tabel[baris+1,2] := buku.b_judul;
tabel[baris+1,3] := buku.b_author;
tabel[baris+1,4] := buku.b_jumlah;
tabel[baris+1,5] := buku.b_tahun;
tabel[baris+1,6] := buku.b_kategori;
//save
save_csv(tabel,'buku_tmp.csv',baris+1,kol);
//Success message
writeln();
writeln('Buku berhasil ditambahkan ke dalam sistem!');
end;
end.
|
unit Kafka.Factory;
interface
uses
Kafka.Interfaces,
Kafka.Types,
Kafka.Classes,
Kafka.Helper,
Kafka.Lib;
type
TKafkaFactory = class
public
class function NewProducer(const ConfigurationKeys, ConfigurationValues: TArray<String>): IKafkaProducer; overload;
class function NewProducer(const Configuration: prd_kafka_conf_t): IKafkaProducer; overload;
class function NewConsumer(const Configuration: prd_kafka_conf_t; const Brokers: String; const Topics: TArray<String>; const Partitions: TArray<Integer>; const Handler: TConsumerMessageHandlerProc): IKafkaConsumer; overload; static;
class function NewConsumer(const ConfigKeys, ConfigValues, ConfigTopicKeys, ConfigTopicValues: TArray<String>; const Brokers: String; const Topics: TArray<String>; const Partitions: TArray<Integer>; const Handler: TConsumerMessageHandlerProc): IKafkaConsumer; overload; static;
end;
implementation
{ TKafkaFactory }
class function TKafkaFactory.NewConsumer(const ConfigKeys, ConfigValues, ConfigTopicKeys, ConfigTopicValues: TArray<String>; const Brokers: String;
const Topics: TArray<String>; const Partitions: TArray<Integer>; const Handler: TConsumerMessageHandlerProc): IKafkaConsumer;
var
Configuration: prd_kafka_conf_t;
TopicConfiguration: prd_kafka_topic_conf_t;
begin
Configuration := TKafkaHelper.NewConfiguration(
ConfigKeys,
ConfigValues);
TopicConfiguration := TKafkaHelper.NewTopicConfiguration(
ConfigTopicKeys,
ConfigTopicValues);
rd_kafka_conf_set_default_topic_conf(
Configuration,
TopicConfiguration);
Result := NewConsumer(
Configuration,
Brokers,
Topics,
Partitions,
Handler
);
end;
class function TKafkaFactory.NewProducer(const Configuration: prd_kafka_conf_t): IKafkaProducer;
begin
Result := TKafkaProducer.Create(Configuration);
end;
class function TKafkaFactory.NewProducer(const ConfigurationKeys, ConfigurationValues: TArray<String>): IKafkaProducer;
var
Configuration: prd_kafka_conf_t;
begin
Configuration := TKafkaHelper.NewConfiguration(
ConfigurationKeys,
ConfigurationValues);
Result := NewProducer(Configuration);
end;
class function TKafkaFactory.NewConsumer(const Configuration: prd_kafka_conf_t; const Brokers: String;
const Topics: TArray<String>; const Partitions: TArray<Integer>; const Handler: TConsumerMessageHandlerProc): IKafkaConsumer;
begin
Result := TKafkaConsumer.Create(
Configuration,
Handler,
Brokers,
Topics,
Partitions
);
end;
end.
|
unit mCoverSheetDisplayPanel_CPRS_Immunizations;
{
================================================================================
*
* Application: Demo
* Developer: doma.user@domain.ext
* Site: Salt Lake City ISC
* Date: 2015-12-21
*
* Description: Coversheet panel for immunizations.
*
* Notes:
*
================================================================================
}
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.ImageList,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.Menus,
Vcl.ImgList,
Vcl.ComCtrls,
Vcl.StdCtrls,
Vcl.Buttons,
mCoverSheetDisplayPanel_CPRS,
iCoverSheetIntf;
type
TfraCoverSheetDisplayPanel_CPRS_Immunizations = class(TfraCoverSheetDisplayPanel_CPRS)
private
{ Private declarations }
protected
{ Overidden events - TfraCoverSheetDisplayPanel_CPRS }
procedure OnAddItems(aList: TStrings); override;
public
constructor Create(aOwner: TComponent); override;
end;
var
fraCoverSheetDisplayPanel_CPRS_Immunizations: TfraCoverSheetDisplayPanel_CPRS_Immunizations;
implementation
{$R *.dfm}
uses
ORFn,
oDelimitedString;
{ TfraCoverSheetDisplayPanel_CPRS_Immunizations }
constructor TfraCoverSheetDisplayPanel_CPRS_Immunizations.Create(aOwner: TComponent);
begin
inherited;
AddColumn(0, 'Immunization');
AddColumn(1, 'Reaction');
AddColumn(2, 'Date/Time');
CollapseColumns;
fAllowDetailDisplay := False;
end;
procedure TfraCoverSheetDisplayPanel_CPRS_Immunizations.OnAddItems(aList: TStrings);
var
aRec: TDelimitedString;
aStr: string;
begin
try
lvData.Items.BeginUpdate;
for aStr in aList do
begin
aRec := TDelimitedString.Create(aStr);
if lvData.Items.Count = 0 then { Executes before any item is added }
if aRec.GetPieceIsNull(1) and (aList.Count = 1) then
CollapseColumns
else
ExpandColumns;
with lvData.Items.Add do
begin
Caption := MixedCase(aRec.GetPiece(2));
if aRec.GetPiece(1) <> '' then
begin
SubItems.Add(MixedCase(aRec.GetPiece(4)));
SubItems.Add(aRec.GetPieceAsFMDateTimeStr(3));
end;
Data := aRec;
end;
end;
finally
lvData.Items.EndUpdate;
end;
end;
end.
|
unit appMobile.Menu;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.Controls.Presentation,
FMX.StdCtrls,
FMX.Objects,
FMX.Layouts;
type
TfrmMenu = class(TForm)
LyButtom: TLayout;
RcButtom: TRectangle;
LyClient: TLayout;
RcBody: TRectangle;
LyTop: TLayout;
RcTop: TRectangle;
LbTitle: TLabel;
Image1: TImage;
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMenu: TfrmMenu;
implementation
uses
Style.Login;
{$R *.fmx}
procedure TfrmMenu.FormShow(Sender: TObject);
var
Styles : TStyleLogin;
begin
// Background...
with RcTop do
begin
Fill.Color := Styles.LyTopAndButtom;
end;
with RcButtom do
begin
Fill.Color := Styles.LyTopAndButtom;
end;
with RcBody do
begin
Fill.Color := Styles.LyBody;
end;
with LbTitle do
begin
Text := Styles.LbTitleTextMenu;
FontColor := Styles.LbColor;
Font.Size := Styles.LbFontSize;
Height := Styles.LbHeightSize;
Width := Styles.LbWidthSize;
Margins.Right := 20;
end;
end;
end.
|
unit APedidoCompra;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
ExtCtrls, PainelGradiente, Componentes1, StdCtrls, ComCtrls, Buttons,
Localizacao, Grids, DBGrids, Tabela, DBKeyViolation, Db, DBTables, Mask,
numericos, UnPedidoCompra, UnDados, Menus, UnNotasFiscaisFor, DBClient, UnProdutos;
type
TFPedidoCompra = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
DataFinal: TCalendario;
Label4: TLabel;
DataInicial: TCalendario;
Label1: TLabel;
ETipoPeriodo: TComboBoxColor;
Label6: TLabel;
EFornecedor: TEditLocaliza;
BFornecedor: TSpeedButton;
LFornecedor: TLabel;
Localiza: TConsultaPadrao;
PanelColor2: TPanelColor;
BCadastrar: TBitBtn;
BAlterar: TBitBtn;
BConsultar: TBitBtn;
BExcluir: TBitBtn;
BImprimir: TBitBtn;
BFechar: TBitBtn;
PanelColor4: TPanelColor;
PEDIDOCOMPRACORPO: TSQL;
DataPEDIDOCOMPRACORPO: TDataSource;
PRODUTOPEDIDO: TSQL;
DataPRODUTOPEDIDO: TDataSource;
PRODUTOPEDIDOC_NOM_PRO: TWideStringField;
PRODUTOPEDIDONOM_COR: TWideStringField;
PRODUTOPEDIDODESREFERENCIAFORNECEDOR: TWideStringField;
PRODUTOPEDIDOQTDPRODUTO: TFMTBCDField;
PRODUTOPEDIDODESUM: TWideStringField;
PRODUTOPEDIDOVALUNITARIO: TFMTBCDField;
PRODUTOPEDIDOVALTOTAL: TFMTBCDField;
PEDIDOCOMPRACORPOSEQPEDIDO: TFMTBCDField;
PEDIDOCOMPRACORPODATPREVISTA: TSQLTimeStampField;
PEDIDOCOMPRACORPOC_NOM_CLI: TWideStringField;
PEDIDOCOMPRACORPOVALTOTAL: TFMTBCDField;
PEDIDOCOMPRACORPOC_NOM_PAG: TWideStringField;
PEDIDOCOMPRACORPOCODFILIAL: TFMTBCDField;
PopupMenu1: TPopupMenu;
mnAprovarPedido: TMenuItem;
PEDIDOCOMPRACORPODATAPROVACAO: TSQLTimeStampField;
PEDIDOCOMPRACORPOC_NOM_USU: TWideStringField;
PEDIDOCOMPRACORPODATENTREGA: TSQLTimeStampField;
Label7: TLabel;
ESituacao: TComboBoxColor;
PanelColor5: TPanelColor;
GPedidoItem: TGridIndice;
Splitter1: TSplitter;
GPedidoCorpo: TGridIndice;
PanelColor3: TPanelColor;
Label2: TLabel;
Label5: TLabel;
CAtualiza: TCheckBox;
EQuantidade: Tnumerico;
EValor: Tnumerico;
Baixar1: TMenuItem;
PEDIDOCOMPRACORPODATPAGAMENTOANTECIPADO: TSQLTimeStampField;
Label8: TLabel;
Aux: TSQL;
PEDIDOCOMPRACORPONOMEST: TWideStringField;
PEDIDOCOMPRACORPOCODESTAGIO: TFMTBCDField;
PEDIDOCOMPRACORPOUSUAPROVACAO: TWideStringField;
PEDIDOCOMPRACORPODATPEDIDO: TSQLTimeStampField;
EEstagio: TEditLocaliza;
BEstagio: TSpeedButton;
Label9: TLabel;
AlterarEstgio1: TMenuItem;
ConcluirPedidoCompra1: TMenuItem;
ExtornarPedidoCompra1: TMenuItem;
PRODUTOPEDIDOQTDSOLICITADA: TFMTBCDField;
Label13: TLabel;
EComprador: TEditLocaliza;
SpeedButton4: TSpeedButton;
Label11: TLabel;
PEDIDOCOMPRACORPONOMCOMPRADOR: TWideStringField;
Label10: TLabel;
SpeedButton1: TSpeedButton;
Label12: TLabel;
ESolicitacao: TEditLocaliza;
CPeriodo: TCheckBox;
Label3: TLabel;
SpeedButton3: TSpeedButton;
Label14: TLabel;
Label15: TLabel;
SpeedButton6: TSpeedButton;
Label16: TLabel;
Label17: TLabel;
SpeedButton7: TSpeedButton;
Label18: TLabel;
EFilial: TEditLocaliza;
EOrdemProducao: TEditLocaliza;
EFracao: TEditLocaliza;
BGerarNF: TBitBtn;
PEDIDOCOMPRACORPOCODCLIENTE: TFMTBCDField;
PEDIDOCOMPRACORPOCODFORMAPAGAMENTO: TFMTBCDField;
PRODUTOPEDIDOQTDBAIXADO: TFMTBCDField;
N1: TMenuItem;
N2: TMenuItem;
ImprimirPedidosPendentes1: TMenuItem;
PEDIDOCOMPRACORPODATRENEGOCIADO: TSQLTimeStampField;
EPedidoCompra: Tnumerico;
BFiltros: TBitBtn;
Label19: TLabel;
N3: TMenuItem;
ConsultarNotasFiscais1: TMenuItem;
N4: TMenuItem;
ConsultaAgendamento1: TMenuItem;
Label20: TLabel;
SpeedButton2: TSpeedButton;
Label21: TLabel;
EProduto: TEditColor;
N5: TMenuItem;
ConsultaSolicitaoCompra1: TMenuItem;
PRODUTOPEDIDOC_COD_PRO: TWideStringField;
PEDIDOCOMPRACORPOCODCONDICAOPAGAMENTO: TFMTBCDField;
PRODUTOPEDIDOLARCHAPA: TFMTBCDField;
PRODUTOPEDIDOCOMCHAPA: TFMTBCDField;
PRODUTOPEDIDOQTDCHAPA: TFMTBCDField;
PEDIDOCOMPRACORPOTIPPEDIDO: TWideStringField;
PEDIDOCOMPRACORPOTIPOPEDIDO: TStringField;
Label22: TLabel;
ETipo: TComboBoxColor;
EUsuario: TRBEditLocaliza;
Label23: TLabel;
SpeedButton5: TSpeedButton;
Label24: TLabel;
N6: TMenuItem;
ConsultaOramentoCompra1: TMenuItem;
N7: TMenuItem;
BCancelar: TBitBtn;
Duplicar1: TMenuItem;
BImportarXML: TBitBtn;
OpenXML: TOpenDialog;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure BCadastrarClick(Sender: TObject);
procedure DataInicialCloseUp(Sender: TObject);
procedure PEDIDOCOMPRACORPOAfterScroll(DataSet: TDataSet);
procedure GPedidoCorpoOrdem(Ordem: String);
procedure GPedidoItemOrdem(Ordem: String);
procedure CAtualizaClick(Sender: TObject);
procedure EFornecedorRetorno(Retorno1, Retorno2: String);
procedure BExcluirClick(Sender: TObject);
procedure BConsultarClick(Sender: TObject);
procedure BAlterarClick(Sender: TObject);
procedure mnAprovarPedidoClick(Sender: TObject);
procedure Baixar1Click(Sender: TObject);
procedure AlterarEstgio1Click(Sender: TObject);
procedure ConcluirPedidoCompra1Click(Sender: TObject);
procedure BImprimirClick(Sender: TObject);
procedure ExtornarPedidoCompra1Click(Sender: TObject);
procedure EOrdemProducaoSelect(Sender: TObject);
procedure EFracaoSelect(Sender: TObject);
procedure GerarNotaFiscaldeentrada1Click(Sender: TObject);
procedure ImprimirPedidosPendentes1Click(Sender: TObject);
procedure BFiltrosClick(Sender: TObject);
procedure EPedidoCompraKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ConsultarNotasFiscais1Click(Sender: TObject);
procedure ConsultaAgendamento1Click(Sender: TObject);
procedure EProdutoExit(Sender: TObject);
procedure EProdutoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure SpeedButton2Click(Sender: TObject);
procedure ConsultaSolicitaoCompra1Click(Sender: TObject);
procedure GPedidoCorpoDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
procedure PEDIDOCOMPRACORPOCalcFields(DataSet: TDataSet);
procedure ETipoChange(Sender: TObject);
procedure ConsultaOramentoCompra1Click(Sender: TObject);
procedure BduplicarClick(Sender: TObject);
procedure BCancelarClick(Sender: TObject);
procedure Duplicar1Click(Sender: TObject);
private
FunNotaFor: TFuncoesNFFor;
VprSeqProduto,
VprFilialNotaEntrada,
VprCodFilialOrcamento,
VprSeqOrcamento,
VprSeqNotaEntrada: Integer;
FunPedidoCompra: TRBFunPedidoCompra;
VprOrdem: String;
VprOrdemItens: String;
procedure InicializaTela;
procedure AtualizaConsulta(VpaPosicionar : Boolean = false);
procedure AdicionaFiltros(VpaSelect: TStrings);
procedure PosItensPedido;
procedure AtualizaTotais;
procedure InsereNaListaPedidos(VpaListaPedidos: TList; VpaDPedidoCompraCorpo: TRBDPedidoCompraCorpo);
procedure CarDClassePedidos(VpaListaPedidos: TList);
function ExisteProduto: Boolean;
function LocalizaProduto: Boolean;
procedure ConfiguraPermissaoUsuario;
public
procedure ConsultaPedidosSolicitacao(VpaSeqSolicitacao: Integer);
procedure ConsultaPedidosOrdemProducao(VpaCodFilial, VpaSeqOrdemProducao, VpaSeqFracao : Integer);
procedure ConsultaNotaEntrada(VpaCodFilial, VpaSeqNota : Integer);
procedure ConsultaProduto(VpaSeqProduto : Integer);
procedure ConsultaPedidosOrcamentoCompra(VpaCodFilial,VpaSeqOrcamento : Integer);
end;
var
FPedidoCompra: TFPedidoCompra;
implementation
uses
APrincipal, ANovoPedidoCompra, ConstMSG, Constantes, FunSQL, FunData,
AAlteraEstagioPedidoCompra, UnCrystal, FunObjeto, ANovaNotaFiscaisFor,
UnDadosProduto, AAgendamentos, dmRave, ALocalizaProdutos, ASolicitacaoCompras, AOrcamentoCompras;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFPedidoCompra.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
FunNotaFor:= TFuncoesNFFor.criar(Self,FPrincipal.BaseDados);
VprCodFilialOrcamento := 0;
FunPedidoCompra:= TRBFunPedidoCompra.Cria(FPrincipal.BaseDados);
ConfiguraPermissaoUsuario;
InicializaTela;
VprOrdem:= ' ORDER BY PCC.SEQPEDIDO';
VprOrdemItens:= ' ORDER BY PRO.C_NOM_PRO';
AtualizaConsulta;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFPedidoCompra.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Aux.Close;
PRODUTOPEDIDO.Close;
PEDIDOCOMPRACORPO.Close;
FunPedidoCompra.Free;
FunNotaFor.Free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFPedidoCompra.ConsultaPedidosSolicitacao(VpaSeqSolicitacao: Integer);
begin
ESolicitacao.AInteiro:= VpaSeqSolicitacao;
ESolicitacao.Atualiza;
CPeriodo.Checked := false;
AtualizaConsulta;
ShowModal;
end;
{******************************************************************************}
procedure TFPedidoCompra.ConsultaProduto(VpaSeqProduto: Integer);
begin
VprSeqProduto := VpaSeqProduto;
DataInicial.Date := DecMes(PrimeiroDiaMes(date),6);
AtualizaConsulta;
ShowModal;
end;
{******************************************************************************}
procedure TFPedidoCompra.ConsultaPedidosOrcamentoCompra(VpaCodFilial, VpaSeqOrcamento: Integer);
begin
VprCodFilialOrcamento := VpaCodFilial;
VprSeqOrcamento := VpaSeqOrcamento;
AtualizaConsulta;
showmodal;
end;
{******************************************************************************}
procedure TFPedidoCompra.ConsultaPedidosOrdemProducao(VpaCodFilial, VpaSeqOrdemProducao, VpaSeqFracao : Integer);
begin
EFilial.AInteiro := VpaCodFilial;
EFilial.Atualiza;
EOrdemProducao.AInteiro := VpaSeqOrdemProducao;
EOrdemProducao.AInteiro;
EFracao.AInteiro := VpaSeqFracao;
EFracao.Atualiza;
AtualizaConsulta;
showmodal;
end;
{******************************************************************************}
procedure TFPedidoCompra.BFecharClick(Sender: TObject);
begin
Close;
end;
{******************************************************************************}
procedure TFPedidoCompra.AdicionaFiltros(VpaSelect: TStrings);
begin
if EPedidoCompra.AsInteger <> 0 then
VpaSelect.Add('and PCC.SEQPEDIDO = ' +EPedidoCompra.Text)
else
begin
if CPeriodo.Checked then
case ETipoPeriodo.ItemIndex of
0: VpaSelect.Add(SQLTextoDataEntreAAAAMMDD('PCC.DATPEDIDO',DataInicial.DateTime,DataFinal.DateTime,True));
1: VpaSelect.Add(SQLTextoDataEntreAAAAMMDD('PCC.DATPREVISTA',DataInicial.DateTime,DataFinal.DateTime,True));
end;
if EFornecedor.AInteiro <> 0 then
VpaSelect.Add(' AND PCC.CODCLIENTE = '+EFornecedor.Text);
case ESituacao.ItemIndex of
1: VpaSelect.Add(' AND PCC.DATAPROVACAO IS NOT NULL');
2: VpaSelect.Add(' AND PCC.DATAPROVACAO IS NULL');
3: VpaSelect.Add(' AND PCC.DATENTREGA IS NULL');
end;
case ETipo.ItemIndex of
1: VpaSelect.Add(' AND PCC.TIPPEDIDO = ''P''');
2: VpaSelect.Add(' AND PCC.TIPPEDIDO = ''T''');
end;
if EEstagio.Text <> '' then
VpaSelect.Add(' AND PCC.CODESTAGIO = '+EEstagio.Text);
if EComprador.Text <> '' then
VpaSelect.Add(' AND PCC.CODCOMPRADOR = '+EComprador.Text);
if EUsuario.AInteiro <> 0 then
VpaSelect.Add(' AND PCC.CODUSUARIO = '+EUsuario.Text);
if ESolicitacao.Text <> '' then
VpaSelect.Add(' AND EXISTS('+
' SELECT *'+
' FROM PEDIDOSOLICITACAOCOMPRA PSC'+
' WHERE PSC.CODFILIAL = PCC.CODFILIAL'+
' AND PSC.SEQSOLICITACAO = '+ESolicitacao.Text+
' AND PCC.SEQPEDIDO = PSC.SEQPEDIDO)');
if VprSeqProduto <> 0 then
VpaSelect.Add(' AND EXISTS (SELECT PCI.SEQPEDIDO '+
' FROM PEDIDOCOMPRAITEM PCI'+
' WHERE PCI.SEQPRODUTO = '+IntToStr(VprSeqProduto)+
' AND PCC.CODFILIAL = PCI.CODFILIAL'+
' AND PCC.SEQPEDIDO = PCI.SEQPEDIDO )');
if (EOrdemProducao.AInteiro <> 0) or (EFracao.AInteiro <> 0) then
begin
VpaSelect.Add('AND EXISTS '+
'( SELECT * FROM PEDIDOCOMPRAFRACAOOP FRA '+
' Where FRA.CODFILIALFRACAO = '+IntToStr(EFilial.AInteiro));
if EOrdemProducao.AInteiro <> 0 then
VpaSelect.add(' and FRA.SEQORDEM = '+IntToStr(EOrdemProducao.AInteiro));
if EFracao.AInteiro <> 0 then
VpaSelect.add(' AND FRA.SEQFRACAO = '+IntToStr(EFracao.AInteiro));
VpaSelect.add('AND FRA.CODFILIAL = PCC.CODFILIAL '+
' AND FRA.SEQPEDIDO = PCC.SEQPEDIDO )');
end;
if VprSeqNotaEntrada <> 0 then
VpaSelect.Add(' and EXISTS ( SELECT * FROM PEDIDOCOMPRANOTAFISCAL PNF'+
' WHERE PNF.SEQPEDIDO = PCC.SEQPEDIDO ' +
' AND PNF.CODFILIAL = PCC.CODFILIAL ' +
' AND PNF.CODFILIAL = ' +IntToStr(VprFilialNotaEntrada)+
' AND PNF.SEQNOTA = ' +IntToStr(VprSeqNotaEntrada)+' )' );
if VprCodFilialOrcamento <> 0 then
VpaSelect.Add(' and exists( Select 1 from ORCAMENTOPEDIDOCOMPRA OPC ' +
' Where OPC.CODFILIAL = PCC.CODFILIAL ' +
' AND OPC.SEQPEDIDO = PCC.SEQPEDIDO ' +
' AND OPC.CODFILIAL = ' +IntToStr(VprCodFilialOrcamento)+
' AND OPC.SEQORCAMENTO = '+IntToStr(VprSeqOrcamento)+')');
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.AtualizaConsulta(VpaPosicionar : Boolean = false);
Var
VpfPosicao : TBookmark;
begin
VpfPosicao := PEDIDOCOMPRACORPO.GetBookmark;
PRODUTOPEDIDO.Close;
PEDIDOCOMPRACORPO.close;
PEDIDOCOMPRACORPO.SQL.Clear;
PEDIDOCOMPRACORPO.SQL.Add('SELECT'+
' PCC.CODCLIENTE, PCC.CODFORMAPAGAMENTO, PCC.SEQPEDIDO, PCC.DATPEDIDO, PCC.DATPREVISTA, PCC.DATENTREGA,'+
' PCC.DATRENEGOCIADO, PCC.CODCONDICAOPAGAMENTO, '+
' CLI.C_NOM_CLI, PCC.VALTOTAL, CPA.C_NOM_PAG,'+
' PCC.CODFILIAL, PCC.DATAPROVACAO,PCC.TIPPEDIDO, '+
' EST.NOMEST, PCC.CODESTAGIO, PCC.DATPAGAMENTOANTECIPADO,'+
' USUAPR.C_NOM_USU USUAPROVACAO,'+
' USU.C_NOM_USU, COM.NOMCOMPRADOR'+
' FROM'+
' PEDIDOCOMPRACORPO PCC, CADCLIENTES CLI, CADCONDICOESPAGTO CPA,'+
' CADUSUARIOS USUAPR, ESTAGIOPRODUCAO EST, CADUSUARIOS USU,'+
' COMPRADOR COM'+
' WHERE '+SQLTextoRightJoin('PCC.CODCLIENTE','CLI.I_COD_CLI')+
' AND '+SQLTextoRightJoin('PCC.CODCONDICAOPAGAMENTO','CPA.I_COD_PAG')+
' AND '+SQLTextoRightJoin('PCC.CODUSUARIOAPROVACAO','USUAPR.I_COD_USU')+
' AND USU.I_COD_USU = PCC.CODUSUARIO'+
' AND '+SQLTextoRightJoin('PCC.CODESTAGIO','EST.CODEST')+
' AND '+SQLTextoRightJoin('PCC.CODCOMPRADOR','COM.CODCOMPRADOR')+
' AND PCC.CODFILIAL = '+IntToStr(Varia.CodigoEmpFil));
AdicionaFiltros(PEDIDOCOMPRACORPO.SQL);
PEDIDOCOMPRACORPO.SQL.Add(VprOrdem);
GPedidoCorpo.ALinhaSQLOrderBy:= PEDIDOCOMPRACORPO.SQL.Count-1;
PEDIDOCOMPRACORPO.Open;
if VpaPosicionar then
begin
try
PEDIDOCOMPRACORPO.GotoBookmark(VpfPosicao);
except
end;
PEDIDOCOMPRACORPO.FreeBookmark(vpfPosicao);
end;
if CAtualiza.Checked then
AtualizaTotais;
end;
{******************************************************************************}
procedure TFPedidoCompra.InicializaTela;
begin
CPeriodo.Checked:= True;
ETipoPeriodo.ItemIndex:= 0;
ESituacao.ItemIndex:= 0;
EComprador.AInteiro:= Varia.CodComprador;
EComprador.Atualiza;
DataInicial.DateTime:= PrimeiroDiaMes(Date);
DataFinal.DateTime:= UltimoDiaMes(Date);
EFornecedor.Clear;
CAtualiza.Checked:= False;
end;
{******************************************************************************}
procedure TFPedidoCompra.DataInicialCloseUp(Sender: TObject);
begin
AtualizaConsulta;
end;
procedure TFPedidoCompra.Duplicar1Click(Sender: TObject);
begin
if PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger <> 0 then
begin
FNovoPedidoCompra:= TFNovoPedidoCompra.CriarSDI(Application,'',True);
if FNovoPedidoCompra.Duplicar(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger) then
AtualizaConsulta(true);
FNovoPedidoCompra.Free;
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.PEDIDOCOMPRACORPOAfterScroll(DataSet: TDataSet);
begin
PosItensPedido;
end;
procedure TFPedidoCompra.PEDIDOCOMPRACORPOCalcFields(DataSet: TDataSet);
begin
if PEDIDOCOMPRACORPOTIPPEDIDO.AsString = 'P' then
PEDIDOCOMPRACORPOTIPOPEDIDO.AsString := 'PEDIDO'
else
PEDIDOCOMPRACORPOTIPOPEDIDO.AsString := 'TERCEIRIZACAO';
end;
{******************************************************************************}
procedure TFPedidoCompra.PosItensPedido;
begin
if not PEDIDOCOMPRACORPOSEQPEDIDO.IsNull then
begin
PRODUTOPEDIDO.Close;
PRODUTOPEDIDO.SQL.Clear;
PRODUTOPEDIDO.SQL.Add('SELECT'+
' PRO.C_COD_PRO, PRO.C_NOM_PRO, COR.NOM_COR, PCI.DESREFERENCIAFORNECEDOR,'+
' PCI.QTDPRODUTO, PCI.QTDBAIXADO, PCI.DESUM, PCI.VALUNITARIO, PCI.VALTOTAL, PCI.QTDSOLICITADA,' +
' PCI.QTDCHAPA, PCI.LARCHAPA, PCI.COMCHAPA '+
' FROM PEDIDOCOMPRAITEM PCI, CADPRODUTOS PRO, COR COR'+
' WHERE'+
' PRO.I_SEQ_PRO = PCI.SEQPRODUTO'+
' AND '+SQLTextoRightJoin('PCI.CODCOR','COR.COD_COR')+
' AND PCI.CODFILIAL = '+PEDIDOCOMPRACORPOCODFILIAL.AsString+
' AND PCI.SEQPEDIDO = '+PEDIDOCOMPRACORPOSEQPEDIDO.AsString);
if VprSeqProduto <> 0 then
PRODUTOPEDIDO.SQL.Add('AND PCI.SEQPRODUTO = '+ IntToStr(VprSeqProduto));
PRODUTOPEDIDO.SQL.Add(VprOrdemItens);
GPedidoItem.ALinhaSQLOrderBy:= PRODUTOPEDIDO.SQL.Count-1;
PRODUTOPEDIDO.Open;
end
else
PRODUTOPEDIDO.Close;
end;
procedure TFPedidoCompra.SpeedButton2Click(Sender: TObject);
begin
if LocalizaProduto then
AtualizaConsulta(false);
end;
{******************************************************************************}
procedure TFPedidoCompra.AtualizaTotais;
begin
EQuantidade.AValor:= 0;
EValor.AValor:= 0;
if CAtualiza.Checked then
begin
Aux.SQL.Clear;
Aux.SQL.Add('SELECT COUNT(PCC.SEQPEDIDO) QTD, SUM(PCC.VALTOTAL) VALOR'+
' FROM PEDIDOCOMPRACORPO PCC'+
' WHERE SEQPEDIDO = SEQPEDIDO ');
AdicionaFiltros(Aux.SQL);
Aux.Open;
EQuantidade.AValor:= Aux.FieldByName('QTD').AsInteger;
EValor.AValor:= Aux.FieldByName('VALOR').AsFloat;
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.GPedidoCorpoDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer;
Column: TColumn; State: TGridDrawState);
begin
if (State = [gdSelected]) then
begin
GPedidoCorpo.Canvas.Font.Color:= clWhite;
GPedidoCorpo.DefaultDrawDataCell(Rect, GPedidoCorpo.columns[datacol].field, State);
end
else
begin
if (PEDIDOCOMPRACORPOCODESTAGIO.AsInteger = varia.EstagioFinalCompras)then
begin
GPedidoCorpo.Canvas.Font.Color:= clGreen;
GPedidoCorpo.DefaultDrawDataCell(Rect, GPedidoCorpo.columns[datacol].field, State);
end
else
if (PEDIDOCOMPRACORPOCODESTAGIO.AsInteger = varia.EstagioComprasEntregaParcial)then
begin
GPedidoCorpo.Canvas.Font.Color:= clBlue;
GPedidoCorpo.DefaultDrawDataCell(Rect, GPedidoCorpo.columns[datacol].field, State);
end
else
if ( PEDIDOCOMPRACORPODATPREVISTA.AsDateTime < Date) and (PEDIDOCOMPRACORPOCODESTAGIO.AsInteger = Varia.EstagioComprasAguardandoEntregaFornecedor) then
begin
GPedidoCorpo.Canvas.Font.Color:= clRed;
GPedidoCorpo.DefaultDrawDataCell(Rect, GPedidoCorpo.columns[datacol].field, State);
end
else
if (PEDIDOCOMPRACORPOCODESTAGIO.AsInteger = varia.EstagioCancelamentoPedidoCompra)then
begin
GPedidoCorpo.Canvas.Font.Color:= clAqua;
GPedidoCorpo.DefaultDrawDataCell(Rect, GPedidoCorpo.columns[datacol].field, State);
end;
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.GPedidoCorpoOrdem(Ordem: String);
begin
VprOrdem:= Ordem;
end;
{******************************************************************************}
procedure TFPedidoCompra.GPedidoItemOrdem(Ordem: String);
begin
VprOrdemItens:= Ordem;
end;
{******************************************************************************}
procedure TFPedidoCompra.CAtualizaClick(Sender: TObject);
begin
AtualizaTotais;
end;
{******************************************************************************}
procedure TFPedidoCompra.EFornecedorRetorno(Retorno1, Retorno2: String);
begin
DataInicialCloseUp(EFornecedor);
end;
{******************************************************************************}
procedure TFPedidoCompra.BCadastrarClick(Sender: TObject);
begin
FNovoPedidoCompra:= TFNovoPedidoCompra.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoPedidoCompra'));
if FNovoPedidoCompra.NovoPedido then
AtualizaConsulta;
FNovoPedidoCompra.Free;
end;
procedure TFPedidoCompra.BCancelarClick(Sender: TObject);
begin
if PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger <> 0 then
begin
FunPedidoCompra.AlteraEstagioPedidoCompra(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger,varia.EstagioCancelamentoPedidoCompra,'Cancelamento');
AtualizaConsulta;
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.BExcluirClick(Sender: TObject);
begin
if PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger <> 0 then
begin
FNovoPedidoCompra:= TFNovoPedidoCompra.CriarSDI(Application,'',True);
if FNovoPedidoCompra.Apagar(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger) then
AtualizaConsulta;
FNovoPedidoCompra.Free;
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.BConsultarClick(Sender: TObject);
begin
if PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger <> 0 then
begin
FNovoPedidoCompra:= TFNovoPedidoCompra.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoPedidoCompra'));
FNovoPedidoCompra.Consultar(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger);
FNovoPedidoCompra.Free;
end;
end;
procedure TFPedidoCompra.BduplicarClick(Sender: TObject);
begin
end;
{******************************************************************************}
procedure TFPedidoCompra.BAlterarClick(Sender: TObject);
begin
if PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger <> 0 then
begin
FNovoPedidoCompra:= TFNovoPedidoCompra.CriarSDI(Application,'',True);
if FNovoPedidoCompra.Alterar(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger) then
AtualizaConsulta(true);
FNovoPedidoCompra.Free;
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.mnAprovarPedidoClick(Sender: TObject);
var
VpfResultado: String;
begin
if PEDIDOCOMPRACORPODATAPROVACAO.IsNull then
begin
if Confirmacao('Tem certeza que deseja aprovar este pedido?') then
begin
VpfResultado:= FunPedidoCompra.AprovarPedido(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger);
if VpfResultado = '' then
begin
Informacao('Pedido aprovado com sucesso.');
VpfResultado:= FunPedidoCompra.AlteraEstagioPedidoCompra(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger,varia.EstagioComprasAprovado,'Aprovação');
AtualizaConsulta;
end
else
aviso(VpfResultado);
end;
end
else
aviso('Este pedido já foi aprovado!')
end;
{******************************************************************************}
procedure TFPedidoCompra.Baixar1Click(Sender: TObject);
var
VpfResultado: String;
begin
if PEDIDOCOMPRACORPODATPAGAMENTOANTECIPADO.IsNull then
begin
if Confirmacao('Deseja baixar o pagamento antecipado deste pedido?') then
begin
VpfResultado:= FunPedidoCompra.BaixarPagamentoAntecipado(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger);
if VpfResultado = '' then
begin
Informacao('Pagamento antecipado baixado com sucesso.');
AtualizaConsulta;
end
else
aviso(VpfResultado);
end;
end
else
Informacao('Este pagamento já foi baixado.');
end;
procedure TFPedidoCompra.AlterarEstgio1Click(Sender: TObject);
begin
FAlteraEstagioPedidoCompra := TFAlteraEstagioPedidoCompra.CriarSDI(self,'',FPrincipal.VerificaPermisao('FAlteraEstagioPedidoCompra'));
if FAlteraEstagioPedidoCompra.AlteraEstagioPedido(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger) then
AtualizaConsulta(True);
FAlteraEstagioPedidoCompra.free;
end;
{******************************************************************************}
procedure TFPedidoCompra.ConcluirPedidoCompra1Click(Sender: TObject);
var
VpfResultado: String;
begin
if PEDIDOCOMPRACORPODATENTREGA.IsNull then
begin
if Confirmacao('Tem certeza que deseja concluir o pedido?') then
begin
VpfResultado:= FunPedidoCompra.ConcluiPedidoCompra(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger);
if VpfResultado = '' then
begin
Informacao('Pedido concluído com sucesso.');
AtualizaConsulta;
end
else
aviso(VpfResultado);
end;
end
else
Informacao('Pedido já concluído.');
end;
{******************************************************************************}
procedure TFPedidoCompra.ConfiguraPermissaoUsuario;
begin
GPedidoItem.Columns[4].Visible := Config.ControlarEstoquedeChapas;
GPedidoItem.Columns[5].Visible := Config.ControlarEstoquedeChapas;
GPedidoItem.Columns[6].Visible := Config.ControlarEstoquedeChapas;
GPedidoItem.Columns[2].Visible := Config.EstoquePorCor;
if not((puAdministrador in varia.PermissoesUsuario) or (puESCompleto in varia.PermissoesUsuario)) then
begin
AlterarVisibleDet([BCadastrar],false);
AlterarVisibleDet([BExcluir],false);
if (puESCadastrarPedidoCompra in varia.PermissoesUsuario) then
AlterarVisibleDet([BCadastrar],true);
if (puESExcluirPedidoCompra in varia.PermissoesUsuario) then
AlterarVisibleDet([BExcluir],true);
end;
mnAprovarPedido.Enabled := (puESAprovaPedidoCompra in varia.PermissoesUsuario);
end;
{******************************************************************************}
procedure TFPedidoCompra.BImprimirClick(Sender: TObject);
begin
if PEDIDOCOMPRACORPOCODFILIAL.AsInteger <> 0 then
begin
dtRave := TdtRave.create(self);
dtRave.ImprimePedidoCompra(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger,true);
dtRave.free;
end;
end;
{******************************************************************************}
function TFPedidoCompra.ExisteProduto: Boolean;
var
VpfUM,
VpfNomProduto: String;
begin
Result:= FunProdutos.ExisteProduto(EProduto.Text,VprSeqProduto,VpfNomProduto,VpfUM);
if Result then
Label21.Caption:= VpfNomProduto
else
Label21.Caption:= '';
end;
{******************************************************************************}
procedure TFPedidoCompra.ExtornarPedidoCompra1Click(Sender: TObject);
var
VpfResultado: String;
begin
if Confirmacao('Tem certeza que deseja extornar o pedido?') then
begin
if not PEDIDOCOMPRACORPODATAPROVACAO.IsNull then
begin
VpfResultado:= FunPedidoCompra.ExtornaPedidoCompra(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger);
if VpfResultado = '' then
begin
aviso('Pedido de compra extornado com sucesso.');
AtualizaConsulta;
end
else
aviso(VpfResultado)
end
else
aviso('Pedido de compra já extornado.');
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.EOrdemProducaoSelect(Sender: TObject);
begin
EOrdemProducao.ASelectLocaliza.Text := 'Select ORD.SEQORD, ORD.DATEMI, CLI.C_NOM_CLI from ORDEMPRODUCAOCORPO ORD, CADCLIENTES CLI '+
' Where ORD.EMPFIL = '+ IntToStr(EFilial.AInteiro)+
' and ORD.CODCLI = CLI.I_COD_CLI '+
' AND CLI.C_NOM_CLI like ''@%''';
EOrdemProducao.ASelectValida.Text := 'Select ORD.SEQORD, ORD.DATEMI, CLI.C_NOM_CLI From ORDEMPRODUCAOCORPO ORD, CADCLIENTES CLI '+
' Where ORD.EMPFIL = '+ IntToStr(EFilial.AInteiro)+
' and ORD.CODCLI = CLI.I_COD_CLI '+
' AND ORD.SEQORD = @';
end;
{******************************************************************************}
procedure TFPedidoCompra.EFracaoSelect(Sender: TObject);
begin
EFracao.ASelectLocaliza.Text := 'SELECT FRA.SEQFRACAO, FRA.DATENTREGA, FRA.QTDPRODUTO, FRA.CODESTAGIO from FRACAOOP FRA '+
' Where FRA.SEQFRACAO LIKE ''@%'''+
' AND FRA.CODFILIAL = '+IntToStr(EFilial.AInteiro)+
' and FRA.SEQORDEM = '+IntToStr(EOrdemProducao.AInteiro);
EFracao.ASelectValida.Text := 'SELECT FRA.SEQFRACAO, FRA.DATENTREGA, FRA.QTDPRODUTO, FRA.CODESTAGIO from FRACAOOP FRA '+
' Where FRA.SEQFRACAO = @ '+
' AND FRA.CODFILIAL = '+IntToStr(EFilial.AInteiro)+
' and FRA.SEQORDEM = '+IntToStr(EOrdemProducao.AInteiro);
end;
{******************************************************************************}
procedure TFPedidoCompra.GerarNotaFiscaldeentrada1Click(Sender: TObject);
var
VpfListaPedidos: TList;
VpfDNota: TRBDNotaFiscalFor;
VpfArquivoXML : String;
begin
VpfArquivoXML := '';
if TBitBtn(sender).Tag = 20 then
begin
if OpenXML.Execute then
VpfArquivoXML := OpenXML.FileName
else
exit;
end;
VpfListaPedidos:= TList.Create;
CarDClassePedidos(VpfListaPedidos);
VpfDNota:= TRBDNotaFiscalFor.cria;
FunNotaFor.GeraNotadosPedidos(VpfListaPedidos,VpfDNota);
FNovaNotaFiscaisFor:= TFNovaNotaFiscaisFor.CriarSDI(Application,'',True);
if FNovaNotaFiscaisFor.NovaNotaPedido(VpfDNota,VpfListaPedidos,VpfArquivoXML) then
AtualizaConsulta(true);
FNovaNotaFiscaisFor.Free;
FreeTObjectsList(VpfListaPedidos);
VpfListaPedidos.Free;
VpfDNota.Free
end;
{******************************************************************************}
procedure TFPedidoCompra.CarDClassePedidos(VpaListaPedidos: TList);
var
VpfLaco: Integer;
VpfBookmark: TBookmark;
VpfDPedidoCompraCorpo: TRBDPedidoCompraCorpo;
begin
if GPedidoCorpo.SelectedRows.Count = 0 then
begin
if PEDIDOCOMPRACORPOCODFILIAL.AsInteger <> 0 then
begin
VpfDPedidoCompraCorpo:= TRBDPedidoCompraCorpo.Cria;
FunPedidoCompra.CarDPedidoCompra(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,
PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger,
VpfDPedidoCompraCorpo);
InsereNaListaPedidos(VpaListaPedidos,VpfDPedidoCompraCorpo);
end;
end
else
for VpfLaco:= 0 to GPedidoCorpo.SelectedRows.Count-1 do
begin
VpfBookmark:= TBookmark(GPedidoCorpo.SelectedRows.Items[VpfLaco]);
PEDIDOCOMPRACORPO.GotoBookmark(VpfBookmark);
VpfDPedidoCompraCorpo:= TRBDPedidoCompraCorpo.Cria;
FunPedidoCompra.CarDPedidoCompra(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,
PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger,
VpfDPedidoCompraCorpo);
InsereNaListaPedidos(VpaListaPedidos,VpfDPedidoCompraCorpo);
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.InsereNaListaPedidos(VpaListaPedidos: TList; VpaDPedidoCompraCorpo: TRBDPedidoCompraCorpo);
var
VpfLaco: Integer;
VpfDPedidoCompraCorpo: TRBDPedidoCompraCorpo;
VpfInseriu: Boolean;
begin
VpfInseriu:= False;
for VpfLaco:= 0 to VpaListaPedidos.Count-1 do
begin
VpfDPedidoCompraCorpo:= TRBDPedidoCompraCorpo(VpaListaPedidos.Items[VpfLaco]);
if VpaDPedidoCompraCorpo.DatPedido < VpfDPedidoCompraCorpo.DatPedido then
begin
VpaListaPedidos.Insert(VpfLaco,VpaDPedidoCompraCorpo);
VpfInseriu:= True;
Break;
end;
end;
if not VpfInseriu then
VpaListaPedidos.Add(VpaDPedidoCompraCorpo);
end;
{******************************************************************************}
function TFPedidoCompra.LocalizaProduto: Boolean;
var
VpfCodProduto,
VpfNomProduto,
VpfDesUM,
VpfClaFiscal: String;
begin
FlocalizaProduto := TFlocalizaProduto.criarSDI(Application,'',FPrincipal.VerificaPermisao('FlocalizaProduto'));
Result:= FlocalizaProduto.LocalizaProduto(VprSeqProduto,VpfCodProduto,VpfNomProduto,VpfDesUM,VpfClaFiscal);
FlocalizaProduto.free;
if Result then
begin
EProduto.Text:= VpfCodProduto;
Label21.Caption:= VpfNomProduto;
end
else
begin
EProduto.Text:= '';
Label21.Caption:= '';
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.ImprimirPedidosPendentes1Click(Sender: TObject);
begin
dtRave := TdtRave.create(self);
dtRave.ImprimePedidoCompraPendente(EFornecedor.AInteiro);
dtRave.free;
end;
procedure TFPedidoCompra.BFiltrosClick(Sender: TObject);
begin
if BFiltros.Caption = '>>' then
begin
PanelColor1.Height := EComprador.Top + EComprador.Height + 5;
BFiltros.Caption := '<<';
end
else
begin
PanelColor1.Height := EPedidoCompra.Top + EPedidoCompra.Height + 5;
BFiltros.Caption := '>>';
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.EPedidoCompraKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
case key of
13 : AtualizaConsulta;
end;
end;
procedure TFPedidoCompra.EProdutoExit(Sender: TObject);
begin
ExisteProduto;
AtualizaConsulta(false);
end;
{******************************************************************************}
procedure TFPedidoCompra.EProdutoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case Key of
13: begin
if ExisteProduto then
AtualizaConsulta(false)
else
if LocalizaProduto then
AtualizaConsulta(false);
end;
114: if LocalizaProduto then
AtualizaConsulta(false);
end;
end;
procedure TFPedidoCompra.ETipoChange(Sender: TObject);
begin
end;
{******************************************************************************}
procedure TFPedidoCompra.ConsultarNotasFiscais1Click(Sender: TObject);
begin
FunPedidoCompra.ConsultaNotasFiscais(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger);
end;
{******************************************************************************}
procedure TFPedidoCompra.ConsultaSolicitaoCompra1Click(Sender: TObject);
begin
FSolicitacaoCompra := TFSolicitacaoCompra.CriarSDI(self,'',true);
FSolicitacaoCompra.ConsultaPedidoCompa(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger);
FSolicitacaoCompra.free;
end;
{******************************************************************************}
procedure TFPedidoCompra.ConsultaAgendamento1Click(Sender: TObject);
begin
if PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger <> 0 then
begin
FAgendamentos:= TFAgendamentos.CriarSDI(self,'',FPrincipal.VerificaPermisao('FAgendamentos'));
FAgendamentos.ConsultaPedidoCompra(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger);
FAgendamentos.free;
end;
end;
{******************************************************************************}
procedure TFPedidoCompra.ConsultaNotaEntrada(VpaCodFilial, VpaSeqNota: Integer);
begin
VprFilialNotaEntrada := VpaCodFilial;
VprSeqNotaEntrada := VpaSeqNota;
CPeriodo.Checked := false;
AtualizaConsulta;
showmodal;
end;
{******************************************************************************}
procedure TFPedidoCompra.ConsultaOramentoCompra1Click(Sender: TObject);
begin
if PEDIDOCOMPRACORPOCODFILIAL.AsInteger <> 0 then
begin
FOrcamentoCompras := TFOrcamentoCompras.criarSDI(Application,'',FPrincipal.VerificaPermisao('FOrcamentoCompras'));
FOrcamentoCompras.ConsultaOrcamentosPedido(PEDIDOCOMPRACORPOCODFILIAL.AsInteger,PEDIDOCOMPRACORPOSEQPEDIDO.AsInteger);
FOrcamentoCompras.free;
end;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFPedidoCompra]);
end.
|
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
|
unit GC.LaserCutBoxes.Box.Dividers;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TBoxDivider }
TBoxDivider = class(TObject)
private
FWidth: Double;
FHeight: Double;
FTabsWidth: Double;
FLegend: String;
procedure SetHeight(Value: Double);
procedure SetLegend(Value: String);
procedure SetWidth(Value: Double);
procedure SetTabsWidth(Value: Double);
procedure ReCalculate;
protected
public
constructor Create;
destructor Destroy; override;
property Width: Double read FWidth write SetWidth;
property Height: Double read FHeight write SetHeight;
property TabsWidth: Double read FTabsWidth write SetTabsWidth;
property Legend: String read FLegend write SetLegend;
end;
implementation
{ TBoxDivider }
procedure TBoxDivider.SetHeight(Value: Double);
begin
if FHeight = Value then Exit;
FHeight := Value;
ReCalculate;
end;
procedure TBoxDivider.SetLegend(Value: String);
begin
if FLegend = Value then Exit;
FLegend := Value;
ReCalculate;
end;
procedure TBoxDivider.SetWidth(Value: Double);
begin
if FWidth = Value then Exit;
FWidth := Value;
ReCalculate;
end;
procedure TBoxDivider.SetTabsWidth(Value: Double);
begin
if FTabsWidth = Value then Exit;
FTabsWidth := Value;
ReCalculate;
end;
procedure TBoxDivider.ReCalculate;
begin
//
end;
constructor TBoxDivider.Create;
begin
//
end;
destructor TBoxDivider.Destroy;
begin
inherited Destroy;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMS.Services;
interface
uses System.SysUtils, System.Classes, EMS.ResourceAPI, EMS.ResourceTypes,
System.JSON, System.Generics.Collections;
type
TEMSApplicationService = class
public
class procedure AddStartupNotification(AProc: TProc); // FIFO order
class procedure AddShutdownNotification(AProc: TProc); // LIFO order
end;
TEMSServices = class
public
class function GetService<T: IInterface>: T;
class function TryGetService<T: IInterface>(out Intf: T): Boolean;
end;
IEMSLoggingService = interface;
TEMSLoggingService = class
private
class function GetLoggingEnabled: Boolean; static;
class function GetService: IEMSLoggingService; static;
public
class procedure Log(const ACategory: string; const AJSON: TJSONObject);
class property LoggingEnabled: Boolean read GetLoggingEnabled;
end;
IEMSServices = interface(IInterface)
['{E9E681C2-3399-4D55-A294-F20E2A59BE35}']
function SupportsService(const Service: TGUID): Boolean;
function GetService(const Service: TGUID): IInterface; overload;
function TryGetService(const Service: TGUID; out Svc): Boolean; overload;
end;
IEMSEndPointSegmentsService = interface
['{15ECD41C-D332-48BA-9C3E-67152EF24205}']
procedure ExtractSegments(const AString: string; const AList: TEMSEndPointSegmentList);
function CountSegments(const AValue: string): Integer;
end;
IEMSApplicationService = interface
['{D5D6FAF8-9AFE-4A9A-81BB-659016EDB179}']
/// <summary>Used internally to tell this service to send startup notifications</summary>
procedure Startup;
/// <summary>Used internally to tell this service to send shutdown notifications</summary>
procedure Shutdown;
procedure AddStartupNotification(AProc: TProc); // FIFO order
procedure AddShutdownNotification(AProc: TProc); // LIFO order
end;
TEMSLoggingOutputProc = reference to procedure(const ACategory: string; const AJSON: TJSONObject);
TEMSLoggingEnabledFunc = TFunc<Boolean>;
IEMSLoggingServiceSetup = interface
['{261E2580-D991-4E1B-9FFF-D68EBD2DEB6E}']
procedure SetupCustomOutput(const AEnabled: TEMSLoggingEnabledFunc;
const AOutput: TEMSLoggingOutputProc; const ASynchronize: Boolean);
procedure SetupFileOutput(const AFileName: string; const AAppend: Boolean);
end;
IEMSLoggingService = interface
['{261E2580-D991-4E1B-9FFF-D68EBD2DEB6F}']
function GetLoggingEnabled: Boolean;
procedure Log(const ACategory: string; const AJSON: TJSONObject);
property LoggingEnabled: Boolean read GetLoggingEnabled;
end;
/// <summary>Query parameter name/value pair</summary>
TEMSResourceRequestQueryParam = TPair<string, string>;
/// <summary>Array of query parameters</summary>
TEMSResourceRequestQueryParams = TArray<TPair<string, string>>;
/// <summary>Array of URL segments</summary>
TEMSResourceRequestSegments = TArray<string>;
/// <summary>Context of an EMS Resource request to the EMS Server.</summary>
IEMSResourceRequestContext = interface
end;
/// <summary>Content of an EMS Resource request.</summary>
IEMSResourceRequestContent = interface
end;
/// <summary>Response to a resource request that you executed.</summary>
IEMSResourceResponseContent = interface
/// <summary>Get the HTTP status code, such as 200</summary>
function GetStatusCode: Integer;
/// <summary>Get the content type such as "application/json"</summary>
function GetContentType: string;
/// <summary>Try to get a stream from the response. False is returned if the response does not have content.</summary>
function TryGetStream(out AStream: TStream): Boolean; overload;
/// <summary>Try to get a stream from the response. False is returned if the response does not have content.</summary>
function TryGetStream(out AStream: TStream; out AContentType: string): Boolean; overload;
/// <summary>Try to get a JSON object from the response. False is returned if the response does not provide this type.</summary>
function TryGetObject(out AJSONObject: TJSONObject): Boolean;
/// <summary>Try to get a JSON array from the response. False is returned if the response does not provide this type.</summary>
function TryGetArray(out AJSONArray: TJSONArray): Boolean;
/// <summary>Try to get a JSON value from the response. False is returned if the response does not provide this type.</summary>
function TryGetValue(out AJSONValue: TJSONValue): Boolean;
/// <summary>Try to get an byte array from the response. False is returned if the response does not have content.</summary>
function TryGetBytes(out ABytes: TBytes): Boolean;
/// <summary>Try to get a stream from the response. An exception is raised if the response does not have content.</summary>
function GetStream: TStream;
/// <summary>Try to get a JSON object from the response. An exception is raised if the response does not provide this type.</summary>
function GetObject: TJSONObject;
/// <summary>Try to get a JSON array from the response. An exception is raised if the response does not provide this type.</summary>
function GetArray: TJSONArray;
/// <summary>Try to get a JSON value from the response. An exception is raised if the response does not provide this type.</summary>
function GetValue: TJSONValue;
/// <summary>Try to get an byte array from the response. An exception is raised if the response does not have content.</summary>
function GetBytes: TBytes;
/// <summary>Get the content type such as "application/json"</summary>
property ContentType: string read GetContentType;
/// <summary>Get the HTTP status code, such as 200</summary>
property StatusCode: Integer read GetStatusCode;
end;
/// <summary>Base interface for services that make requests to
/// resources.</summary>
IEMSResourceRequest = interface
/// <summary>Create a context using the context parameter passed to aa custom resource endpoint. If the TEndpointContext identifies a user, the result will identify then same user.</summary>
function CreateRequestContext(const AContext: TEndpointContext): IEMSResourceRequestContext;
/// <summary>Create content/payload from a JSON value.</summary>
function CreateRequestContent(const AJSON: TJSONValue): IEMSResourceRequestContent; overload;
/// <summary>Create content/payload from a stream.</summary>
function CreateRequestContent(const AContentType: string; const AStream: TStream): IEMSResourceRequestContent; overload;
/// <summary>Create content/payload from a byte array.</summary>
function CreateRequestContent(const AContentType: string; const ABytes: TBytes): IEMSResourceRequestContent; overload;
/// <summary>Execute a resource request that passes content/payload. Typically this version of Execute is used for PUT and POST requests.</summary>
function Execute(const AContext: IEMSResourceRequestContext;
const AMethodType: TEndpointRequest.TMethod; const AResourceName: string;
const ASegments: TEMSResourceRequestSegments;
const AQueryParams: TEMSResourceRequestQueryParams;
const ARequestContent: IEMSResourceRequestContent): IEMSResourceResponseContent; overload;
/// <summary>Execute a resource request that does not pass content/payload. Typically this version of Execute is used for GET and DELETE requests.</summary>
function Execute(const AContext: IEMSResourceRequestContext;
AMethodType: TEndpointRequest.TMethod; const AResourceName: string;
const ASegments: TEMSResourceRequestSegments;
const AQueryParams: TEMSResourceRequestQueryParams): IEMSResourceResponseContent; overload;
/// <summary>Execute DELETE resource request.</summary>
function Delete(const AContext: IEMSResourceRequestContext; const AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams): IEMSResourceResponseContent;
/// <summary>Execute GET resource request.</summary>
function Get(const AContext: IEMSResourceRequestContext; const AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams): IEMSResourceResponseContent;
/// <summary>Execute PATCH resource request.</summary>
function Patch(const AContext: IEMSResourceRequestContext; const AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams;
const ARequestContent: IEMSResourceRequestContent): IEMSResourceResponseContent;
/// <summary>Execute POST resource request.</summary>
function Post(const AContext: IEMSResourceRequestContext; const AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams;
const ARequestContent: IEMSResourceRequestContent): IEMSResourceResponseContent;
/// <summary>Execute PUT resource request.</summary>
function Put(const AContext: IEMSResourceRequestContext; const AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams;
const ARequestContent: IEMSResourceRequestContent): IEMSResourceResponseContent;
end;
/// <summary>Service for executing internal EMS resource endpoint requests
/// from another custom EMS resource endpoint implementations.</summary>
IEMSInternalResourceRequestService = interface(IEMSResourceRequest)
['{0C98920E-E524-4917-8F00-AC968C0A9D13}']
end;
/// <summary>Interface that provides methods to execute EMS Edge Module
/// resource request from custom EMS Resource endpoint
/// implementations.</summary>
IEMSModuleResourceRequest = interface(IEMSResourceRequest)
function GetModuleName: string;
/// <summary>Get the name of the module.</summary>
property ModuleName: string read GetModuleName;
end;
/// <summary>Service interface for executing EMS Edge Module resource requests
/// from custom EMS Resource endpoint implementation.</summary>
IEMSModuleResourceRequestService = interface
['{24772850-762F-43FA-9B9E-0818750F0E06}']
function CreateRequest(const AModuleName: string): IEMSModuleResourceRequest;
end;
/// <summary>Supports internal executing of built-in EMS Resource endpoints
/// from a custom EMS Resource endpoint implementation.</summary>
TEMSInternalAPI = class
private
FContext: IEMSResourceRequestContext;
FService: IEMSInternalResourceRequestService;
public type
/// <summary>Names used to format JSON objects which are passed to built-in endpoints.</summary>
TJSONNames = record
public const
UserName = 'username';
Password = 'password';
SessionToken = 'sessionToken';
Error = 'error';
Description = 'description';
UserID = '_id';
GroupName = 'groupname';
InstallationID = '_id';
MetaData = '_meta';
MetaCreated = 'created';
MetaUpdated = 'updated';
MetaCreator = 'creator';
PushWhere = 'where';
PushChannels = 'channels';
PushData = 'data';
GroupUsers = 'users';
end;
/// <summary>Names of resources and URL segments which are used to execute build-in endpoints</summary>
TSegmentNames = record
public const
Users = 'users';
Groups = 'groups';
Installations = 'installations';
Edgemodules = 'edgemodules';
Resources = 'resources';
Login = 'login';
Signup = 'signup';
Logout = '_logout';
Me = 'me';
Push = 'push';
end;
/// <summary>Query parameter name/value pair.</summary>
TQueryParam = TPair<string, string>;
/// <summary>Array of query parameters.</summary>
TQueryParams = TArray<TQueryParam>;
/// <summary>Names used in built-in endpoint query parameters.</summary>
TQueryParamNames = record
public const
Order = 'order';
Where = 'where';
Limit = 'limit';
Skip = 'skip';
end;
public
/// <summary>Create an api class that uses the context passed to a custom endpoint.</summary>
constructor Create(const AContext: TEndpointContext);
// Users
/// <summary>Add a new EMS user. User fields parameter my be nil.</summary>
function AddUser(const AUserName, APassword: string;
const AUserFields: TJSONObject): IEMSResourceResponseContent; overload;
/// <summary>Add a new EMS user. JSON parameter must include username and password.</summary>
function AddUser(const AJSONBody: TJSONObject): IEMSResourceResponseContent; overload;
/// <summary>Delete an EMS user. False is returned if the user was not found.</summary>
function DeleteUser(const AObjectID: string; out AResponse: IEMSResourceResponseContent): Boolean; overload;
/// <summary>Delete an EMS user. False is returned if the user was not found.</summary>
function DeleteUser(const AObjectID: string): Boolean; overload;
/// <summary>Login an EMS user.</summary>
function LoginUser(const AUserName, APassword: string): IEMSResourceResponseContent; overload;
/// <summary>Login an EMS user. JSON parameter must include username and password.</summary>
function LoginUser(const AJSONLogin: TJSONObject): IEMSResourceResponseContent; overload;
/// <summary>Logout a user. This causes the server-side session id to be cleared. All clients will need to re-login.</summary>
function Logout: IEMSResourceResponseContent; overload;
/// <summary>Get the user with a give user name. False is returned if the user was not found.</summary>
function QueryUserName(const AUserName: string;
out AResponse: IEMSResourceResponseContent): Boolean; overload;
/// <summary>>Get the user with a give user name. False is returned if the user was not found.</summary>
function QueryUserName(const AUserName: string): Boolean; overload;
/// <summary>Retreive users using query parameters. If the parameters are empty then the result is unfiltered and unordered.</summary>
function QueryUsers(const AQuery: TQueryParams): IEMSResourceResponseContent; overload;
/// <summary>Get the properties of a user. False is returned if the user was not found.</summary>
function RetrieveUser(const AObjectID: string; out AResponse: IEMSResourceResponseContent): Boolean;
/// <summary>Signup a user. The response will include the session id.</summary>
function SignupUser(const AUserName, APassword: string;
const AUserFields: TJSONObject): IEMSResourceResponseContent; overload;
/// <summary>Signup a user. The JSON parameter must include the username and password. The response will include the session id.</summary>
function SignupUser(const AJSONBody: TJSONObject): IEMSResourceResponseContent; overload;
/// <summary>Update the fields of a user. This method may be used to add custom name/value pairs to the object. To delete a custom name/value pair, pass a null value in the JSON object (e.g.; "SomeName":null)</summary>
function UpdateUser(const AObjectID: string;
const AUserFields: TJSONObject): IEMSResourceResponseContent; overload;
// Groups
/// <summary>Add one or more users to a group. The group parameter must identify an existing group.</summary>
function AddUsersToGroup(const AGroupName: string;
const AUsers: TArray<string>): IEMSResourceResponseContent;
/// <summary>Create a user group.</summary>
function CreateGroup(const AGroupName: string;
const AGroupFields: TJSONObject): IEMSResourceResponseContent; overload;
/// <summary>Create a user group.</summary>
function CreateGroup(const AJSONBody: TJSONObject): IEMSResourceResponseContent; overload;
/// <summary>Delete a user group.</summary>
function DeleteGroup(const AGroupName: string; out AResponse: IEMSResourceResponseContent): Boolean; overload;
/// <summary>Delete a user group.</summary>
function DeleteGroup(const AGroupName: string): Boolean; overload;
/// <summary>Retreive groups using query parameters. If the parameters are empty then the result is unfiltered and unordered.</summary>
function QueryGroups(const AQuery: TQueryParams): IEMSResourceResponseContent;
/// <summary>Remove one or more users from a group.</summary>
function RemoveUsersFromGroup(const AGroupName: string;
const AUsers: TArray<string>; out AResponse: IEMSResourceResponseContent): Boolean;
/// <summary>Retrieve a user group. False is returned if the group was not found.</summary>
function RetrieveGroup(const AGroupName: string; out AResponse: IEMSResourceResponseContent): Boolean;
/// <summary>Update the fields of a user group. This method may be used to add custom name/value pairs to the object. To delete a custom name/value pair, pass a null value in the JSON object (e.g.; "SomeName":null)</summary>
function UpdateGroup(const AGroupName: string;
const AGroupFields: TJSONObject): IEMSResourceResponseContent; overload;
// Installations
/// <summary>Delete an installation. False is returned if the installation was not found.</summary>
function DeleteInstallation(const AInstallationID: string; out AResponse: IEMSResourceResponseContent): Boolean; overload;
/// <summary>Delete an installation. False is returned if the installation was not found.</summary>
function DeleteInstallation(const AInstallationID: string): Boolean; overload;
/// <summary>Retreive installations using query parameters. If the parameters are empty then the result is unfiltered and unordered.</summary>
function QueryInstallations(const AQuery: TQueryParams): IEMSResourceResponseContent;
/// <summary>Retrieve a paraticular installation. False is returned if the installation was not found.</summary>
function RetrieveInstallation(const AInstallationID: string; out AResponse: IEMSResourceResponseContent): Boolean; overload;
/// <summary>Update the fields of an installation. This method may be used to add custom name/value pairs to the object. To delete a custom name/value pair, pass a null value in the JSON object (e.g.; "SomeName":null)</summary>
function UpdateInstallation(const AInstallationID: string; const AJSONObject: TJSONObject): IEMSResourceResponseContent; overload;
// Push
/// <summary>Broadcast a push notification to all installations.</summary>
function PushBroadcast(const AData: TJSONObject): IEMSResourceResponseContent;
/// <summary>Send a push notfication to particular installations. A target parameters identifies which installations. The target may identifiy channels and/or a where filter such as {"where":{"email":"xyz@xmail.com"}, "channels": ["a","b"]}"</summary>
function PushToTarget(const AData: TJSONObject; const ATarget: TJSONObject): IEMSResourceResponseContent;
/// <summary>Send a push notification to installations associated with channels</summary>
function PushToChannels(const AData: TJSONObject; const AChannels: array of string): IEMSResourceResponseContent;
/// <summary>Send a push notification to installations identified by a where filter such as {"email":"xyz@xmail.com"} </summary>
function PushWhere(const AData: TJSONObject; const AWhere: TJSONObject): IEMSResourceResponseContent;
// Edge modules and resources
/// <summary>Delete an edge module. False is returned if the module was not found.</summary>
function UnregisterModule(const AModuleName: string; out AResponse: IEMSResourceResponseContent): Boolean; overload;
/// <summary>Delete an edge module. False is returned if the module was not found.</summary>
function UnregisterModule(const AModuleName: string): Boolean; overload;
/// <summary>Delete an edge resource. False is returned if the resource was not found.</summary>
function UnregisterModuleResource(const AModuleName, AResourceName: string; out AResponse: IEMSResourceResponseContent): Boolean; overload;
/// <summary>Delete an edge resource. False is returned if the resource was not found.</summary>
function UnregisterModuleResource(const AModuleName, AResourceName: string): Boolean; overload;
/// <summary>Retreive modules using query parameters. If the parameters are empty then the result is unfiltered and unordered.</summary>
function QueryModules(const AQuery: TQueryParams): IEMSResourceResponseContent;
/// <summary>Retreive module resources using query parameters. If the parameters are empty then the result is unfiltered and unordered.</summary>
function QueryModuleResources(const AQuery: TQueryParams): IEMSResourceResponseContent; overload;
/// <summary>Retreive module resources using query parameters. If the parameters are empty then the result is unfiltered and unordered.</summary>
function QueryModuleResources(const AModuleName: string; const AQuery: TQueryParams): IEMSResourceResponseContent; overload;
/// <summary>Retrieve a particular module. False is returned if the module was not found.</summary>
function RetrieveModule(const AModuleName: string; out AResponse: IEMSResourceResponseContent): Boolean; overload;
/// <summary>Retrieve a particular module resource. False is returned if the module resource was not found.</summary>
function RetrieveModuleResource(const AModuleName, AResourceName: string; out AResponse: IEMSResourceResponseContent): Boolean; overload;
/// <summary>Update the fields of a module. This method may be used to add custom name/value pairs to the object. To delete a custom name/value pair, pass a null value in the JSON object (e.g.; "SomeName":null)</summary>
function UpdateModule(const AModuleName: string; const AJSONObject: TJSONObject): IEMSResourceResponseContent; overload;
/// <summary>Update the fields of a module resource. This method may be used to add custom name/value pairs to the object. To delete a custom name/value pair, pass a null value in the JSON object (e.g.; "SomeName":null)</summary>
function UpdateModuleResource(const AModuleName, AResourceName: string; const AJSONObject: TJSONObject): IEMSResourceResponseContent; overload;
/// <summary>Execute DELETE resource request.</summary>
function ModuleResourceDelete(const AModuleName, AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams): IEMSResourceResponseContent;
/// <summary>Execute GET resource request.</summary>
function ModuleResourceGet(const AModuleName, AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams): IEMSResourceResponseContent;
/// <summary>Execute PATCH resource request.</summary>
function ModuleResourcePatch(const AModuleName, AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams;
const ARequestContent: IEMSResourceRequestContent): IEMSResourceResponseContent;
/// <summary>Execute POST resource request.</summary>
function ModuleResourcePost(const AModuleName, AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams;
const ARequestContent: IEMSResourceRequestContent): IEMSResourceResponseContent;
/// <summary>Execute PUT resource request.</summary>
function ModuleResourcePut(const AModuleName, AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams;
const ARequestContent: IEMSResourceRequestContent): IEMSResourceResponseContent;
end;
/// <summary>Exception that may raise when you interact with the members of
/// the TEMSInternalAPI class.</summary>
EEMSInternalAPIError = class(Exception);
TEMSLoggingResourceFunc = function(const AResource: TEMSResource; AJSON: TJSONObject): Boolean;
var
(* The EMSServices global variable is initialized by the EMS server.
From this interface all of the IxxxxServices interfaces
may be queried for.
*)
EMSServices: IEMSServices = nil;
EMSLoggingResourceFunc: TEMSLoggingResourceFunc = nil;
implementation
uses System.TypInfo, EMS.Consts;
{ TEMSServices }
class function TEMSServices.GetService<T>: T;
var
LGuid: TGuid;
LIntf: IInterface;
begin
LGuid := GetTypeData(TypeInfo(T))^.Guid;
LIntf := EMSServices.GetService(LGuid);
Result := T(LIntf);
end;
class function TEMSServices.TryGetService<T>(out Intf: T): Boolean;
var
LGuid: TGuid;
LIntf: IInterface;
begin
LGuid := GetTypeData(TypeInfo(T))^.Guid;
Result := EMSServices.TryGetService(LGuid, LIntf);
if Result then
Intf := T(LIntf);
end;
{ TEMSApplicationService }
class procedure TEMSApplicationService.AddShutdownNotification(AProc: TProc);
begin
Assert( TEMSServices.GetService<IEMSApplicationService> <> nil);
TEMSServices.GetService<IEMSApplicationService>.AddShutdownNotification(AProc);
end;
class procedure TEMSApplicationService.AddStartupNotification(AProc: TProc);
begin
Assert( TEMSServices.GetService<IEMSApplicationService> <> nil);
TEMSServices.GetService<IEMSApplicationService>.AddStartupNotification(AProc);
end;
{ TEMSLoggingService }
class procedure TEMSLoggingService.Log(const ACategory: string;
const AJSON: TJSONObject);
var
LService: IEMSLoggingService;
begin
LService := GetService;
if (LService <> nil) and (LService.LoggingEnabled) then
LService.Log(ACategory, AJSON);
end;
class function TEMSLoggingService.GetLoggingEnabled: Boolean;
var
LService: IEMSLoggingService;
begin
LService := GetService;
if LService <> nil then
Result := LService.LoggingEnabled
else
Result := False;
end;
class function TEMSLoggingService.GetService: IEMSLoggingService;
begin
if (EMS.Services.EMSServices = nil) or not EMS.Services.EMSServices.TryGetService(IEMSLoggingService, Result) then
Result := nil;
end;
{ TEMSInternalAPI }
function TEMSInternalAPI.AddUser(const AUserName, APassword: string;
const AUserFields: TJSONObject): IEMSResourceResponseContent;
var
LJSON: TJSONObject;
begin
if AUserFields <> nil then
LJSON := AUserFields.Clone as TJSONObject
else
LJSON := TJSONObject.Create;
try
LJSON.AddPair(TJSONNames.UserName, AUserName);
LJSON.AddPair(TJSONNames.Password, APassword);
Result := AddUser(LJSON);
finally
LJSON.Free;
end;
end;
function TEMSInternalAPI.AddUser(
const AJSONBody: TJSONObject): IEMSResourceResponseContent;
var
LRequest: IEMSResourceRequestContent;
begin
LRequest := FService.CreateRequestContent(AJSONBody);
Result := FService.Post(FContext, TSegmentNames.Users, nil, nil, LRequest);
end;
function TEMSInternalAPI.AddUsersToGroup(const AGroupName: string;
const AUsers: TArray<string>): IEMSResourceResponseContent;
var
LJSONObject: TJSONObject;
LTemp: TJSONArray;
LJSONArray: TJSONArray;
S: string;
LResponse: IEMSResourceResponseContent;
begin
LJSONArray := nil;
try
if not RetrieveGroup(AGroupName, LResponse) then
raise EEMSInternalAPIError.CreateFmt(sGroupNotFound, [AGroupName]);
LJSONArray := nil;
if LResponse.TryGetObject(LJSONObject) then
if LJSONObject.TryGetValue<TJSONArray>(TJSONNames.GroupUsers, LTemp) then
LJSONArray := LTemp.Clone as TJSONArray;
if LJSONArray = nil then
LJSONArray := TJSONArray.Create;
for S in AUsers do
LJSONArray.Add(S);
LJSONObject := TJSONObject.Create;
try
LJSONObject.AddPair(TJSONNames.GroupUsers, LJSONArray);
LJSONArray := nil;
UpdateGroup(AGroupName, LJSONObject);
finally
LJSONObject.Free;
end;
finally
LJSONArray.Free;
end;
end;
function TEMSInternalAPI.RemoveUsersFromGroup(const AGroupName: string;
const AUsers: TArray<string>;
out AResponse: IEMSResourceResponseContent): Boolean;
var
LJSONObject: TJSONObject;
LJSONArray: TJSONArray;
S: string;
LResponse: IEMSResourceResponseContent;
LList: TList<string>;
LJSONValue: TJSONValue;
begin
Result := False;
if not RetrieveGroup(AGroupName, LResponse) then
raise EEMSInternalAPIError.CreateFmt(sGroupNotFound, [AGroupName]);
if LResponse.TryGetObject(LJSONObject) then
begin
if LJSONObject.TryGetValue<TJSONArray>(TJSONNames.GroupUsers, LJSONArray) then
begin
LList := TList<string>.Create;
try
for LJSONValue in LJSONArray do
LList.Add(LJSONValue.Value);
for S in AUsers do
if LList.Contains(S) then
begin
Result := True;
LList.Remove(S);
end;
if Result then
begin
LJSONObject := TJSONObject.Create;
try
LJSONArray := TJSONArray.Create;
LJSONObject.AddPair(TJSONNames.GroupUsers, LJSONArray);
for S in LList do
LJSONArray.Add(S);
AResponse := UpdateGroup(AGroupName, LJSONObject);
finally
LJSONObject.Free;
end;
end;
finally
LList.Free;
end;
end;
end;
end;
constructor TEMSInternalAPI.Create(const AContext: TEndpointContext);
begin
FService := TEMSServices.GetService<IEMSInternalResourceRequestService>;
FContext := FService.CreateRequestContext(AContext);
end;
function TEMSInternalAPI.CreateGroup(
const AJSONBody: TJSONObject): IEMSResourceResponseContent;
var
LRequest: IEMSResourceRequestContent;
begin
LRequest := FService.CreateRequestContent(AJSONBody);
Result := FService.Post(FContext, TSegmentNames.Groups, nil, nil, LRequest);
end;
function TEMSInternalAPI.CreateGroup(const AGroupName: string;
const AGroupFields: TJSONObject): IEMSResourceResponseContent;
var
LJSON: TJSONObject;
begin
if AGroupFields <> nil then
LJSON := AGroupFields.Clone as TJSONObject
else
LJSON := TJSONObject.Create;
try
LJSON.AddPair(TJSONNames.GroupName, AGroupName);
Result := CreateGroup(LJSON);
finally
LJSON.Free;
end;
end;
function TEMSInternalAPI.LoginUser(const AUserName, APassword: string): IEMSResourceResponseContent;
var
LJSON: TJSONObject;
begin
LJSON := TJSONObject.Create;
try
LJSON.AddPair(TJSONNames.UserName, AUserName);
LJSON.AddPair(TJSONNames.Password, APassword);
Result := LoginUser(LJSON);
finally
LJSON.Free;
end;
end;
function TEMSInternalAPI.DeleteUser(const AObjectID: string;
out AResponse: IEMSResourceResponseContent): Boolean;
begin
AResponse := FService.Delete(FContext, TSegmentNames.Users, TEMSResourceRequestSegments.Create(AObjectID), nil);
Result := AResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.DeleteGroup(const AGroupName: string): Boolean;
var
LResponse: IEMSResourceResponseContent;
begin
LResponse := FService.Delete(FContext, TSegmentNames.Groups, TEMSResourceRequestSegments.Create(AGroupName), nil);
Result := LResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.DeleteInstallation(
const AInstallationID: string): Boolean;
var
LResponse: IEMSResourceResponseContent;
begin
LResponse := FService.Delete(FContext, TSegmentNames.Installations, TEMSResourceRequestSegments.Create(AInstallationID), nil);
Result := LResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.UnregisterModule(
const AModuleName: string): Boolean;
var
LResponse: IEMSResourceResponseContent;
begin
LResponse := FService.Delete(FContext, TSegmentNames.Edgemodules, TEMSResourceRequestSegments.Create(AModuleName), nil);
Result := LResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.UnregisterModuleResource(
const AModuleName, AResourceName: string): Boolean;
var
LResponse: IEMSResourceResponseContent;
begin
LResponse := FService.Delete(FContext, TSegmentNames.Edgemodules, TEMSResourceRequestSegments.Create(AModuleName, TSegmentNames.Resources, AResourceName), nil);
Result := LResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.ModuleResourceDelete(const AModuleName, AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams): IEMSResourceResponseContent;
var
LSegments: TEMSResourceRequestSegments;
begin
LSegments := TEMSResourceRequestSegments.Create(AModuleName, AResourceName) + ASegments;
Result := FService.Delete(FContext, TSegmentNames.Edgemodules, LSegments, AQueryParams);
end;
function TEMSInternalAPI.ModuleResourceGet(const AModuleName, AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams): IEMSResourceResponseContent;
var
LSegments: TEMSResourceRequestSegments;
begin
LSegments := TEMSResourceRequestSegments.Create(AModuleName, AResourceName) + ASegments;
Result := FService.Get(FContext, TSegmentNames.Edgemodules, LSegments, AQueryParams);
end;
function TEMSInternalAPI.ModuleResourcePost(const AModuleName, AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams;
const ARequestContent: IEMSResourceRequestContent): IEMSResourceResponseContent;
var
LSegments: TEMSResourceRequestSegments;
begin
LSegments := TEMSResourceRequestSegments.Create(AModuleName, AResourceName) + ASegments;
Result := FService.Post(FContext, TSegmentNames.Edgemodules, LSegments, AQueryParams, ARequestContent);
end;
function TEMSInternalAPI.ModuleResourcePut(const AModuleName, AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams;
const ARequestContent: IEMSResourceRequestContent): IEMSResourceResponseContent;
var
LSegments: TEMSResourceRequestSegments;
begin
LSegments := TEMSResourceRequestSegments.Create(AModuleName, AResourceName) + ASegments;
Result := FService.Put(FContext, TSegmentNames.Edgemodules, LSegments, AQueryParams, ARequestContent);
end;
function TEMSInternalAPI.ModuleResourcePatch(const AModuleName, AResourceName: string; const ASegments: TEMSResourceRequestSegments; const AQueryParams: TEMSResourceRequestQueryParams;
const ARequestContent: IEMSResourceRequestContent): IEMSResourceResponseContent;
var
LSegments: TEMSResourceRequestSegments;
begin
LSegments := TEMSResourceRequestSegments.Create(AModuleName, AResourceName) + ASegments;
Result := FService.Patch(FContext, TSegmentNames.Edgemodules, LSegments, AQueryParams, ARequestContent);
end;
function TEMSInternalAPI.UpdateModule(const AModuleName: string;
const AJSONObject: TJSONObject): IEMSResourceResponseContent;
var
LRequest: IEMSResourceRequestContent;
begin
LRequest := FService.CreateRequestContent(AJSONObject);
Result := FService.Put(FContext, TSegmentNames.Edgemodules, TEMSResourceRequestSegments.Create(AModuleName), nil, LRequest);
end;
function TEMSInternalAPI.DeleteInstallation(const AInstallationID: string;
out AResponse: IEMSResourceResponseContent): Boolean;
begin
AResponse := FService.Delete(FContext, TSegmentNames.Installations, TEMSResourceRequestSegments.Create(AInstallationID), nil);
Result := AResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.UnregisterModule(const AModuleName: string;
out AResponse: IEMSResourceResponseContent): Boolean;
begin
AResponse := FService.Delete(FContext, TSegmentNames.EdgeModules, TEMSResourceRequestSegments.Create(AModuleName), nil);
Result := AResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.UnregisterModuleResource(const AModuleName, AResourceName: string;
out AResponse: IEMSResourceResponseContent): Boolean;
begin
AResponse := FService.Delete(FContext, TSegmentNames.EdgeModules, TEMSResourceRequestSegments.Create(AModuleName, TSegmentNames.Resources, AResourceName), nil);
Result := AResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.DeleteGroup(const AGroupName: string;
out AResponse: IEMSResourceResponseContent): Boolean;
var
LResponse: IEMSResourceResponseContent;
begin
LResponse := FService.Delete(FContext, TSegmentNames.Groups, TEMSResourceRequestSegments.Create(AGroupName), nil);
Result := LResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.DeleteUser(const AObjectID: string): Boolean;
var
LResponse: IEMSResourceResponseContent;
begin
LResponse := FService.Delete(FContext, TSegmentNames.Users, TEMSResourceRequestSegments.Create(AObjectID), nil);
Result := LResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.LoginUser(
const AJSONLogin: TJSONObject): IEMSResourceResponseContent;
var
LRequest: IEMSResourceRequestContent;
begin
LRequest := FService.CreateRequestContent(AJSONLogin);
Result := FService.Post(FContext, TSegmentNames.Users, TEMSResourceRequestSegments.Create(TSegmentNames.Login), nil, LRequest);
end;
function TEMSInternalAPI.Logout: IEMSResourceResponseContent;
begin
Result := FService.Post(FContext, TSegmentNames.Users, TEMSResourceRequestSegments.Create(TSegmentNames.Logout), nil, nil);
end;
function TEMSInternalAPI.PushBroadcast(
const AData: TJSONObject): IEMSResourceResponseContent;
begin
Result := PushToTarget(AData, nil);
end;
function TEMSInternalAPI.PushToChannels(const AData: TJSONObject;
const AChannels: array of string): IEMSResourceResponseContent;
var
LJSON: TJSONObject;
LChannels: TJSONArray;
S: string;
LRequest: IEMSResourceRequestContent;
begin
if Length(AChannels) = 0 then
raise EEMSInternalAPIError.Create(sChannelNamesExpected);
LJSON := TJSONObject.Create;
try
LChannels := TJSONArray.Create;
for S in AChannels do
LChannels.Add(S);
LJSON.AddPair(TJSONNames.PushChannels, LChannels);
LRequest := FService.CreateRequestContent(LJSON);
Result := FService.Post(FContext, TSegmentNames.Push, nil, nil, LRequest);
finally
LJSON.Free;
end;
end;
function TEMSInternalAPI.PushToTarget(const AData,
ATarget: TJSONObject): IEMSResourceResponseContent;
var
LJSON: TJSONObject;
LPair: TJSONPair;
LRequest: IEMSResourceRequestContent;
begin
LJSON := TJSONObject.Create;
try
if AData <> nil then
LJSON.AddPair(TJSONNames.PushData, AData.Clone as TJSONObject); // Do not localize
if ATarget <> nil then
for LPair in ATarget do
// such as "where" and "channels"
LJSON.AddPair(LPair.Clone as TJSONPair);
LRequest := FService.CreateRequestContent(LJSON);
Result := FService.Post(FContext, TSegmentNames.Push, nil, nil, LRequest);
finally
LJSON.Free;
end;
end;
function TEMSInternalAPI.PushWhere(const AData,
AWhere: TJSONObject): IEMSResourceResponseContent;
var
LJSON: TJSONObject;
LRequest: IEMSResourceRequestContent;
begin
LJSON := TJSONObject.Create;
try
if AWhere <> nil then
LJSON.AddPair(TJSONNames.PushWhere, AWhere.Clone as TJSONObject); // Do not localize
if AData <> nil then
LJSON.AddPair(TJSONNames.PushData, AData.Clone as TJSONObject); // Do not localize
LRequest := FService.CreateRequestContent(LJSON);
Result := FService.Post(FContext, TSegmentNames.Push, nil, nil, LRequest);
finally
LJSON.Free;
end;
end;
function TEMSInternalAPI.QueryGroups(
const AQuery: TQueryParams): IEMSResourceResponseContent;
begin
Result := FService.Get(FContext, TSegmentNames.Groups, nil, AQuery);
end;
function TEMSInternalAPI.QueryInstallations(
const AQuery: TQueryParams): IEMSResourceResponseContent;
begin
Result := FService.Get(FContext, TSegmentNames.Installations, nil, AQuery);
end;
function TEMSInternalAPI.QueryModules(
const AQuery: TQueryParams): IEMSResourceResponseContent;
begin
Result := FService.Get(FContext, TSegmentNames.Edgemodules, nil, AQuery);
end;
function TEMSInternalAPI.QueryModuleResources(
const AQuery: TQueryParams): IEMSResourceResponseContent;
begin
Result := FService.Get(FContext, TSegmentNames.Edgemodules, TEMSResourceRequestSegments.Create(TSegmentNames.Resources), AQuery);
end;
function TEMSInternalAPI.QueryModuleResources(
const AModuleName: string; const AQuery: TQueryParams): IEMSResourceResponseContent;
begin
Result := FService.Get(FContext, TSegmentNames.Edgemodules, TEMSResourceRequestSegments.Create(AModuleName, TSegmentNames.Resources), AQuery);
end;
function TEMSInternalAPI.QueryUserName(const AUserName: string): Boolean;
var
LResponse: IEMSResourceResponseContent;
begin
Result := QueryUserName(AUserName, LResponse);
end;
function TEMSInternalAPI.QueryUsers(
const AQuery: TQueryParams): IEMSResourceResponseContent;
begin
Result := FService.Get(FContext, TSegmentNames.Users, nil, AQuery);
end;
function TEMSInternalAPI.RetrieveGroup(const AGroupName: string;
out AResponse: IEMSResourceResponseContent): Boolean;
begin
AResponse := FService.Get(FContext, TSegmentNames.Groups, TEMSResourceRequestSegments.Create(AGroupName), nil);
Result := AResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.RetrieveInstallation(const AInstallationID: string;
out AResponse: IEMSResourceResponseContent): Boolean;
begin
AResponse := FService.Get(FContext, TSegmentNames.Installations, TEMSResourceRequestSegments.Create(AInstallationID), nil);
Result := AResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.RetrieveModule(const AModuleName: string;
out AResponse: IEMSResourceResponseContent): Boolean;
begin
AResponse := FService.Get(FContext, TSegmentNames.EdgeModules, TEMSResourceRequestSegments.Create(AModuleName), nil);
Result := AResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.RetrieveModuleResource(const AModuleName, AResourceName: string;
out AResponse: IEMSResourceResponseContent): Boolean;
begin
AResponse := FService.Get(FContext, TSegmentNames.EdgeModules, TEMSResourceRequestSegments.Create(AModuleName, TSegmentNames.Resources, AResourceName), nil);
Result := AResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.RetrieveUser(const AObjectID: string;
out AResponse: IEMSResourceResponseContent): Boolean;
begin
AResponse := FService.Get(FContext, TSegmentNames.Users, TEMSResourceRequestSegments.Create(AObjectID), nil);
Result := AResponse.StatusCode <> 404;
end;
function TEMSInternalAPI.SignupUser(const AUserName, APassword: string; const AUserFields: TJSONObject): IEMSResourceResponseContent;
var
LJSON: TJSONObject;
begin
if AUserFields <> nil then
LJSON := AUserFields.Clone as TJSONObject
else
LJSON := TJSONObject.Create;
try
LJSON.AddPair(TJSONNames.UserName, AUserName);
LJSON.AddPair(TJSONNames.Password, APassword);
Result := SignupUser(LJSON);
finally
LJSON.Free;
end;
end;
function TEMSInternalAPI.SignupUser(const AJSONBody: TJSONObject): IEMSResourceResponseContent;
var
LRequest: IEMSResourceRequestContent;
begin
LRequest := FService.CreateRequestContent(AJSONBody);
Result := FService.Post(FContext, TSegmentNames.Users, TEMSResourceRequestSegments.Create(TSegmentNames.Signup), nil, LRequest);
end;
function TEMSInternalAPI.UpdateGroup(const AGroupName: string;
const AGroupFields: TJSONObject): IEMSResourceResponseContent;
var
LRequest: IEMSResourceRequestContent;
begin
LRequest := FService.CreateRequestContent(AGroupFields);
Result := FService.Put(FContext, TSegmentNames.Groups, TEMSResourceRequestSegments.Create(AGroupName), nil, LRequest);
end;
function TEMSInternalAPI.UpdateInstallation(const AInstallationID: string;
const AJSONObject: TJSONObject): IEMSResourceResponseContent;
var
LRequest: IEMSResourceRequestContent;
begin
LRequest := FService.CreateRequestContent(AJSONObject);
Result := FService.Put(FContext, TSegmentNames.Installations, TEMSResourceRequestSegments.Create(AInstallationID), nil, LRequest);
end;
function TEMSInternalAPI.UpdateModuleResource(const AModuleName, AResourceName: string;
const AJSONObject: TJSONObject): IEMSResourceResponseContent;
var
LRequest: IEMSResourceRequestContent;
begin
LRequest := FService.CreateRequestContent(AJSONObject);
Result := FService.Put(FContext, TSegmentNames.Edgemodules, TEMSResourceRequestSegments.Create(AModuleName, TSegmentNames.Resources, AResourceName), nil, LRequest);
end;
function TEMSInternalAPI.UpdateUser(const AObjectID: string;
const AUserFields: TJSONObject): IEMSResourceResponseContent;
var
LRequest: IEMSResourceRequestContent;
begin
LRequest := FService.CreateRequestContent(AUserFields);
Result := FService.Put(FContext, TSegmentNames.Users, TEMSResourceRequestSegments.Create(AObjectID), nil, LRequest);
end;
function TEMSInternalAPI.QueryUserName(const AUserName: string;
out AResponse: IEMSResourceResponseContent): Boolean;
var
LJSON: TJSONObject;
LWhere: string;
LQueryParams: TEMSResourceRequestQueryParams;
LJSONArray: TJSONArray;
begin
LJSON := TJSONObject.Create.AddPair(TJSONNames.UserName, TJSONString.Create(AUserName));
try
LWhere := LJSON.ToJSON;
finally
LJSON.Free;
end;
LQueryParams := TEMSResourceRequestQueryParams.Create(
TPair<string, string>.Create(
TEMSInternalAPI.TQueryParamNames.Where,
LWhere)
);
AResponse := FService.Get(FContext, TSegmentNames.Users, nil, LQueryParams);
Result := AResponse.TryGetArray(LJSONArray) and (LJSONArray.Count > 0);
end;
end.
|
unit UNcm;
interface
uses DateUtils, SysUtils;
type Ncm = class
protected
Id : Integer;
Numero : Integer;
Porcentagem_Ipi : Real;
DataCadastro : TDateTime;
DataAlteracao : TDateTime;
public
Constructor CrieObjeto;
Destructor Destrua_Se;
Procedure setId (vId : Integer);
Procedure setNumero (vNumero : Integer);
Procedure setPorcentagem_Ipi (vPorcentagem_Ipi : Real);
Procedure setDataCadastro (vDataCadastro : TDateTime);
Procedure setDataAlteracao (vDataAlteracao : TDateTime);
Function getId : integer;
Function getNumero : Integer;
Function getPorcentagem_Ipi : Real;
Function getDataCadastro :TDateTime;
Function getDataAlteracao : TDateTime;
end;
implementation
{ Ncm }
constructor Ncm.CrieObjeto;
var dataAtual : TDateTime;
begin
dataAtual := Date;
Id := 0;
Numero := 0;
Porcentagem_Ipi := 0.0;
DataCadastro := dataAtual;
DataAlteracao := dataAtual;
end;
destructor Ncm.Destrua_Se;
begin
end;
function Ncm.getDataAlteracao: TDateTime;
begin
Result := DataAlteracao;
end;
function Ncm.getDataCadastro: TDateTime;
begin
Result := DataCadastro;
end;
function Ncm.getId: integer;
begin
Result := Id;
end;
function Ncm.getNumero: Integer;
begin
Result := Numero;
end;
function Ncm.getPorcentagem_Ipi: Real;
begin
Result := Porcentagem_Ipi;
end;
procedure Ncm.setDataAlteracao(vDataAlteracao: TDateTime);
begin
DataAlteracao := vDataAlteracao;
end;
procedure Ncm.setDataCadastro(vDataCadastro: TDateTime);
begin
DataCadastro := vDataCadastro;
end;
procedure Ncm.setId(vId: Integer);
begin
Id := vId;
end;
procedure Ncm.setNumero(vNumero: Integer);
begin
Numero := vNumero;
end;
procedure Ncm.setPorcentagem_Ipi(vPorcentagem_Ipi: Real);
begin
Porcentagem_Ipi := vPorcentagem_Ipi;
end;
end.
|
unit pFIBComponentEditors;
interface
{$I ..\FIBPlus.inc}
uses
Classes, SysUtils,
{$IFDEF D_XE2}
Vcl.Forms,Vcl.Controls,DB,Vcl.Dialogs,
{$ELSE}
Forms,Controls,DB,Dialogs,
{$ENDIF}
ToCodeEditor,TypInfo, ColnEdit,
{$IFDEF D6+}
DesignEditors,DesignIntf, Variants
{$else}
DsgnIntf
{$ENDIF}
;
type
TFIBAliasEdit = class(TStringProperty)
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TFileNameProperty = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
TpFIBDatabaseEditor = class(TComponentEditor)
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TpFIBTransactionEditor = class(TComponentEditor)
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TpFIBDeltaReceiverEditor = class(TComponentEditor)
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TFIBConditionsEditor = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TpFIBDataSetOptionsEditor = class(TSetProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TpFIBAutoUpdateOptionsEditor = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TEdParamToFields = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure Edit; override;
end;
TKeyFieldNameEdit = class(TStringProperty)
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TpFIBStoredProcProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TGeneratorNameEdit = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TTableNameEdit = class(TStringProperty)
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TTableNameEditDR = class(TStringProperty)
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TFIBTrKindEdit = class(TStringProperty)
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
TpFIBTRParamsEditor = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure Edit; override;
end;
TpFIBQueryEditor = class(TComponentEditor)
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
TDataSet_ID_Edit = class(TIntegerProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TFIBSQLsProperties = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure Edit; override;
end;
TFIBSQLsProperty = class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure Edit; override;
end;
TFIBGenSQlEd = class(TComponentEditor)
{$IFDEF D6+}
DefaultEditor: IComponentEditor;
{$ELSE}
DefaultEditor: TComponentEditor;
{$ENDIF}
public
{$IFDEF VER100}
constructor Create(AComponent: TComponent; ADesigner: TFormDesigner); override;
{$ELSE}
{$IFNDEF D6+}
constructor Create(AComponent: TComponent; ADesigner: IFormDesigner); override;
{$ELSE}
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
{$ENDIF}
{$ENDIF}
destructor Destroy; override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
procedure SaveDataSetInfo;
end;
TpFIBSQLPropEdit =class(TClassProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure Edit; override;
end;
TpFIBGeneratorsProperty = class(TPropertyEditor {TClassProperty})
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure Edit; override;
end;
implementation
uses RegistryUtils, pFIBEditorsConsts, pFIBDBEdit
// , EdFieldInfo
, pFIBInterfaces, pFIBRepositoryOperations, EdFieldInfo, EdErrorInfo,
pFIBConditionsEdit, EdDataSetInfo, pFIBTrEdit, pFIBDataSetOptions,
pFIBAutoUpdEditor, RegFIBPlusEditors, RTTIRoutines, FIBSQLEditor,
EdParamToFields, FIBDataSQLEditor,uFIBScriptForm;
{ TFIBAliasEdit }
type
IFIBClassesExporter = interface
['{AFC7CF1A-EAA5-4584-B47D-BDAD337B4EEC}']
function iGetStringer:IFIBStringer;
function iGetMetaExtractor:IFIBMetaDataExtractor;
end;
function TFIBAliasEdit.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
Result := Result + [paValueList]
end;
procedure TFIBAliasEdit.GetValues(Proc: TGetStrProc);
var i: integer;
Keys: Variant;
begin
{$IFNDEF NO_REGISTRY}
if PropCount > 1 then Exit;
Keys := DefAllSubKey(['Software', RegFIBRoot, 'Aliases']);
if VarType(Keys) = varBoolean then Exit;
for i := VarArrayLowBound(Keys, 1) to VarArrayHighBound(Keys, 1) do Proc(Keys[i])
{$ENDIF}
end;
{ TFileNameProperty }
procedure TFileNameProperty.Edit;
var
FileOpen: TOpenDialog;
pName:string;
pValue:string;
begin
pName :=GetPropInfo^.Name;
pValue :=GetValue;
FileOpen := TOpenDialog.Create(Application);
try
with Fileopen do
begin
if Trim(pValue)<>'' then
// if DirectoryExists(ExtractFilePath(pValue)) then
FileOpen.InitialDir:=ExtractFilePath(pValue)
else
FileOpen.InitialDir:='c:\';
if pName='DBName' then
Filter := 'IB base files|*.gdb|IB7 base files|*.ib|Firebird base files|*.fdb|All files|*.*'
else
if pName='CacheFileName' then
Filter := 'INI|*.ini|All files|*.*'
else
Filter := 'DLL|*.dll|All files|*.*';
if FileExists(pValue) then
FileName:=pValue;
if Execute then
SetValue(Filename);
end;
finally
Fileopen.free;
end;
end;
function TFileNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paRevertable];
end;
{ TpFIBDatabaseEditor }
procedure TpFIBDatabaseEditor.ExecuteVerb(Index: Integer);
var
db:IFIBConnect;
Script:TStrings;
Stringer:IFIBStringer;
Connected:Boolean;
begin
if ObjSupports(Component,IFIBConnect,db) then
case Index of
0 :if EditFIBDatabase(Component) then
Designer.Modified;
1 : begin
// try to connect
if not GetPropValue(Component,'Connected',False) then
begin
MessageDlg(SCompDatabaseNotConnected, mtConfirmation, [mbOK], 0);
Exit;
end;
if db.QueryValueAsStr(qryExistTable,0,['FIB$FIELDS_INFO'])='0' then
begin
if MessageDlg(SCompEditInfoFieldsNotExist, mtConfirmation, [mbOK, mbCancel], 0) <> mrOk
then Exit;
AdjustFRepositaryTable(db)
end
else
AdjustFRepositaryTable(db);
ShowFieldInfo(Component)
end;
2:
begin
// try to connect
if not GetPropValue(Component,'Connected',False) then
begin
MessageDlg(SCompDatabaseNotConnected, mtConfirmation, [mbOK], 0);
Exit;
end;
if db.QueryValueAsStr(qryExistTable,0,['FIB$ERROR_MESSAGES'])='0' then
begin
if MessageDlg(SCompEditErrorTableNotExist, mtConfirmation, [mbOK, mbCancel], 0) <> mrOk
then Exit;
CreateErrorRepositoryTable(db);
end;
ShowErrorInfo(Component)
end;
3:
begin
// try to connect
if not GetPropValue(Component,'Connected',False) then
begin
MessageDlg(SCompDatabaseNotConnected, mtConfirmation, [mbOK], 0);
Exit;
end;
if db.QueryValueAsStr(qryExistTable,0,['FIB$DATASETS_INFO'])='0' then
begin
if
MessageDlg(SCompEditInfoTableNotExist, mtConfirmation, [mbOK, mbCancel], 0
) <> mrOk
then Exit;
CreateDataSetRepositoryTable(db);
end;
EditDSInfo(Component);
end;
4:
begin
Script:=TStringList.Create;
try
Connected:=GetPropValue(Component,'Connected',False);
Script.Add('/***************************************');
Script.Add(' FIBPlus repository tables ');
Script.Add('***************************************/');
Script.Add('');
// if not Connected or (db.QueryValueAsStr(qryExistDomain,0,['FIB$BOOLEAN'])='0') then
Script.Add(qryCreateBooleanDomain+';');
// if not Connected or (db.QueryValueAsStr(qryGeneratorExist,0,['FIB$FIELD_INFO_VERSION'])='0') then
Script.Add(qryCreateFieldInfoVersionGen+';');
Script.Add('');
Script.Add('/*Fields repository table*/');
Script.Add('');
Script.Add(qryCreateTabFieldsRepository+';');
Script.Add('');
Script.Add('SET TERM ^;');
Script.Add(qryCreateFieldRepositoryTriggerBI+' ^');
Script.Add('');
Script.Add(qryCreateFieldRepositoryTriggerBU+' ^');
Script.Add('SET TERM ;^');
Script.Add('');
Script.Add('GRANT SELECT ON TABLE FIB$FIELDS_INFO TO PUBLIC;');
Script.Add('COMMIT WORKS ;');
Script.Add('');
Script.Add('');
Script.Add('/*Datasets repository table*/');
Script.Add('');
Script.Add(qryCreateDataSetsRepository+';');
Script.Add('');
Script.Add('SET TERM ^;');
Script.Add(qryCreateDataSetRepositoryTriggerBI+' ^');
Script.Add('');
Script.Add(qryCreateDataSetRepositoryTriggerBU+' ^');
Script.Add('SET TERM ;^');
Script.Add('');
Script.Add('GRANT SELECT ON TABLE FIB$DATASETS_INFO TO PUBLIC;');
Script.Add('COMMIT WORKS ;');
Script.Add('');
Script.Add('');
Script.Add('/*Errors repository table*/');
Script.Add('');
Script.Add(qryCreateErrorsRepository+';');
Script.Add('');
Script.Add('SET TERM ^;');
Script.Add(qryCreateErrorsRepositoryTriggerBI+' ^');
Script.Add('');
Script.Add(qryCreateErrorsRepositoryTriggerBU+' ^');
Script.Add('SET TERM ;^');
Script.Add('');
Script.Add('GRANT SELECT ON TABLE FIB$ERROR_MESSAGES TO PUBLIC;');
Script.Add('COMMIT WORKS ;');
ShowScript('Metadata for repository tables',Component,Script);
finally
Script.Free;
end
end;
end;
end;
function TpFIBDatabaseEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := SCompEditDBEditor;
1: Result := SCompEditEditFieldInfo;
2: Result := SCompEditErrorMessages;
3: Result := SCompEditDataSetInfo;
4: Result := SRepositoriesScript;
end;
end;
function TpFIBDatabaseEditor.GetVerbCount: Integer;
begin
Result := 5
end;
{ TFIBConditionsEditor }
procedure TFIBConditionsEditor.Edit;
var
Conditions:TObject;
begin
Conditions:=GetObjectProp(GetComponent(0),'Conditions');
if Assigned(Conditions) then
if EditConditions(TStrings(Conditions)) then
Designer.Modified
end;
function TFIBConditionsEditor.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog] - [paSubProperties];
end;
{ TpFIBTransactionEditor }
procedure TpFIBTransactionEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0: if EditFIBTrParams(Component) then
Designer.Modified
end;
end;
function TpFIBTransactionEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := SCompEditEditTransaction;
end;
end;
function TpFIBTransactionEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
{ TpFIBDataSetOptionsEditor }
procedure TpFIBDataSetOptionsEditor.Edit;
var
pName: string;
DataSets: array of TDataSet;
k:integer;
begin
pName := GetPropInfo^.Name;
SetLength(DataSets,PropCount);
for k := 0 to PropCount-1 do
begin
DataSets[k]:=GetComponent(k) as TDataSet;
end;
if pName = 'Options' then
begin
if EditOptions(DataSets, 0) then
Modified;
end
else
if EditOptions(DataSets, 1) then
Modified;
end;
function TpFIBDataSetOptionsEditor.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog];
end;
{ TpFIBAutoUpdateOptionsEditor }
procedure TpFIBAutoUpdateOptionsEditor.Edit;
begin
if EditAutoUpdateOptions(GetComponent(0) as TDataSet) then
Modified
end;
function TpFIBAutoUpdateOptionsEditor.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog, paSubProperties];
end;
{ TpFIBStoredProcProperty }
function TpFIBStoredProcProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList];
end;
procedure TpFIBStoredProcProperty.GetValues(Proc: TGetStrProc);
var
StoredProc: TPersistent;
DB:TObject;
Qry:TComponent;
Trans :TComponent;
iQry:IFIBQuery;
begin
StoredProc := GetComponent(0) ;
DB:=GetObjectProp(StoredProc,'Database');
if not Assigned(DB) then Exit;
Qry := nil; Trans := nil;
try
try
Trans:= expTransactionClass.Create(nil);
SetObjectProp(Trans,'DefaultDatabase',DB);
Qry:= expQueryClass.Create(nil);
SetPropValue(Qry,'ParamCheck','False');
SetObjectProp(Qry,'Database',DB);
SetObjectProp(Qry,'Transaction',Trans);
AssignStringsToProp(Qry,'SQL','SELECT RDB$PROCEDURE_NAME FROM RDB$PROCEDURES');
SetPropValue(Trans,'Active','True');
try
ObjSupports(Qry, IFIBQuery,iQry);
iQry.ExecQuery;
while not iQry.iEof do
begin
Proc(
Trim(
VarToStr(iQry.FieldValue('RDB$PROCEDURE_NAME',False))
)
);
iQry.iNext;
end;
iQry.Close;
finally
SetPropValue(Trans,'Active','False');
end;
except
end
finally
iQry:=nil;
Qry.Free;
Trans.Free;
end;
end;
{ TGeneratorNameEdit }
function TGeneratorNameEdit.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
Result := Result + [paValueList]
end;
type
THackAutoUpdateOptions= class (TPersistent)
private
FOwner :TComponent;
end;
procedure TGeneratorNameEdit.GetValues(Proc: TGetStrProc);
var
DB:TObject;
Dset:TComponent;
Qry:TComponent;
Trans :TComponent;
iQry:IFIBQuery;
begin
if PropCount > 1 then Exit;
if not (THackAutoUpdateOptions(GetComponent(0)).FOwner is
expDatasetClass
) then Exit;
Dset:= THackAutoUpdateOptions(GetComponent(0)).FOwner ;
DB:= GetObjectProp(Dset,'Database');
if not Assigned(DB) then Exit;
Qry := nil; Trans := nil;
try
Trans:= expTransactionClass.Create(nil);
SetObjectProp(Trans,'DefaultDatabase',DB);
Qry:= expQueryClass.Create(nil);
SetPropValue(Qry,'ParamCheck','False');
SetObjectProp(Qry,'Database',DB);
SetObjectProp(Qry,'Transaction',Trans);
AssignStringsToProp(Qry,'SQL',
'select RDB$GENERATOR_NAME from RDB$GENERATORS '+
'where (RDB$SYSTEM_FLAG is NULL) or (RDB$SYSTEM_FLAG = 0)'+
' order by RDB$GENERATOR_NAME'
);
SetPropValue(Trans,'Active','True');
try
ObjSupports(Qry, IFIBQuery,iQry);
iQry.ExecQuery;
while not iQry.iEof do
begin
Proc(
Trim(
VarToStr(iQry.FieldValue(0,false))
)
);
iQry.iNext;
end;
iQry.Close;
finally
SetPropValue(Trans,'Active','False');
end;
finally
iQry:=nil;
Qry.Free;
Trans.Free;
end;
(*{ if not (TAutoUpdateOptions(GetComponent(0)).Owner is TpFIBDataSet) then Exit;
Dset:= (TAutoUpdateOptions(GetComponent(0)).Owner as TpFIBDataSet);}
if not Assigned(Dset.Database) then Exit;
Qry := nil; Trans := nil;
try
Trans := TpFIBTransaction.Create(nil);
Qry := TpFIBQuery.Create(nil);
Qry.ParamCheck:=false;
Qry.Database := Dset.Database;
Trans.DefaultDatabase := Dset.Database;
Qry.Transaction := Trans;
Qry.SQL.Text := 'select RDB$GENERATOR_NAME '+
'from RDB$GENERATORS '+
'where (RDB$SYSTEM_FLAG is NULL) or (RDB$SYSTEM_FLAG = 0)'+
'order by RDB$GENERATOR_NAME';
try
Trans.StartTransaction;
Qry.ExecQuery;
lSQLDA := Qry.Current;
while not Qry.Eof do
begin
Proc(Trim(lSQLDA.ByName['RDB$GENERATOR_NAME'].AsString));
lSQLDA := Qry.Next;
end;
Qry.Close;
finally
Trans.Commit;
end;
finally
Qry.Free;
Trans.Free;
end*)
end;
{ TFIBTrKindEdit }
function TFIBTrKindEdit.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
Result := Result + [paValueList]
end;
procedure TFIBTrKindEdit.GetValues(Proc: TGetStrProc);
var i: integer;
Keys,v: Variant;
begin
if PropCount > 1 then Exit;
Keys := DefAllSubKey(['Software', RegFIBRoot, RegFIBTrKinds]);
Proc('NoUserKind');
if VarType(Keys) = varBoolean then Exit;
for i := VarArrayLowBound(Keys, 1) to VarArrayHighBound(Keys, 1) do
begin
v:=DefReadFromRegistry(['Software', RegFIBRoot, RegFIBTrKinds,
Keys[i]
],['Name']);
if VarType(v) <> varBoolean then
Proc(v[0,0])
end;
end;
{ TpFIBTRParamsEditor }
procedure TpFIBTRParamsEditor.Edit;
begin
if EditFIBTrParams(TComponent(GetComponent(0))) then
Modified
end;
function TpFIBTRParamsEditor.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog]-[paSubProperties];
end;
function TpFIBTRParamsEditor.GetValue: string;
begin
Result:='(TTRParams)'
end;
{ TpFIBQueryEditor }
procedure TpFIBQueryEditor.ExecuteVerb(Index: Integer);
begin
case Index of
0:
begin
if not FindPropInCode(Component,'SQL') then
if ShowSQLEdit(Component) then
Designer.Modified;
FindPropInCode(Component,'SQL')
end;
1: begin
// TpFIBQuery(Component).CheckValidStatement;
ShowMessage(SNoErrors);
end;
end;
end;
function TpFIBQueryEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := SEditSQL;
1: Result := SCheckSQLs;
end;
end;
function TpFIBQueryEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
{ TEdParamToFields }
procedure TEdParamToFields.Edit;
var
P:TObject;
begin
P:=GetObjectProp(GetComponent(0),'ParamsToFieldsLinks');
if Assigned(P) and
(THackAutoUpdateOptions(GetComponent(0)).FOwner is TDataSet)
then
if ShowEdParamToFields(TDataSet(THackAutoUpdateOptions(GetComponent(0)).FOwner),TStrings(P))
then
Designer.Modified
end;
function TEdParamToFields.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog] - [paSubProperties];
end;
function TEdParamToFields.GetValue: string;
var
P:TObject;
begin
P:=GetObjectProp(GetComponent(0),'ParamsToFieldsLinks');
if Assigned(P) and ((TStrings(P).Count)>0) then
Result:='(TPARAMS_FIELDS_LINKS)'
else
Result:='(TParams_Fields_Links)';
{ if (GetComponent(0) is TAutoUpdateOptions)
and (TAutoUpdateOptions(GetComponent(0)).ParamsToFieldsLinks.Count>0) then
Result:='(TPARAMS_FIELDS_LINKS)'
else
Result:='(TParams_Fields_Links)'}
end;
{ TKeyFieldNameEdit }
function TKeyFieldNameEdit.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
Result := Result + [paValueList]
end;
procedure TKeyFieldNameEdit.GetValues(Proc: TGetStrProc);
var i: integer;
Tables: TStrings;
ds:TDataSet;
ids:IFIBDataSet;
Obj:TObject;
Stringer:IFIBStringer;
updTableName:string;
clExp:IFIBClassesExporter;
begin
if PropCount > 1 then
Exit;
ds:=(THackAutoUpdateOptions(GetComponent(0)).FOwner as TDataSet);
if not ObjSupports(ds,IFIBDataSet,ids) then
Exit;
Obj:=GetObjectProp(THackAutoUpdateOptions(GetComponent(0)).FOwner,'Database');
if not Assigned(Obj) then
// if not Assigned(TAutoUpdateOptions(GetComponent(0)).FOwner).Database) then
Exit;
Tables := TStringList.Create;
with ds do
try
try
updTableName:=GetPropValue(GetComponent(0), 'UpdateTableName');
if Trim(updTableName)='' then
begin
ShowMessage('Error: UpdateTableName is empty');
Exit;
end;
Supports(FIBClassesExporter,IFIBClassesExporter,clExp);
Stringer:=clExp.iGetStringer;
FieldDefs.Update;
if FieldCount>0 then
for i := 0 to Pred(FieldCount) do
begin
if (Fields[i] is TLargeIntField) or
(Fields[i] is TIntegerField) or ((Fields[i] is TBCDField)and (TBCDField(Fields[i]).Size=0))
and
Stringer.EquelStrings(ids.GetRelationTableName(Fields[i]),updTableName,False)
then
begin
Proc(Fields[i].FieldName);
end;
end
else
begin
{ if not QSelect.Prepared then
QSelect.Prepare;}
ids.Prepare;
for i := 0 to Pred(FieldDefs.Count) do
begin
if (FieldDefs[i].DataType in [ftSmallint, ftInteger]) and
Stringer.EquelStrings(ids.GetRelationTableName(FieldDefs[i]),UpdTableName,False)
then
begin
Proc(FieldDefs[i].Name);
end
else
if ((FieldDefs[i].DataType =ftBCD) and (FieldDefs[i].Size=0)) and
Stringer.EquelStrings(ids.GetRelationTableName(FieldDefs[i]),UpdTableName,False)
then
begin
Proc(FieldDefs[i].Name);
end;
end;
end;
except
end;
finally
Tables.Free
end
end;
{ TTableNameEdit }
function TTableNameEdit.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
Result := Result + [paValueList]
end;
procedure TTableNameEdit.GetValues(Proc: TGetStrProc);
var i: integer;
Tables: TStrings;
Stringer:IFIBStringer;
clExp:IFIBClassesExporter;
begin
if PropCount > 1 then Exit;
if not (THackAutoUpdateOptions(GetComponent(0)).FOwner is TDataSet) then Exit;
Tables := TStringList.Create;
try
Supports(FIBClassesExporter,IFIBClassesExporter,clExp);
Stringer:=clExp.iGetStringer;
Stringer.AllTables(TStrings(GetObjectProp(THackAutoUpdateOptions(GetComponent(0)).FOwner,'SelectSQL')).Text, Tables);
for i := 0 to Pred(Tables.Count) do Proc(Stringer.ExtractWord(1, Tables[i], [' ']));
finally
Tables.Free
end
end;
//DataSet Editor
procedure ShowDataSetSQLEditor(Component:TComponent;Kind:integer;Designer:IDesigner);
const
SQLNames:array[0..4] of string =('SelectSQL','InsertSQL','UpdateSQL',
'DeleteSQL','RefreshSQL'
);
var
k:byte;
ExitToCodeEditor:integer;
begin
for k:=0 to 4 do
begin
SaveModule(Component,SQLNames[k]);
end;
if ShowDSSQLEdit(TDataSet(Component),Kind,ExitToCodeEditor) then
begin
Designer.Modified;
end;
if ExitToCodeEditor>=0 then
begin
for k:=0 to 4 do
begin
if ExitToCodeEditor<>k then
if CloseModule(Component,SQLNames[k]) then
CreatePropInCode(Component,SQLNames[k],
nil,True
);
SaveModule(Component,SQLNames[k]);
end;
if ExitToCodeEditor>=0 then
FindPropInCode(Component,SQLNames[ExitToCodeEditor]);
end;
end;
type
PClass = ^TClass;
{$IFDEF VER100}
constructor TFIBGenSQlEd.Create(AComponent: TComponent; ADesigner: TFormDesigner);
{$ELSE}
{$IFNDEF D6+}
constructor TFIBGenSQlEd.Create(AComponent: TComponent; ADesigner: IFormDesigner);
{$ELSE}
constructor TFIBGenSQlEd.Create(AComponent: TComponent; ADesigner: IDesigner);
{$ENDIF}
{$ENDIF}
var CompClass: TClass;
begin
inherited Create(AComponent, ADesigner);
CompClass := PClass(Acomponent)^;
try
PClass(AComponent)^ := TDataSet;
DefaultEditor := GetComponentEditor(AComponent, ADesigner);
finally
PClass(AComponent)^ := CompClass;
end;
end;
destructor TFIBGenSQlEd.Destroy;
begin
{$IFDEF D6+}
// DefaultEditor._Release;
// DefaultEditor.;
{$ELSE}
DefaultEditor.Free;
{$ENDIF}
inherited Destroy
end;
function TFIBGenSQlEd.GetVerbCount: Integer;
begin
Result := DefaultEditor.GetVerbCount + 4
end;
function TFIBGenSQlEd.GetVerb(Index: Integer): string;
begin
if Index < DefaultEditor.GetVerbCount then
Result := DefaultEditor.GetVerb(Index)
else
case Index - DefaultEditor.GetVerbCount of
0: Result := SCompEditSQLGenerator;
1: Result := SCompSaveToDataSetInfo;
2: Result := SCompChooseDataSetInfo;
3: Result := SCheckSQLs;
end;
end;
procedure TFIBGenSQlEd.ExecuteVerb(Index: Integer);
var SText:string;
k:integer;
Reopen:boolean;
ErrStr:string;
ids:IFIBDataSet;
iqry:IFIBQuery;
idb:IFIBConnect;
curObj:TObject;
begin
if ObjSupports(Component,IFIBDataSet,ids) then
if Index < DefaultEditor.GetVerbCount then
with TDataSet(Component) do
begin
try
Reopen:=Active;
Close;
{ QSelect.FreeHandle;
if Database<>nil then
ListTableInfo.ClearForDataBase(Database);}
ids.Prepare;
if Reopen then Open;
except
end;
DefaultEditor.ExecuteVerb(Index);
end
else
begin
SText:=TStrings(GetObjectProp(Component,'SelectSQL')).Text;
case Index - DefaultEditor.GetVerbCount of
0: ShowDataSetSQLEditor(Component,0,Designer);
1: SaveDataSetInfo;
2:
begin
// try to connect
(* if (not Assigned(TpFibDataSet(Component).DataBase)) or
(not TpFibDataSet(Component).DataBase.Connected) then
*)
curObj:=GetObjectProp(Component,'Database');
if not Assigned(curObj) or
not GetPropValue(CurObj,'Connected') then
begin
MessageDlg(SCompDatabaseNotConnected, mtConfirmation, [mbOK], 0);
Exit;
end;
ObjSupports(curObj,IFIBConnect,idb);
if idb.QueryValueAsStr(qryExistTable,0,['FIB$DATASETS_INFO'])='0' then
begin
if
MessageDlg(SCompEditInfoTableNotExist, mtConfirmation, [mbOK, mbCancel], 0
) <> mrOk
then Exit;
CreateDataSetRepositoryTable(idb);
end;
k := GetPropValue(Component,'DataSet_ID',False);
ChooseDSInfo(TDataSet(Component));
if k <> GetPropValue(Component,'DataSet_ID',False) then
Designer.Modified
end;
3:
with TDataSet(Component) do
begin
ErrStr:=SErrorIn;
curObj:=FindComponent('SelectQuery');
if ObjSupports(curObj,IFIBQuery,iqry) then
if TStrings(GetObjectProp(Component,'SelectSQL')).Count>0 then
try
iqry.CheckValidStatement;
except
ErrStr:=ErrStr+'SelectSQL'#13#10;
end;
curObj:=FindComponent('UpdateQuery');
if ObjSupports(curObj,IFIBQuery,iqry) then
if TStrings(GetObjectProp(Component,'UpdateSQL')).Count>0 then
try
iqry.CheckValidStatement;
except
ErrStr:=ErrStr+'UpdateSQL'#13#10;
end;
curObj:=FindComponent('DeleteQuery');
if ObjSupports(curObj,IFIBQuery,iqry) then
if TStrings(GetObjectProp(Component,'DeleteSQL')).Count>0 then
try
iqry.CheckValidStatement;
except
ErrStr:=ErrStr+'DeleteSQL'#13#10;
end;
curObj:=FindComponent('InsertQuery');
if ObjSupports(curObj,IFIBQuery,iqry) then
if TStrings(GetObjectProp(Component,'InsertSQL')).Count>0 then
try
iqry.CheckValidStatement;
except
ErrStr:=ErrStr+'InsertSQL'#13#10;
end;
curObj:=FindComponent('RefreshQuery');
if ObjSupports(curObj,IFIBQuery,iqry) then
if TStrings(GetObjectProp(Component,'RefreshSQL')).Count>0 then
try
iqry.CheckValidStatement;
except
ErrStr:=ErrStr+'RefreshSQL'#13#10;
end;
if ErrStr<>SErrorIn then
ShowMessage(ErrStr)
else
ShowMessage(SNoErrors)
end;
end;
if SText<>TStrings(GetObjectProp(Component,'SelectSQL')).Text then
Designer.Modified;
end;
end;
const
ExchangeDelimeter='#$#$';
type THackCondition=class
private
FOwner:TObject;
FEnabled:boolean;
end;
function GetConditionsExchangeStr(Conditions:TStrings):string;
var
i:integer;
begin
Result:='';
with Conditions do
for i:=0 to Pred(Count) do
Result:=Result+
Names[i]+ExchangeDelimeter+Values[Names[i]]+ExchangeDelimeter+IntToStr(Ord(THackCondition(Objects[i]).FEnabled))+#13#10
end;
procedure SaveFIBDataSetInfo(Database,DataSet:TObject;DS_ID:integer);
var
iDB:IFIBConnect;
begin
if ObjSupports(Database,IFIBConnect,iDB) then
begin
if idb.QueryValueAsStr('SELECT Count(*) FROM FIB$DATASETS_INFO WHERE DS_ID=:DS_ID',0,[DS_ID])='0' then
idb.Execute('INSERT INTO FIB$DATASETS_INFO (DS_ID,UPDATE_ONLY_MODIFIED_FIELDS) VALUES('+
IntToStr(DS_ID)+',1)'
);
idb.Execute(
'Update FIB$DATASETS_INFO SET '#13#10+
'SELECT_SQL='''+TStrings(GetObjectProp(DataSet,'SelectSQL')).Text+''','#13#10+
'INSERT_SQL='''+TStrings(GetObjectProp(DataSet,'InsertSQL')).Text+''','#13#10+
'UPDATE_SQL='''+TStrings(GetObjectProp(DataSet,'UpdateSQL')).Text+''','#13#10+
'DELETE_SQL='''+TStrings(GetObjectProp(DataSet,'DeleteSQL')).Text+''','#13#10+
'REFRESH_SQL='''+TStrings(GetObjectProp(DataSet,'RefreshSQL')).Text+''','#13#10+
'KEY_FIELD='''+GetPropStringValue(Dataset,'AutoUpdateOptions.KeyFields')+''','#13#10+
'NAME_GENERATOR='''+GetPropStringValue(Dataset,'AutoUpdateOptions.GeneratorName')+''','#13#10+
'DESCRIPTION='''+GetPropStringValue(Dataset,'Description')+''','#13#10+
'UPDATE_TABLE_NAME='''+GetPropStringValue(Dataset,'AutoUpdateOptions.UpdateTableName')+''','#13#10+
'UPDATE_ONLY_MODIFIED_FIELDS='''+IntToStr(GetSubPropValue(Dataset,'AutoUpdateOptions.UpdateOnlyModifiedFields'))+''','#13#10+
'CONDITIONS='''+GetConditionsExchangeStr(TStrings(GetObjectProp(DataSet,'Conditions')))+''''#13#10+
'WHERE DS_ID='+IntToStr(DS_ID)
)
end
end;
procedure TFIBGenSQlEd.SaveDataSetInfo;
var
vDescription:string;
DS_ID:integer;
DB:TObject;
idb:IFIBConnect;
begin
DS_ID:=GetPropValue(Component,'DataSet_ID',False);
with Component do
if DS_ID=0 then
ShowMessage(Name + SCompEditDataSet_ID)
else
begin
DB:=GetObjectProp(Component,'Database');
if DB=nil then
ShowMessage(SDataBaseNotAssigned)
else
begin
ObjSupports(DB,IFIBConnect,idb);
if idb.QueryValueAsStr(qryExistTable,0,['FIB$DATASETS_INFO'])='0' then
begin
if
MessageDlg(SCompEditInfoTableNotExist, mtConfirmation, [mbOK, mbCancel], 0
) <> mrOk
then Exit;
CreateDataSetRepositoryTable(idb);
end;
vDescription:=GetPropValue(Component,'Description');
{ if not InputQuery(SCompEditSaveDataSetProperty, SCompEditDataSetDesc, vDescription) then
Exit;
// SetPropValue(Component,'Description',vDescription);}
SaveFIBDataSetInfo(DB,Component,DS_ID);
end
end;
end;
{ TDataSet_ID_Edit }
procedure TDataSet_ID_Edit.Edit;
var
OldID: integer;
DB:TObject;
iDB:iFIBConnect;
begin
OldID := GetPropValue( GetComponent(0),'DataSet_ID',False);
DB:= GetObjectProp(GetComponent(0),'Database');
if DB=nil then
Exit
else
if ObjSupports(DB,iFIBConnect,iDB) then
begin
if iDB.QueryValueAsStr(qryExistTable,0,['FIB$DATASETS_INFO'])='0' then
begin
// if not (urDataSetInfo in DataBase.UseRepositories) then
if not GetValueInSet(DB,'UseRepositories','urDataSetInfo') then
raise Exception.Create(SCompEditDataSetInfoForbid);
if
MessageDlg(SCompEditInfoTableNotExist, mtConfirmation, [mbOK, mbCancel], 0
) <> mrOk
then
Exit;
CreateDataSetRepositoryTable(iDB);
end;
ChooseDSInfo(TDataSet(GetComponent(0)));
if OldID <> GetPropValue( GetComponent(0),'DataSet_ID',False) then
Modified
end
end;
function TDataSet_ID_Edit.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog];
end;
{ TFIBSQLsProperties }
function TFIBSQLsProperties.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog,paSubProperties];
end;
function TFIBSQLsProperties.GetValue: string;
begin
Result := '(SQLs)'
end;
procedure TFIBSQLsProperties.Edit;
begin
ShowDataSetSQLEditor(TComponent(GetComponent(0)),0,Designer);
end;
{ TFIBSQLsProperty }
type THackSQls=class(TPersistent)
private
FOwner :TComponent;
end;
procedure TFIBSQLsProperty.Edit;
var pName:string;
KindSQL:integer;
begin
pName:=GetPropInfo^.Name;
if pName='SelectSQL' then
KindSQL:=0
else
if pName='UpdateSQL' then
KindSQL:=2
else
if pName='InsertSQL' then
KindSQL:=1
else
if pName='DeleteSQL' then
KindSQL:=3
else
KindSQL:=4;
if not FindPropInCode(THackSQls(GetComponent(0)).FOwner,pName) then
ShowDataSetSQLEditor(THackSQls(GetComponent(0)).FOwner,KindSQL,Designer);
end;
function TFIBSQLsProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog] - [paSubProperties];
end;
function TFIBSQLsProperty.GetValue: string;
begin
Result := SCompEditSQLText;
end;
{ TpFIBSQLPropEdit }
procedure TpFIBSQLPropEdit.Edit;
begin
// if GetComponent(0) is TpFIBQuery then
begin
if not FindPropInCode(TComponent(GetComponent(0)),'SQL') then
if ShowSQLEdit(TComponent(GetComponent(0))) then
Modified;
FindPropInCode(TComponent(GetComponent(0)),'SQL');
end;
end;
function TpFIBSQLPropEdit.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog] - [paSubProperties];
end;
{ TTableNameEditDR }
function TTableNameEditDR.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
Result := Result + [paValueList]
end;
const
QRYTables =
'SELECT REL.RDB$RELATION_NAME FROM RDB$RELATIONS REL WHERE ' +
'(REL.RDB$SYSTEM_FLAG <> 1 OR REL.RDB$SYSTEM_FLAG IS NULL) AND ' +
'(NOT REL.RDB$FLAGS IS NULL) AND ' +
'(REL.RDB$VIEW_BLR IS NULL) AND ' +
'(REL.RDB$SECURITY_CLASS STARTING WITH ''SQL$'') ' +
'ORDER BY REL.RDB$RELATION_NAME';
procedure TTableNameEditDR.GetValues(Proc: TGetStrProc);
var
edComponent:TPersistent;
DB:TObject;
Qry:TComponent;
Trans :TObject;
iQry:IFIBQuery;
trActive:boolean;
begin
edComponent:= GetComponent(0) ;
Trans:=GetObjectProp(edComponent,'Transaction');
if not Assigned(Trans) then Exit;
trActive:=GetPropValue(Trans,'Active');
if not trActive then
SetPropValue(Trans,'Active',True);
DB:=GetObjectProp(Trans,'DefaultDatabase');
Qry:= expQueryClass.Create(nil);
SetPropValue(Qry,'ParamCheck','False');
SetObjectProp(Qry,'Database',DB);
SetObjectProp(Qry,'Transaction',Trans);
AssignStringsToProp(Qry,'SQL',QRYTables);
try
try
try
ObjSupports(Qry, IFIBQuery,iQry);
iQry.ExecQuery;
while not iQry.iEof do
begin
Proc(
Trim(
VarToStr(iQry.FieldValue('RDB$RELATION_NAME',False))
)
);
iQry.iNext;
end;
iQry.Close;
finally
SetPropValue(Trans,'Active','False');
end;
except
end
finally
if not trActive then
SetPropValue(Trans,'Active',False);
iQry:=nil;
Qry.Free;
end;
end;
{ TpFIBDeltaReceiverEditor }
procedure TpFIBDeltaReceiverEditor.ExecuteVerb(Index: Integer);
var
TableName:string;
DelTableName,TriggerName:string;
DB:TObject;
Qry:TComponent;
Trans :TObject;
iQry:IFIBQuery;
iTrans:IFIBTransaction;
trActive:boolean;
ErrMessage:string;
Script:TStrings;
Stringer:IFIBStringer;
clExp:IFIBClassesExporter;
procedure ExecStatement(const SQL:string);
begin
AssignStringsToProp(Qry,'SQL',SQL);
try
iQry.ExecQuery;
except
on E:Exception do
ErrMessage:=ErrMessage+#13#10+E.Message
end;
end;
begin
Trans:=GetObjectProp(Component,'Transaction');
if not Assigned(Trans) then
begin
ShowMessage(SCompEditDeltaReceiverErr2);
Exit;
end;
DB:=GetObjectProp(Trans,'DefaultDatabase');
{ trActive:=GetPropValue(Trans,'Active');
if not trActive then
SetPropValue(Trans,'Active',True);
DB:=GetObjectProp(Trans,'DefaultDatabase');
Qry:= expQueryClass.Create(nil);
SetPropValue(Qry,'ParamCheck','False');
SetObjectProp(Qry,'Database',DB);
SetObjectProp(Qry,'Transaction',Trans);
ObjSupports(Qry, IFIBQuery,iQry);
ErrMessage:='';}
Script:=TStringList.Create;
try
case Index of
0:
begin
Script.Add('/***************************************');
Script.Add('Common metadata for TableChangesReader supports');
if Assigned(DB) then
Script.Add('Database: '+GetPropStringValue(DB,'DBName'));
Script.Add('***************************************/');
Script.Add('');
Script.Add('CREATE DOMAIN FIB$BIGINT AS BIGINT;');
Script.Add('CREATE DOMAIN FIB$TIMESTAMP AS TIMESTAMP;');
Script.Add('CREATE GENERATOR FIB$GEN_COMMIT_NO;');
Script.Add('CREATE GENERATOR FIB$GEN_TRANSACTION_ID;');
//
Script.Add('');
Script.Add('CREATE TABLE FIB$TRANSACTIONS(');
Script.Add(' TRANSACTION_ID FIB$BIGINT,');
Script.Add(' COMMIT_NO FIB$BIGINT ,');
Script.Add(' COMMIT_TIME FIB$TIMESTAMP');
Script.Add(');');
Script.Add('');
Script.Add('CREATE DESCENDING INDEX IDX_FIB$COMMIT_NO ON FIB$TRANSACTIONS (COMMIT_NO);');
Script.Add('');
Script.Add('SET TERM ^ ;');
Script.Add('');
Script.Add('CREATE PROCEDURE FIB$CLEAR_TRANSACTION_ID ');
Script.Add('AS BEGIN ');
Script.Add(' rdb$set_context(''USER_TRANSACTION'',''FIB$TRANSACTION_ID'',NULL);');
Script.Add('END ^');
Script.Add('');
Script.Add('CREATE PROCEDURE FIB$GET_TRANSACTION_ID ( FORCE SMALLINT )');
Script.Add('RETURNS ( TRANS_ID BIGINT) ');
Script.Add('AS');
Script.Add('BEGIN ');
Script.Add(' TRANS_ID=rdb$get_context(''USER_TRANSACTION'',''FIB$TRANSACTION_ID'');');
Script.Add(' if ((TRANS_ID is NULL) AND (FORCE=1)) then');
Script.Add(' begin');
Script.Add(' TRANS_ID=GEN_ID(FIB$GEN_TRANSACTION_ID,1);');
Script.Add(' rdb$set_context(''USER_TRANSACTION'',''FIB$TRANSACTION_ID'',:TRANS_ID);');
Script.Add(' end');
Script.Add(' suspend;');
Script.Add('END ^');
Script.Add('');
Script.Add('CREATE TRIGGER FIB$ON_TRANSACTION_ROLLBACK ');
Script.Add('ACTIVE ON TRANSACTION ROLLBACK POSITION 0');
Script.Add('AS ');
Script.Add('BEGIN');
Script.Add(' EXECUTE PROCEDURE FIB$CLEAR_TRANSACTION_ID;');
Script.Add('END ^');
Script.Add('');
Script.Add('CREATE TRIGGER FIB$ON_TRANSACTION_COMMIT');
Script.Add('ACTIVE ON TRANSACTION COMMIT POSITION 0');
Script.Add('AS ');
Script.Add(' DECLARE TRANS_ID BIGINT;');
Script.Add(' DECLARE COMMIT_NO BIGINT;');
Script.Add('BEGIN');
Script.Add(' Select TRANS_ID From FIB$GET_TRANSACTION_ID(0) INTO :TRANS_ID;');
Script.Add(' if (NOT TRANS_ID is NULL) then');
Script.Add(' begin');
Script.Add(' COMMIT_NO=GEN_ID(FIB$GEN_COMMIT_NO,1);');
Script.Add(' insert into FIB$TRANSACTIONS (TRANSACTION_ID,COMMIT_NO,COMMIT_TIME)');
Script.Add(' values(:TRANS_ID,:COMMIT_NO,''NOW'');');
Script.Add(' EXECUTE PROCEDURE FIB$CLEAR_TRANSACTION_ID;');
Script.Add(' end');
Script.Add('END ^');
Script.Add('');
Script.Add('COMMIT WORKS ^');
ShowScript('Common metadata for DeltaReceiver supports',DB,Script);
end;
1:
begin
TableName:=GetPropStringValue(Component,'TableName');
if Length(TableName)= 0 then
ShowMessage(SCompEditDeltaReceiverErr1);
Script.Add('/***************************************');
Script.Add('Common metadata for TableChangesReader supports');
if Assigned(DB) then
Script.Add('Database: '+GetPropStringValue(DB,'DBName'));
Script.Add('***************************************/');
Script.Add('');
Supports(FIBClassesExporter,IFIBClassesExporter,clExp);
Stringer:=clExp.iGetStringer;
DelTableName:=Stringer.FormatIdentifier(3,TableName+'_DELETED');
TriggerName:=Stringer.FormatIdentifier(3, 'FIB$TRANSLOG_'+TableName);
TableName:=Stringer.FormatIdentifier(3,TableName);
Script.Add('ALTER TABLE '+TableName+' ADD FIB$TRANSACTION_ID FIB$BIGINT;');
Script.Add('ALTER TABLE '+TableName+' ADD FIB$UPDATE_TIME FIB$TIMESTAMP;');
Script.Add('');
Script.Add('CREATE TABLE '+DelTableName+'(');
Script.Add(' ID FIB$BIGINT NOT NULL,');
Script.Add(' FIB$TRANSACTION_ID FIB$BIGINT,');
Script.Add(' FIB$DELETED_TIME FIB$TIMESTAMP');
Script.Add(' );');
Script.Add('');
Script.Add('SET TERM ^ ;');
Script.Add('');
Script.Add('CREATE TRIGGER '+TriggerName+' FOR '+TableName);
Script.Add('ACTIVE BEFORE INSERT OR UPDATE OR DELETE POSITION 0');
Script.Add('AS');
Script.Add(' DECLARE VARIABLE TRANS_ID BIGINT;');
Script.Add('BEGIN');
Script.Add(' Select TRANS_ID From FIB$GET_TRANSACTION_ID(1) INTO :TRANS_ID;');
Script.Add(' if (DELETING) then');
Script.Add(' Insert into '+DelTableName+'(ID,FIB$TRANSACTION_ID,FIB$DELETED_TIME)');
Script.Add(' values (Old.ID,:TRANS_ID,''NOW'');');
Script.Add(' else');
Script.Add(' begin');
Script.Add(' new.FIB$TRANSACTION_ID=:TRANS_ID;');
Script.Add(' new.FIB$UPDATE_TIME =''NOW'';');
Script.Add(' end');
Script.Add('END ^');
Script.Add('');
Script.Add('COMMIT WORKS ^');
ShowScript(' Metadata for DeltaReceiver supports',DB,Script);
end;
end;
finally
Script.Free;
if not trActive then
SetPropValue(Trans,'Active',False);
iQry:=nil;
Qry.Free;
end
end;
function TpFIBDeltaReceiverEditor.GetVerb(Index: Integer): string;
var
TableName:string;
begin
case Index of
0: Result := SCompEditDeltaReceiver1;
1:
begin
TableName:=GetPropStringValue(Component,'TableName');
Result := Format(SCompEditDeltaReceiver2,[TableName]);
end
end;
end;
function TpFIBDeltaReceiverEditor.GetVerbCount: Integer;
begin
Result:=2;
end;
{ TpFIBGeneratorsProperty }
type
TPersistentCracker = class(TPersistent);
procedure TpFIBGeneratorsProperty.Edit;
var
Obj: TPersistent;
begin
Obj := GetComponent(0);
while (Obj <> nil) and not (Obj is TComponent) do
Obj := TPersistentCracker(Obj).GetOwner;
ShowCollectionEditorClass(Designer, TCollectionEditor, TComponent(Obj),
TCollection(GetOrdValue), 'GeneratorList', [coAdd, coDelete, coMove]);
end;
function TpFIBGeneratorsProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paReadOnly ];
end;
function TpFIBGeneratorsProperty.GetValue: string;
begin
// FmtStr(Result, '(%s)', [GetPropType^.Name]);
Result:='TGeneratorList'
end;
end.
|
(**
This module contains a class which represents a form on which the project options for
the active project can be edited.
@Author David Hoyle
@Version 1.0
@Date 05 Jan 2018
**)
Unit ITHelper.ProjectOptionsDialogue;
Interface
{$I 'CompilerDefinitions.inc'}
Uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
Buttons,
StdCtrls,
ToolsAPI,
ITHelper.Interfaces,
Grids,
ValEdit,
ComCtrls;
Type
(** A class to represent the project options form. **)
TfrmITHProjectOptionsDialogue = Class(TForm)
lblResExts: TLabel;
lblVersionInfo: TLabel;
chkIncrementBuildOnCompile: TCheckBox;
edtResExts: TEdit;
edtVersionInfo: TEdit;
btnOpenEXE: TButton;
btnOK: TBitBtn;
btnCancel: TBitBtn;
dlgOpenEXE: TOpenDialog;
vleVersionInfo: TValueListEditor;
gbxVersionInfo: TGroupBox;
chkEnabled: TCheckBox;
lblMajor: TLabel;
edtMajor: TEdit;
upMajor: TUpDown;
edtMinor: TEdit;
upMinor: TUpDown;
lblMinor: TLabel;
edtRelease: TEdit;
upRelease: TUpDown;
lblRelease: TLabel;
edtBuild: TEdit;
upBuild: TUpDown;
lblBuild: TLabel;
btnGetVersionInfo: TBitBtn;
chkIncludeInProject: TCheckBox;
chkCompileWithBRCC32: TCheckBox;
lblResourceName: TLabel;
edtResourceName: TEdit;
btnHelp: TBitBtn;
Procedure btnOpenEXEClick(Sender: TObject);
Procedure chkEnabledClick(Sender: TObject);
Procedure BuildChange(Sender: TObject; Button: TUDBtnType);
Procedure btnGetVersionInfoClick(Sender: TObject);
procedure btnHelpClick(Sender: TObject);
Private
{ Private declarations }
FProject : IOTAProject;
Procedure InitialiseOptions(Const GlobalOps: IITHGlobalOptions; Const Project: IOTAProject);
Procedure SaveOptions(Const GlobalOps: IITHGlobalOptions; Const Project: IOTAProject);
Public
{ Public declarations }
Class Procedure Execute(Const GlobalOps: IITHGlobalOptions; Const Project: IOTAProject);
End;
Implementation
{$R *.dfm}
Uses
IniFiles,
{$IFDEF DXE20}
CommonOptionStrs,
{$ENDIF}
ITHelper.TestingHelperUtils;
Const
(** An INI Section name for the dialogue settings. **)
strProjectDlgSection = 'Project Dlg';
(** An INI key for the dialogue top. **)
strTopKey = 'Top';
(** An INI key for the dialogue left. **)
strLeftKey = 'Left';
(** An INI key for the dialogue height. **)
strHeightKey = 'Height';
(** An INI key for the dialogue width. **)
strWidthKey = 'Width';
(**
This is an on click event handler for the GetvVersionInfo button.
@precon None.
@postcon Extracts the version information from the IDE.
@param Sender as a TObject
**)
Procedure TfrmITHProjectOptionsDialogue.btnGetVersionInfoClick(Sender: TObject);
Const
strMsg = 'Are you sure you want to replace the current version information with the ' +
'version information from the IDE?';
strMajorVersion = 'MajorVersion';
strMinorVersion = 'MinorVersion';
strRelease = 'Release';
strBuild = 'Build';
strKeys = 'Keys';
Var
S : TStrings;
{$IFNDEF DXE20}
PO : IOTAProjectOptions;
i : Integer;
sl : TStrings;
{$ELSE}
POC : IOTAProjectOptionsConfigurations;
AC : IOTABuildConfiguration;
{$ENDIF}
Begin
If MessageDlg(strMsg, mtConfirmation, [mbYes, mbNo], 0) <> mrYes Then
Exit;
{$IFDEF DXE20}
If FProject.ProjectOptions.QueryInterface(IOTAProjectOptionsConfigurations,
POC) = S_OK Then
Begin
AC := POC.ActiveConfiguration;
upMajor.Position := AC.AsInteger[sVerInfo_MajorVer];
upMinor.Position := AC.AsInteger[sVerInfo_MinorVer];
upRelease.Position := AC.AsInteger[sVerInfo_Release];
upBuild.Position := AC.AsInteger[sVerInfo_Build];
S := vleVersionInfo.Strings;
S.Text := StringReplace(AC.Value[sVerInfo_Keys], ';', #13#10, [rfReplaceAll]);
End;
{$ELSE}
PO := FProject.ProjectOptions;
upMajor.Position := PO.Values[strMajorVersion];
upMinor.Position := PO.Values[strMinorVersion];
upRelease.Position := PO.Values[strRelease];
upBuild.Position := PO.Values[strBuild];
i := VarAsType(PO.Values[strKeys], varInteger);
sl := TStrings(i);
S := vleVersionInfo.Strings;
S.Assign(sl);
S.Text := StringReplace(S.Text, ';', #13#10, [rfReplaceAll]);
{$ENDIF}
End;
(**
This is an on click event handler for the Help button.
@precon None.
@postcon Displays the Project Options help page.
@param Sender as a TObject
**)
Procedure TfrmITHProjectOptionsDialogue.btnHelpClick(Sender: TObject);
Const
strProjectOptions = 'ProjectOptions';
Begin
HTMLHelp(0, PChar(ITHHTMLHelpFile(strProjectOptions)), HH_DISPLAY_TOPIC, 0);
End;
(**
This is an on click event handler for the Browse Zip EXE button.
@precon None.
@postcon Allows the user to select a zip executable.
@param Sender as a TObject
**)
Procedure TfrmITHProjectOptionsDialogue.btnOpenEXEClick(Sender: TObject);
Begin
dlgOpenEXE.FileName := edtVersionInfo.Text;
If dlgOpenEXE.Execute Then
edtVersionInfo.Text := dlgOpenEXE.FileName;
End;
(**
This is an on change event handler for the Build controls (Major, Minor, Release and
Build) control.
@precon None.
@postcon Updates the FileVersion member of the version information strings.
@param Sender as a TObject
@param Button as a TUDBtnType
**)
Procedure TfrmITHProjectOptionsDialogue.BuildChange(Sender: TObject; Button: TUDBtnType);
Const
strFileVersion = 'FileVersion';
Var
S : TStrings;
Begin
S := vleVersionInfo.Strings;
If S.IndexOfName(strFileVersion) > -1 Then
S.Values[strFileVersion] :=
Format('%d.%d.%d.%d', [upMajor.Position, upMinor.Position, upRelease.Position,
upBuild.Position]);
End;
(**
This is an on click event handler for the Enabled checkbox.
@precon None.
@postcon Enables of disables the grouop box accordingly.
@param Sender as a TObject
**)
Procedure TfrmITHProjectOptionsDialogue.chkEnabledClick(Sender: TObject);
Begin
gbxVersionInfo.Enabled := chkEnabled.Checked;
lblMajor.Enabled := chkEnabled.Checked;
edtMajor.Enabled := chkEnabled.Checked;
upMajor.Enabled := chkEnabled.Checked;
lblMinor.Enabled := chkEnabled.Checked;
edtMinor.Enabled := chkEnabled.Checked;
upMinor.Enabled := chkEnabled.Checked;
lblRelease.Enabled := chkEnabled.Checked;
edtRelease.Enabled := chkEnabled.Checked;
upRelease.Enabled := chkEnabled.Checked;
lblBuild.Enabled := chkEnabled.Checked;
edtBuild.Enabled := chkEnabled.Checked;
upBuild.Enabled := chkEnabled.Checked;
vleVersionInfo.Enabled := chkEnabled.Checked;
chkIncludeInProject.Enabled := chkEnabled.Checked;
chkCompileWithBRCC32.Enabled := chkEnabled.Checked;
lblResourceName.Enabled := chkEnabled.Checked;
edtResourceName.Enabled := chkEnabled.Checked;
btnGetVersionInfo.Enabled := chkEnabled.Checked;
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
@param Project as an IOTAProject as a constant
**)
Class Procedure TfrmITHProjectOptionsDialogue.Execute(Const GlobalOps: IITHGlobalOptions;
Const Project: IOTAProject);
ResourceString
strProjectOptionsFor = 'Project Options for %s';
Var
frm: TfrmITHProjectOptionsDialogue;
Begin
frm := TfrmITHProjectOptionsDialogue.Create(Nil);
Try
frm.Caption := Format(strProjectOptionsFor, [GetProjectName(Project)]);
frm.FProject := Project;
frm.InitialiseOptions(GlobalOps, Project);
frm.chkEnabledClick(Nil);
If frm.ShowModal = mrOK Then
frm.SaveOptions(GlobalOps, Project);
Finally
frm.Free;
End;
End;
(**
This method initialises the dialogue controls with information from the global options and the project
options.
@precon GlobalOps and Project must be valid instances.
@postcon Initialises the dialogue controls with information from the global options and the project
options.
@param GlobalOps as a IITHGlobalOptions as a constant
@param Project as an IOTAProject as a constant
**)
Procedure TfrmITHProjectOptionsDialogue.InitialiseOptions(Const GlobalOps: IITHGlobalOptions;
Const Project: IOTAProject);
Var
iniFile: TMemIniFile;
ProjectOps: IITHProjectOptions;
Begin
iniFile := TMemIniFile.Create(GlobalOps.INIFileName);
Try
Top := iniFile.ReadInteger(strProjectDlgSection, strTopKey, (Screen.Height - Height) Div 2);
Left := iniFile.ReadInteger(strProjectDlgSection, strLeftKey, (Screen.Width - Width) Div 2);
Height := iniFile.ReadInteger(strProjectDlgSection, strHeightKey, Height);
Width := iniFile.ReadInteger(strProjectDlgSection, strWidthKey, Width);
Finally
iniFile.Free;
End;
ProjectOps := GlobalOps.ProjectOptions(Project);
Try
chkIncrementBuildOnCompile.Checked := ProjectOps.IncOnCompile;
edtVersionInfo.Text := ProjectOps.CopyVerInfo;
edtResExts.Text := ProjectOps.ResExtExc;
chkEnabled.Checked := ProjectOps.IncITHVerInfo;
chkIncludeInProject.Checked := ProjectOps.IncResInProj;
chkCompileWithBRCC32.Checked := ProjectOps.CompileRes;
upMajor.Position := ProjectOps.Major;
upMinor.Position := ProjectOps.Minor;
upRelease.Position := ProjectOps.Release;
upBuild.Position := ProjectOps.Build;
edtResourceName.Text := ProjectOps.ResourceName;
vleVersionInfo.Strings.Assign(ProjectOps.VerInfo);
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
@param Project as an IOTAProject as a constant
**)
Procedure TfrmITHProjectOptionsDialogue.SaveOptions(Const GlobalOps: IITHGlobalOptions;
Const Project: IOTAProject);
Var
iniFile: TMemIniFile;
ProjectOps: IITHProjectOptions;
Begin
iniFile := TMemIniFile.Create(GlobalOps.INIFileName);
Try
iniFile.WriteInteger(strProjectDlgSection, strTopKey, Top);
iniFile.WriteInteger(strProjectDlgSection, strLeftKey, Left);
iniFile.WriteInteger(strProjectDlgSection, strHeightKey, Height);
iniFile.WriteInteger(strProjectDlgSection, strWidthKey, Width);
iniFile.UpdateFile;
Finally
iniFile.Free;
End;
ProjectOps := GlobalOps.ProjectOptions(Project);
Try
ProjectOps.IncOnCompile := chkIncrementBuildOnCompile.Checked;
ProjectOps.CopyVerInfo := edtVersionInfo.Text;
ProjectOps.ResExtExc := edtResExts.Text;
ProjectOps.IncITHVerInfo := chkEnabled.Checked;
ProjectOps.IncResInProj := chkIncludeInProject.Checked;
ProjectOps.CompileRes := chkCompileWithBRCC32.Checked;
ProjectOps.Major := upMajor.Position;
ProjectOps.Minor := upMinor.Position;
ProjectOps.Release := upRelease.Position;
ProjectOps.Build := upBuild.Position;
ProjectOps.ResourceName := edtResourceName.Text;
ProjectOps.VerInfo.Assign(vleVersionInfo.Strings);
Finally
ProjectOps := Nil;
End;
End;
End.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ UDDI Browser }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit UDDIHlprDesign;
interface
uses
inquire_v1, Classes;
type
{ Interface that caches UDDI Search Results }
IUDDIResultCache = interface
{ find_Business }
function GetBusinessList: BusinessList;
procedure SetBusinessList(const BL: BusinessList);
{ get_BusinessDetail }
function GetBusinessDetail: BusinessDetail;
procedure SetBusinessDetail(const BT: BusinessDetail);
{ get_ServiceDetail }
function FindServiceDetail(serviceKey: String): ServiceDetail;
procedure SetServiceDetail(const serviceKey: String; const SD: ServiceDetail);
{ get_tModelDetail }
function FindTModelDetail(tModelKey: String): TModelDetail;
procedure SetTModelDetail(const tModelKey: String; const TMD: TModelDetail);
{ Clear cached data }
procedure Clear;
property BusinessList: BusinessList read GetBusinessList write SetBusinessList;
property BusinessDetail: BusinessDetail read GetBusinessDetail write SetBusinessDetail;
end;
{ Interface that caches information about a binding we might want to import }
IImportBindingInfo = interface
['{752A6BF3-0B91-4099-91E6-E0481AA2D460}']
function GetWSDLLocation: WideString;
procedure SetWSDLLocation(const AWSDLLocation: WideString);
function GetUDDIOperator: WideString;
procedure SetUDDIOperator(const AOperator: WideString);
function GetHostingRedirector: WideString;
procedure SetHostingRedirector(const AHostRedirector: WideString);
function GetBindingKey: WideString;
procedure SetBindingKey(const ABindingKey: WideString);
function GetSOAPEndpoint: WideString;
procedure SetSOAPEndpoint(const ASOAPEndpoint: WideString);
property WSDLLocation: WideString read GetWSDLLocation write SetWSDLLocation;
property UDDIOperator: WideString read GetUDDIOperator write SetUDDIOperator;
property BindingKey: WideString read GetBindingKey write SetBindingKey;
property SOAPEndpoint: WideString read GetSOAPEndpoint write SetSOAPEndpoint;
property HostingRedirector: WideString read GetHostingRedirector write SetHostingRedirector;
end;
{ Returns object that can cache Search Result }
function GetUDDIResultCache: IUDDIResultCache;
{ Returns object that implements IImportBindingInfo }
function GetImportBindingInfo: IImportBindingInfo;
{ Wrappers around UDDI API }
function FindBus(const Service: InquireSoap; maxRows: Integer; const Name: String;
ExactMatch: Boolean; CaseSensitive: Boolean): BusinessList; overload;
function FindBus(const Service: InquireSoap; maxRows: Integer; const DiscURLs: TStrings): BusinessList; overload;
function FindSvc(const Service: InquireSoap;
maxRows: Integer;
const Name: String;
ExactMatch: Boolean;
CaseSensitive: Boolean): ServiceList;
function GetSvcDetail(const Service: InquireSoap; const sKey: String): ServiceDetail;
function GetBusDetail(const Service: InquireSoap; const bInfo: BusinessInfo): BusinessDetail;
function GetTModDetail(const Service: InquireSoap; const tModKey: String): TModelDetail;
function GetTModelOfWSDL(const TMD: TModelDetail): TModel; overload;
function GetTModelOfWSDL(const Service: InquireSoap; const tModKey: String): TModel; overload;
function GetBindingkeyDetail(const Service: InquireSoap; const key: String): BindingDetail; overload;
function GetBindingkeyDetail(const Operator: String; const key: String): BindingDetail; overload;
function GetBindingkeyImportInfo(const Operator: String; const key: String): IImportBindingInfo; overload;
function GetBindingkeyImportInfo(const Service: InquireSOAP; const Operator: String; const key: String): IImportBindingInfo; overload;
function GetWSDL(const Service: InquireSoap; const BTemplate: BindingTemplate; var WSDL: string): Boolean; overload;
function GetWSDL(const Operator: String; const key: String): String; overload;
function GetWSDL(const Service: InquireSOAP; const key: String): String; overload;
function GetWSDL(const Service: InquireSOAP; const BD: BindingDetail): String; overload;
implementation
uses
SysUtils, Contnrs, SOAPHTTPClient;
type
{ Implements IUDDIResultCache }
TUDDIResultCache = class(TInterfacedObject, IUDDIResultCache)
private
FBusinessList: BusinessList;
FBusinessDetail: BusinessDetail;
FServiceDetailList: TObjectList;
FTModelDetailList: TObjectList;
public
constructor Create;
destructor Destroy; override;
function GetBusinessList: BusinessList;
procedure SetBusinessList(const BL: BusinessList);
function GetBusinessDetail: BusinessDetail;
procedure SetBusinessDetail(const BT: BusinessDetail);
function FindServiceDetail(serviceKey: String): ServiceDetail;
procedure SetServiceDetail(const serviceKey: String; const SD: ServiceDetail);
function FindTModelDetail(tModelKey: String): TModelDetail;
procedure SetTModelDetail(const tModelKey: String; const TMD: TModelDetail);
procedure Clear;
end;
function GetSvcDetail(const Service: InquireSoap; const sKey: String): ServiceDetail;
var
GSD: GetServiceDetail;
keys: serviceKey;
begin
GSD := GetServiceDetail.Create;
try
SetLength(keys, 1);
keys[0] := sKey;
GSD.serviceKey := keys;
GSD.generic := '1.0';
Result := Service.get_serviceDetail(GSD);
finally
GSD.Free;
end;
end;
function FindBus(const Service: InquireSoap;
maxRows: Integer; const DiscURLs: TStrings): BusinessList;
var
FB: find_business;
DU: DiscoveryURLs;
DUrls: discoveryUrl2;
I: Integer;
begin
FB := find_business.Create;
try
FB.generic := '1.0';
FB.maxRows := maxRows;
DU := DiscoveryURLS.Create;
try
SetLength(DUrls, DiscURLs.Count);
for I := 0 to DiscURLs.Count-1 do
begin
DUrls[I] := DiscoveryURL.Create;
DUrls[I].DiscoveryUrl := DiscURLs[I];
// DUrls[I] := DiscURLs[I];
end;
DU.discoveryUrl := DUrls;
FB.discoveryURLs := DU;
Result := Service.find_business(FB);
finally
{ DU.Free; - Freed by FindBusiness.Destroy }
end;
finally
FB.Free;
end;
end;
function FindBus(const Service: InquireSoap;
maxRows: Integer;
const Name: String;
ExactMatch: Boolean;
CaseSensitive: Boolean): BusinessList;
var
FB: find_business;
FQ: findQualifier;
begin
FB := find_business.Create;
try
FB.generic := '1.0';
FB.maxRows := maxRows;
FB.name := Name;
{ ExactMatch? }
if ExactMatch then
begin
SetLength(FQ, Length(FQ)+1);
FQ[Length(FQ)-1] := 'exactNameMatch'; { do not localize }
end;
{ Case Sensitive ? }
if CaseSensitive then
begin
SetLength(FQ, Length(FQ)+1);
FQ[Length(FQ)-1] := 'caseSensitiveMatch'; { do not localize }
end;
{ Set search qualifiers, if any }
if Length(FQ) > 0 then
begin
FB.findQualifiers := FindQualifiers.Create;
FB.findQualifiers.findQualifier := FQ;
end;
Result := Service.find_business(FB);
finally
FB.Free;
end;
end;
function FindSvc(const Service: InquireSoap;
maxRows: Integer;
const Name: String;
ExactMatch: Boolean;
CaseSensitive: Boolean): ServiceList;
var
FS: find_service;
FQ: findQualifier;
begin
FS := find_service.Create;
try
FS.generic := '1.0';
FS.maxRows := maxRows;
FS.name := Name;
// FS.businessKey := '*';
{ ExactMatch? }
if ExactMatch then
begin
SetLength(FQ, Length(FQ)+1);
FQ[Length(FQ)-1] := 'exactNameMatch'; { do not localize }
end;
{ Case Sensitive ? }
if CaseSensitive then
begin
SetLength(FQ, Length(FQ)+1);
FQ[Length(FQ)-1] := 'caseSensitiveMatch'; { do not localize }
end;
{ Set search qualifiers, if any }
if Length(FQ) > 0 then
begin
FS.findQualifiers := FindQualifiers.Create;
FS.findQualifiers.findQualifier := FQ;
end;
Result := Service.find_service(FS);
finally
FS.Free;
end;
end;
function GetBusDetail(const Service: InquireSoap; const bInfo: BusinessInfo): BusinessDetail;
var
GBD: GetBusinessDetail;
keys: inquire_v1.businessKey;
begin
GBD := GetBusinessDetail.Create;
try
SetLength(keys, 1);
keys[0] := bInfo.businessKey;
GBD.businessKey := keys;
GBD.generic := '1.0';
Result := Service.get_businessDetail(GBD);
finally
GBD.Free;
end;
end;
function GetTModDetail(const Service: InquireSoap; const tModKey: String): TModelDetail;
var
GTM: GetTModelDetail;
keys: tModelKey;
begin
GTM := GetTModelDetail.Create;
try
GTM.generic := '1.0';
SetLength(keys, 1);
keys[0] := tModKey;
GTM.tModelKey := keys;
Result := Service.get_tModelDetail(GTM);
finally
GTM.Free;
end;
end;
function GetTModelOfWSDL(const TMD: TModelDetail): TModel; overload;
var
I, J: Integer;
TM: TModel;
begin
Result := nil;
if Assigned(TMD) then
begin
for I := 0 to TMD.Len-1 do
begin
TM := TMD[I];
if Assigned(TM.overviewDoc) then
begin
{ TM.overviewDoc.description }
{ TM.overviewDoc.overviewURL }
{ TM.operator }
if Assigned(TM.categoryBag) then
begin
for J := 0 to TM.categoryBag.Len-1 do
begin
if (TM.categoryBag[J].tModelKey = 'uuid:C1ACF26D-9672-4404-9D70-39B756E62AB4') or
(TM.categoryBag[J].keyValue = 'wsdlSpec') then
Result := TM;
end;
end;
end;
end;
end;
end;
function GetTModelOfWSDL(const Service: InquireSoap; const tModKey: String): TModel; overload;
var
TMD: TModelDetail;
begin
Result := nil;
TMD := GetTModDetail(Service, tModKey);
try
GetTModelOfWSDL(TMD);
finally
TMD.Free;
end;
end;
function GetUDDIService(const Operator: String): InquireSOAP;
var
HTTPRIO: THTTPRIO;
begin
Result := nil;
HTTPRIO := THTTPRIO.Create(nil);
try
Result := HTTPRIO as InquireSOAP;
HTTPRIO.URL := Operator;
finally
if Result = nil then
HTTPRIO.Free;
end;
end;
function GetBindingkeyDetail(const Operator: String; const key: String): BindingDetail;
var
Service: InquireSOAP;
begin
Service := GetUDDIService(Operator);
Result := GetBindingkeyDetail(Service, key);
end;
function GetBindingkeyDetail(const Service: InquireSoap; const key: String): BindingDetail;
var
GBD: GetBindingDetail;
BK: bindingKey;
begin
GBD := GetBindingDetail.Create;
try
GBD.generic := '1.0';
SetLength(BK, 1);
BK[0] := key;
GBD.bindingKey := BK;
Result := Service.get_bindingDetail(GBD);
finally
GBD.Free;
end;
end;
function GetBindingkeyImportInfo(const Operator: String; const key: String): IImportBindingInfo;
var
Service: InquireSOAP;
begin
Service := GetUDDIService(Operator);
Result := GetBindingkeyImportInfo(Service, Operator, key);
end;
function GetBindingkeyImportInfo(const Service: InquireSOAP;
const Operator: String;
const key: String): IImportBindingInfo;
var
BD: BindingDetail;
begin
Result := nil;
BD := GetBindingkeyDetail(Service, key);
try
if BD.Len > 0 then
begin
Result := GetImportBindingInfo;
if Assigned(BD[0].accessPoint) then
Result.SOAPEndpoint := BD[0].accessPoint.AccessPoint;
Result.UDDIOperator := Operator;
Result.BindingKey := Key;
Result.WSDLLocation := GetWSDL(Service, BD);
end;
finally
BD.Free;
end;
end;
function GetWSDL(const Service: InquireSoap;
const BTemplate: BindingTemplate;
var WSDL: string): Boolean;
var
I: Integer;
TModInstDetails: TModelInstanceDetails;
TModDetail: TModelDetail;
TM: TModel;
begin
Result := System.False;
if Assigned(BTemplate) then
begin
if Assigned(BTemplate.tModelInstanceDetails) then
begin
TModInstDetails := BTemplate.tModelInstanceDetails;
if TModInstDetails.Len > 0 then
begin
for I := 0 to TModInstDetails.Len-1 do
begin
TModDetail := GetTModDetail(Service, TModInstDetails[I].tModelKey);
TM := GetTModelOfWSDL(TModDetail);
if Assigned(TM) then
begin
{ Here we've found a WSDL }
Result := System.True;
WSDL := TM.overviewDoc.overviewURL;
break;
end;
end;
end;
end;
end;
end;
function GetWSDL(const Service: InquireSOAP; const BD: BindingDetail): String;
var
BT: BindingTemplate;
I: Integer;
begin
Result := '';
if BD.Len > 0 then
begin
for I := 0 to BD.Len-1 do
begin
BT := BD[I];
if GetWSDL(Service, BT, Result) then
Exit;
end;
end;
end;
function GetWSDL(const Service: InquireSOAP; const key: String): String;
var
BD: BindingDetail;
begin
BD := GetBindingkeyDetail(Service, key);
try
Result := GetWSDL(Service, BD);
finally
BD.Free;
end;
end;
function GetWSDL(const Operator: String; const key: String): String;
var
Service: InquireSOAP;
begin
Service := GetUDDIService(Operator);
Result := GetWSDL(Service, key);
end;
function GetUDDIResultCache: IUDDIResultCache;
begin
Result := TUDDIResultCache.Create;
end;
{ TUDDIResultCache }
procedure TUDDIResultCache.Clear;
begin
FServiceDetailList.Clear;
FTModelDetailList.Clear;
FreeAndNil(FBusinessList);
FreeAndNil(FBusinessDetail);
end;
constructor TUDDIResultCache.Create;
begin
inherited Create;
FServiceDetailList := TObjectList.Create(System.True);
FTModelDetailList := TObjectList.Create(System.True);
end;
destructor TUDDIResultCache.Destroy;
begin
FreeAndNil(FBusinessList);
FreeAndNil(FBusinessDetail);
FServiceDetailList.Free;
FTModelDetailList.Free;
inherited;
end;
function TUDDIResultCache.FindServiceDetail(serviceKey: String): ServiceDetail;
var
I: Integer;
SD: ServiceDetail;
begin
for I := 0 to FServiceDetailList.Count-1 do
begin
SD := ServiceDetail(FServiceDetailList.Items[I]);
if Assigned(SD) and
(SD.Len > 0) and
(SD[0].serviceKey = serviceKey) then
begin
Result := SD;
Exit;
end;
end;
Result := nil;
end;
function TUDDIResultCache.FindTModelDetail(tModelKey: String): TModelDetail;
var
I, J: Integer;
TMD: TModelDetail;
begin
for I := 0 to FTModelDetailList.Count-1 do
begin
TMD := TModelDetail(FTModelDetailList.Items[I]);
if Assigned(TMD) then
begin
for J := 0 to TMD.Len-1 do
begin
if TMD[J].tModelKey = tModelKey then
begin
Result := TMD;
Exit;
end;
end;
end;
end;
Result := nil;
end;
function TUDDIResultCache.GetBusinessDetail: BusinessDetail;
begin
Result := FBusinessDetail;
end;
function TUDDIResultCache.GetBusinessList: BusinessList;
begin
Result := FBusinessList;
end;
procedure TUDDIResultCache.SetBusinessDetail(const BT: BusinessDetail);
begin
FreeAndNil(FBusinessDetail);
FBusinessDetail := BT;
end;
procedure TUDDIResultCache.SetBusinessList(const BL: BusinessList);
begin
FreeAndNil(FBusinessList);
FBusinessList := BL;
end;
procedure TUDDIResultCache.SetServiceDetail(const serviceKey: String;
const SD: ServiceDetail);
begin
{ NOTE: No need to check if object is already in list since caller
will first do a Find before invoking this method!! }
FServiceDetailList.Add(SD);
end;
procedure TUDDIResultCache.SetTModelDetail(const tModelKey: String;
const TMD: TModelDetail);
begin
{ NOTE: No need to check if object is already in list since caller
will first do a Find before invoking this method!! }
FTModelDetailList.Add(TMD);
end;
type
TImportBindingInfo = class(TInterfacedObject, IImportBindingInfo)
private
FUDDIOperator: WideString;
FWSDLLocation: WideString;
FHostingRedirector: WideString;
FBindingKey: WideString;
FSOAPEndpoint: WideString;
public
function GetUDDIOperator: WideString;
procedure SetUDDIOperator(const AOperator: WideString);
function GetWSDLLocation: WideString;
procedure SetWSDLLocation(const AWSDLLocation: WideString);
function GetHostingRedirector: WideString;
procedure SetHostingRedirector(const AHostRedirector: WideString);
function GetBindingKey: WideString;
procedure SetBindingKey(const ABindingKey: WideString);
function GetSOAPEndpoint: WideString;
procedure SetSOAPEndpoint(const ASOAPEndpoint: WideString);
end;
function GetImportBindingInfo: IImportBindingInfo;
begin
Result := TImportBindingInfo.Create;
end;
{ TImportBindingInfo }
function TImportBindingInfo.GetBindingKey: WideString;
begin
Result := FBindingKey;
end;
function TImportBindingInfo.GetHostingRedirector: WideString;
begin
Result := FHostingRedirector;
end;
function TImportBindingInfo.GetSOAPEndpoint: WideString;
begin
Result := FSOAPEndpoint;
end;
function TImportBindingInfo.GetUDDIOperator: WideString;
begin
Result := FUDDIOperator;
end;
function TImportBindingInfo.GetWSDLLocation: WideString;
begin
Result := FWSDLLocation;
end;
procedure TImportBindingInfo.SetBindingKey(const ABindingKey: WideString);
begin
FBindingKey := ABindingKey;
end;
procedure TImportBindingInfo.SetHostingRedirector(
const AHostRedirector: WideString);
begin
FHostingRedirector := AHostRedirector;
end;
procedure TImportBindingInfo.SetSOAPEndpoint(
const ASOAPEndpoint: WideString);
begin
FSOAPEndpoint := ASOAPEndpoint;
end;
procedure TImportBindingInfo.SetUDDIOperator(const AOperator: WideString);
begin
FUDDIOperator := AOperator;
end;
procedure TImportBindingInfo.SetWSDLLocation(
const AWSDLLocation: WideString);
begin
FWSDLLocation := AWSDLLocation;
end;
end.
|
program GenericFunc(input,output);
type
gftype = array [0..15] of integer;
var
a, b, c, d:integer;
fresult:integer;
func: gftype;
(* Standard Pascal does not provide the ability to shift integer data *)
(* to the left or right. Therefore, we will simulate a 16-bit value *)
(* using an array of 16 integers. We can simulate shifts by moving *)
(* data around in the array. *)
(* *)
(* Note that Turbo Pascal *does* provide shl and shr operators. How- *)
(* ever, this code is written to work with standard Pascal, not just *)
(* Turbo Pascal. *)
procedure ShiftLeft(shiftin:integer);
var i:integer;
begin
for i := 15 downto 1 do func[i] := func[i-1];
func[0] := shiftin;
end;
procedure ShiftNibble(d,c,b,a:integer);
begin
ShiftLeft(d);
ShiftLeft(c);
ShiftLeft(b);
ShiftLeft(a);
end;
procedure ShiftRight;
var i:integer;
begin
for i := 0 to 14 do func[i] := func[i+1];
func[15] := 0;
end;
procedure toupper(var ch:char);
begin
if (ch in ['a'..'z']) then ch := chr(ord(ch) - 32);
end;
function ReadFunc:integer;
var ch:char;
i, val:integer;
begin
write('Enter function number (hexadecimal): ');
for i := 0 to 15 do func[i] := 0;
repeat
read(ch);
if not eoln then begin
toupper(ch);
case ch of
'0': ShiftNibble(0,0,0,0);
'1': ShiftNibble(0,0,0,1);
'2': ShiftNibble(0,0,1,0);
'3': ShiftNibble(0,0,1,1);
'4': ShiftNibble(0,1,0,0);
'5': ShiftNibble(0,1,0,1);
'6': ShiftNibble(0,1,1,0);
'7': ShiftNibble(0,1,1,1);
'8': ShiftNibble(1,0,0,0);
'9': ShiftNibble(1,0,0,1);
'A': ShiftNibble(1,0,1,0);
'B': ShiftNibble(1,0,1,1);
'C': ShiftNibble(1,1,0,0);
'D': ShiftNibble(1,1,0,1);
'E': ShiftNibble(1,1,1,0);
'F': ShiftNibble(1,1,1,1);
else write(chr(7),chr(8));
end;
end;
until eoln;
val := 0;
for i := 0 to 15 do val := val + func[i];
ReadFunc := val;
end;
(* Generic - Computes the generic logical function specified by *)
(* the function number "func" on the four input vars *)
(* a, b, c, and d. It does this by returning bit *)
(* d*8 + c*4 + b*2 + a from func. This version re- *)
(* lies on Turbo Pascal's shift right operator. *)
function Generic(var func:gftype; a,b,c,d:integer):integer;
begin
Generic := func[a + b*2 + c*4 + d*8];
end;
begin (* main *)
repeat
fresult := ReadFunc;
if (fresult <> 0) then begin
write('Enter values for D, C, B, & A (0/1):');
readln(d, c, b, a);
writeln('The result is ',Generic(func,a,b,c,d));
end;
until fresult = 0;
end. |
unit uStrategy;
interface
uses
Classes, SysUtils, StrUtils, Math,
pFIBQuery, superobject, uGameItems, uDefs, uServerConnect, uDB,
uLogger;
type
TStrategy = class
private
FID,
FGroupID,
FPriority: integer;
FActive: boolean;
FImperium: TImperium;
FServer: TMoonServerConnect;
FDB: TMoonDB;
FExecOnce: boolean;
FLastExecute,
FNextExecute: TDateTime;
FromHour,
ToHour,
FInterval,
FIntDeviation,
FFromPlanetID: integer;
procedure PlaninigNextExecution;
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); virtual;
procedure Clear; virtual;
function LoadConfig(cfg: string): ISuperObject; virtual;
function Execute: boolean;
function IntExecute: boolean; virtual;
property Active: boolean read FActive write FActive;
property Priority: integer read FPriority write FPriority;
property ID: integer read FID write FID;
property GroupID: integer read FGroupID;
end;
TStInit = class(TStrategy)
private
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); override;
function LoadConfig(cfg: string): ISuperObject; override;
procedure Clear; override;
function IntExecute: boolean; override;
end;
TStExpedition = class(TStrategy)
protected
FWaitAllShipsAvail: boolean;
FDelMsgEvery,
FDelMsgCount: integer;
FFleet: TFleetOrderArr;
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); override;
function LoadConfig(cfg: string): ISuperObject; override;
procedure Clear; override;
function IntExecute: boolean; override;
end;
TStImperiumUpdate = class(TStrategy)
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); override;
function LoadConfig(cfg: string): ISuperObject; override;
procedure Clear; override;
function IntExecute: boolean; override;
end;
TStMapUpdate = class(TStrategy)
private
FOnePass: integer;
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); override;
function LoadConfig(cfg: string): ISuperObject; override;
procedure Clear; override;
function IntExecute: boolean; override;
end;
TStFleetBuild = class(TStrategy)
private
FWaitForRes,
FLockRes: boolean;
FFleet: TFleetOrderArr;
function intBuild(PlanetID: integer): boolean;
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); override;
function LoadConfig(cfg: string): ISuperObject; override;
procedure Clear; override;
function IntExecute: boolean; override;
end;
TStColonize = class(TStrategy)
private
FDelMsgEvery,
FDelMsgCount: integer;
FWaitAllShipsAvail: boolean;
FFromGalaxy,
FToGalaxy,
FFromSystem,
FToSystem,
FFromPlanet,
FToPlanet,
FWorkPlanetCount,
FMaxPlanetFields: integer;
FFleet: TFleetOrderArr;
FCurrCoords: TGameCoords;
function CalcNextCoords: boolean;
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); override;
function LoadConfig(cfg: string): ISuperObject; override;
procedure Clear; override;
function IntExecute: boolean; override;
end;
TStPlanetBuild = class(TStrategy)
private
FPlaningLock: integer;
FLockRes: boolean;
FBuildType: integer;
function IntBuildPlanet(PlanetID: integer): boolean;
procedure CalcBuild(pl: TPlanet; btree: TGameItems; var indx: Integer);
procedure CalcBuildPlan(pl: TPlanet; btree: TGameItems; var indx: Integer);
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); override;
function LoadConfig(cfg: string): ISuperObject; override;
procedure Clear; override;
function IntExecute: boolean; override;
end;
TStResearch = class(TStrategy)
private
FPlaningLock: integer;
FLockRes: boolean;
FMaxLength: integer;
procedure CalcResearch(rtree: TGameItems; pl: TPlanet; var indx: Integer);
procedure CalcResearchPlan(rtree: TGameItems; pl: TPlanet; var indx: Integer);
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); override;
function LoadConfig(cfg: string): ISuperObject; override;
procedure Clear; override;
function IntExecute: boolean; override;
end;
TStFleetMove = class(TStrategy)
private
FWaitAllShipsAvail: boolean;
FFleetOrder: TFleetOrder;
FCoords: TGameCoords;
FSpeed: integer;
FTimeThere: extended;
FFleet: TFleetOrderArr;
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); override;
function LoadConfig(cfg: string): ISuperObject; override;
procedure Clear; override;
function IntExecute: boolean; override;
end;
TStSatelitesBuild = class(TStrategy)
private
FLockRes: boolean;
FIncCount: integer;
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); override;
function LoadConfig(cfg: string): ISuperObject; override;
procedure Clear; override;
function IntExecute: boolean; override;
end;
TStMineDarkMatery = class(TStrategy)
private
FMinersCount,
FExpeditionsCount: integer;
FMaxDarkMatery: int64;
public
constructor Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB); override;
function LoadConfig(cfg: string): ISuperObject; override;
procedure Clear; override;
function IntExecute: boolean; override;
end;
TStrategyExecutor = class
private
FImperium: TImperium;
FServer: TMoonServerConnect;
FStrat: array of TStrategy;
function GetStrategy(ID: integer): TStrategy;
function GetStrategyI(ID: integer): integer;
public
constructor Create(imp: TImperium; srv: TMoonServerConnect);
procedure ApplyMacroStrategy(MacroStID: integer);
procedure AddStrategy(ID, TypeID: integer; Params: string);
procedure ActivateStrategy(ID: integer);
procedure DeactivateStrategy(ID: integer);
procedure DelStrategy(ID: integer);
procedure UpdateStrategy(ID: integer; Params: string);
procedure Execute;
end;
implementation
{ TStrategy }
procedure TStrategy.Clear;
begin
FPriority := -1;
FActive := false;
FImperium := nil;
FExecOnce := false;
FLastExecute := 0;
FNextExecute := 0;
FromHour := 0;
ToHour := 0;
FInterval := 0;
FIntDeviation := 0;
FFromPlanetID := 0;
end;
constructor TStrategy.Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB);
begin
inherited Create;
FGroupID := 0; // тип стратегии
Clear;
FImperium := imp;
FServer := srv;
FDB := db;
end;
function TStrategy.Execute: boolean;
begin
Result := true; // execute next strategy after this
if not FActive then exit;
if (FLastExecute <> 0) and FExecOnce then exit;
if (FNextExecute <> 0) and (Now < FNextExecute) then exit;
if (FromHour <> 0) and
(not TimeBetween(Now, FromHour, ToHour)) then exit;
IntExecute;
PlaninigNextExecution;
end;
function TStrategy.IntExecute: boolean;
begin
Result := true;
end;
function TStrategy.LoadConfig(cfg: string): ISuperObject;
var
obj: ISuperObject;
begin
Result := nil;
FActive := false;
FPriority := -1;
try
obj := TSuperObject.ParseString(PWideChar(cfg), false);
if obj = nil then exit;
Result := obj;
FExecOnce := SOAsBooleanDef(obj, 'ExecOnce', false);
FromHour := SOAsIntegerDef(obj, 'ExecFromHour', 0);
ToHour := SOAsIntegerDef(obj, 'ExecToHour', 0);
FInterval := SOAsIntegerDef(obj, 'Interval', 0);
FIntDeviation := SOAsIntegerDef(obj, 'IntDeviation', 0);
FFromPlanetID := SOAsIntegerDef(obj, 'FromPlanetID', 0);
except
end;
end;
procedure TStrategy.PlaninigNextExecution;
var
sec: integer;
begin
try
FLastExecute := Now;
sec := FInterval + (FIntDeviation - Random(FIntDeviation * 2));
if sec < 4 then sec := 60;
FNextExecute := FLastExecute + 1 / (24 * 60 * 60) * sec;
except
end;
end;
{ TStrategyExecutor }
procedure TStrategyExecutor.ActivateStrategy(ID: integer);
var
strg: TStrategy;
begin
strg := GetStrategy(ID);
if strg = nil then exit;
strg.Active := true;
end;
procedure TStrategyExecutor.AddStrategy(ID, TypeID: integer; Params: string);
var
strg: TStrategy;
begin
strg := nil;
case TypeID of
1: strg := TStExpedition.Create(FImperium, FServer, TMoonDB.GetInstance);
2: strg := TStImperiumUpdate.Create(FImperium, FServer, TMoonDB.GetInstance);
3: strg := TStMapUpdate.Create(FImperium, FServer, TMoonDB.GetInstance);
4: strg := TStFleetBuild.Create(FImperium, FServer, TMoonDB.GetInstance);
5: strg := TStColonize.Create(FImperium, FServer, TMoonDB.GetInstance);
6: strg := TStPlanetBuild.Create(FImperium, FServer, TMoonDB.GetInstance);
7: strg := TStResearch.Create(FImperium, FServer, TMoonDB.GetInstance);
8: strg := TStFleetMove.Create(FImperium, FServer, TMoonDB.GetInstance);
9: strg := TStSatelitesBuild.Create(FImperium, FServer, TMoonDB.GetInstance);
10: strg := TStMineDarkMatery.Create(FImperium, FServer, TMoonDB.GetInstance);
100: strg := TStInit.Create(FImperium, FServer, TMoonDB.GetInstance);
end;
if strg = nil then exit;
strg.ID := ID;
strg.LoadConfig(Params);
SetLength(FStrat, length(FStrat) + 1);
FStrat[length(FStrat) - 1] := strg;
end;
procedure TStrategyExecutor.ApplyMacroStrategy(MacroStID: integer);
var
i: Integer;
begin
if MacroStID = -1 then
for i := 0 to length(FStrat) -1 do
FStrat[i].Priority := i;
end;
constructor TStrategyExecutor.Create(imp: TImperium; srv: TMoonServerConnect);
begin
inherited Create;
SetLength(FStrat, 0);
FImperium := imp;
FServer := srv;
end;
procedure TStrategyExecutor.DeactivateStrategy(ID: integer);
var
strg: TStrategy;
begin
strg := GetStrategy(ID);
if strg = nil then exit;
strg.Active := false;
end;
procedure TStrategyExecutor.DelStrategy(ID: integer);
begin
end;
procedure TStrategyExecutor.Execute;
var
i: integer;
Prio: integer;
nPrio,
nIndx: integer;
begin
Prio := -1; // start strategy priority
while True do
try
nPrio := -1;
nIndx := -1;
for i := 0 to length(FStrat) - 1 do
if (FStrat[i].FPriority > Prio) and
((nPrio < 0) or (FStrat[i].FPriority < nPrio))
then
begin
nPrio := FStrat[i].FPriority;
nIndx := i;
end;
if nIndx < 0 then break;
Prio := nPrio;
if not FStrat[nIndx].Execute then exit;
except
end;
end;
function TStrategyExecutor.GetStrategy(ID: integer): TStrategy;
var
indx: integer;
begin
Result := nil;
indx := GetStrategyI(ID);
if indx < 0 then exit;
Result := FStrat[indx];
end;
function TStrategyExecutor.GetStrategyI(ID: integer): integer;
var
i: integer;
begin
Result := -1;
for i := 0 to length(FStrat) - 1 do
if FStrat[i].ID = ID then
begin
Result := i;
break;
end;
end;
procedure TStrategyExecutor.UpdateStrategy(ID: integer; Params: string);
var
strg: TStrategy;
begin
strg := GetStrategy(ID);
if strg = nil then exit;
strg.LoadConfig(Params);
end;
{ TStExpedition }
procedure TStExpedition.Clear;
begin
inherited;
FWaitAllShipsAvail := true;
FDelMsgEvery := 0;
FDelMsgCount := 0;
end;
constructor TStExpedition.Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB);
begin
inherited;
FGroupID := 1; // expedition
end;
function TStExpedition.IntExecute: boolean;
var
c: TGameCoords;
pl: TPlanet;
i: integer;
ships: TFleetOrderArr;
begin
Result := true;
pl := FImperium.GetPlanet(FFromPlanetID);
if pl = nil then exit;
if FWaitAllShipsAvail then
begin
for i := 0 to length(FFleet) - 1 do
if FFleet[i].Value > pl.GetShipsCount(FFleet[i].Name, true, false)
then exit;
end;
c.Clear;
c.FromStr('1:1:16');
c.PlType := ptPlanet;
c.Galaxy := Random(8) + 1;
c.System := Random(499) + 1;
ships := Copy(FFleet, 0, length(FFleet));
FServer.FleetMove(FImperium, FFromPlanetID, c, ships, foExpedition, 10, 1);
if FDelMsgEvery > 0 then
begin
if FDelMsgCount > FDelMsgEvery then
begin
FServer.DeleteMessages(integer(foExpedition));
FDelMsgCount := 0;
end;
FDelMsgCount := FDelMsgCount + 1;
end;
end;
function TStExpedition.LoadConfig(cfg: string): ISuperObject;
begin
Result := inherited LoadConfig(cfg);
FWaitAllShipsAvail := SOAsBooleanDef(Result, 'WaitAllShipsAvail', true);
FDelMsgEvery := SOAsIntegerDef(Result, 'DelMsgEvery', 0);
FFleet := SOAsShips(Result, 'ships');
end;
{ TStImperiumUpdate }
procedure TStImperiumUpdate.Clear;
begin
inherited;
end;
constructor TStImperiumUpdate.Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB);
begin
inherited;
FGroupID := 2; // Imperium Update
end;
function TStImperiumUpdate.IntExecute: boolean;
begin
Result := true;
// не чаще раза в минуту
if FImperium.LastUpdate < (Now - 1/(24*60)) then
Result := FServer.UpdateImperium(FImperium);
end;
function TStImperiumUpdate.LoadConfig(cfg: string): ISuperObject;
begin
Result := inherited LoadConfig(cfg);
end;
{ TStMapUpdate }
procedure TStMapUpdate.Clear;
begin
inherited;
FOnePass := 1;
end;
constructor TStMapUpdate.Create(imp: TImperium; srv: TMoonServerConnect; db: TMoonDB);
begin
inherited;
FGroupID := 3; // Map Update
end;
function TStMapUpdate.IntExecute: boolean;
var
pls: TPlanetSystem;
usr: TUserList;
qry: TpFIBQuery;
res: boolean;
cnt: integer;
begin
Result := true;
qry := FDB.GetSystemToScan(FOnePass);
if qry = nil then exit;
try
cnt := 0;
while not qry.Eof do
begin
res := FServer.UpdateGalaxyPlanets(
qry.FieldByName('GALAXY').AsInteger,
qry.FieldByName('SYSTEM').AsInteger,
gmvNone,
pls,
usr);
if res then
begin
if length(usr) > 0 then
FServer.UpdateUsersInfo(usr);
FDB.UpdateUsers(usr);
FDB.UpdatePlanetSystem(pls);
cnt := cnt + 1;
end;
qry.Next;
end;
qry.Close;
FDB.Commit;
Result := false;
AddLog('update galaxy. systems=' + IntToStr(cnt));
except
end;
end;
function TStMapUpdate.LoadConfig(cfg: string): ISuperObject;
begin
Result := inherited LoadConfig(cfg);
FOnePass := SOAsIntegerDef(Result, 'OnePassSystemsCount', 1);
end;
{ TStShipBuild }
procedure TStFleetBuild.Clear;
begin
inherited;
FWaitForRes := true;
FLockRes := false;
SetLength(FFleet, 0);
end;
constructor TStFleetBuild.Create(imp: TImperium; srv: TMoonServerConnect;
db: TMoonDB);
begin
inherited;
FGroupID := 4; // Ship build
end;
function TStFleetBuild.IntExecute: boolean;
var
i: integer;
begin
try
if FFromPlanetID <> 0 then
begin
Result := intBuild(FFromPlanetID);
exit;
end;
Result := true;
for i := 0 to FImperium.PlanetsCount - 1 do
Result := Result or intBuild(FImperium.GetPlanetI(i).ID);
except
Result := false;
end;
end;
function TStFleetBuild.intBuild(PlanetID: integer): boolean;
var
res: Boolean;
ships: TFleetOrderArr;
begin
Result := true;
res := FImperium.PlanetHaveResources(
FFromPlanetID,
TCalc.ShipsBuildCost(FFleet));
// we dont have needed resources
if (not res) and (FWaitForRes) then exit;
ships := Copy(FFleet, 0, length(FFleet));
Result :=
FServer.BuildFleet(FImperium, PlanetID, ships, FWaitForRes, true);
end;
function TStFleetBuild.LoadConfig(cfg: string): ISuperObject;
begin
Result := inherited LoadConfig(cfg);
FWaitForRes := SOAsBooleanDef(Result, 'WaitForRes', true);
FLockRes := SOAsBooleanDef(Result, 'LockRes', false);
FFleet := SOAsShips(Result, 'ships');
end;
{ TStColonize }
function TStColonize.CalcNextCoords: boolean;
var
i: Integer;
pls: TPlanetSystem;
usr: TUserList;
LastCoords: TGameCoords;
firststep: boolean;
begin
Result := false;
i := 0;
LastCoords := FCurrCoords;
LastCoords.Inc(FFromGalaxy, FToGalaxy, FFromSystem, FToSystem,
FFromPlanet, FToPlanet, 1);
firststep := true;
while true do
begin
FCurrCoords.Inc(FFromGalaxy, FToGalaxy, FFromSystem, FToSystem,
FFromPlanet, FToPlanet, 1);
if LastCoords.Equal(FCurrCoords) and not firststep then break;
if FImperium.GetPlanetC(FCurrCoords) <> nil then continue;
firststep := false;
// если тут была планета то скорее всего она там и есть....
if not FDB.GetPlanet(FCurrCoords).isEmpty then continue;
// проверка на то, что планета не появилась
FServer.UpdateGalaxyPlanets(
FCurrCoords.Galaxy,
FCurrCoords.System,
gmvNone, pls, usr);
FDB.UpdatePlanetSystem(pls);
FDB.Commit;
i := i + 1;
if i > 100 then break;
if FDB.GetPlanet(FCurrCoords).isEmpty then
begin
Result := true;
exit;
end;
end;
end;
procedure TStColonize.Clear;
begin
inherited;
FDelMsgEvery := 10;
FDelMsgCount := 0;
FWaitAllShipsAvail := false;
FFromGalaxy := 0;
FToGalaxy := 0;
FFromSystem := 0;
FToSystem := 0;
FFromPlanet := 0;
FToPlanet := 0;
FWorkPlanetCount := 0;
FMaxPlanetFields := 300;
SetLength(FFleet, 0);
FCurrCoords.Clear;
FCurrCoords.PlType := ptPlanet;
end;
constructor TStColonize.Create(imp: TImperium; srv: TMoonServerConnect;
db: TMoonDB);
begin
inherited;
FGroupID := 5; // Colonize
end;
function TStColonize.IntExecute: boolean;
var
MaxPlanetsCount: integer;
ExpCnt: integer;
i: Integer;
pl: TPlanet;
epl: TEnemyPlanet;
MinFields,
MinIndx: integer;
ships: TFleetOrderArr;
begin
Result := true;
pl := FImperium.GetPlanet(FFromPlanetID);
if pl = nil then exit;
if FWaitAllShipsAvail then
begin
for i := 0 to length(FFleet) - 1 do
if FFleet[i].Value > pl.GetShipsCount(FFleet[i].Name, true, false)
then exit;
end;
MaxPlanetsCount := FImperium.MaxPlanetsCount;
// delete planets
ExpCnt := FWorkPlanetCount - (MaxPlanetsCount - FImperium.PlanetsCount(false));
if ExpCnt < 0 then ExpCnt := 0;
if ExpCnt > FWorkPlanetCount then ExpCnt := FWorkPlanetCount;
while ExpCnt > 0 do
begin
MinIndx := -1;
MinFields := 1000;
for i := 0 to FImperium.PlanetsCount - 1 do
begin
pl := FImperium.GetPlanetI(i);
if (pl = nil) or (pl.Name <> 'Планета') or
(pl.MaxFields >= FMaxPlanetFields) or
(pl.isMoon) then continue;
if pl.MaxFields < MinFields then
begin
MinIndx := i;
MinFields := pl.MaxFields;
end;
end;
if MinIndx >= 0 then
begin
pl := FImperium.GetPlanetI(MinIndx);
if pl <> nil then
begin
if FServer.DeletePlanet(pl.ID) then
begin
epl.Clear;
epl.Coords := pl.Coords;
epl.Name := 'deleted my planet';
FDB.AddPlanet(epl);
end;
pl.Name := 'deleted';
ExpCnt := ExpCnt - 1;
sleep(1000);
end;
end
else
break;
end;
sleep(1000);
FServer.UpdateImperium(FImperium);
sleep(1000);
// normalize expedition count
if FImperium.PlanetsCount(false) >= MaxPlanetsCount then exit;
ExpCnt := MaxPlanetsCount - FImperium.PlanetsCount(false);
if ExpCnt > FWorkPlanetCount then ExpCnt := FWorkPlanetCount;
// launch expedition
if FCurrCoords.Galaxy = 0 then
begin
FCurrCoords.Galaxy := FFromGalaxy;
FCurrCoords.System := FFromSystem;
FCurrCoords.Planet := FFromPlanet - 1;
end;
for i := 1 to ExpCnt do
begin
if not CalcNextCoords then break;
ships := Copy(FFleet, 0, length(FFleet));
FServer.FleetMove(FImperium, FFromPlanetID, FCurrCoords, ships, foColonize, 10, 1);
sleep(2000);
end;
if FDelMsgEvery > 0 then
begin
if FDelMsgCount > FDelMsgEvery then
begin
FServer.DeleteMessages(4);
FDelMsgCount := 0;
end;
FDelMsgCount := FDelMsgCount + 1;
end;
end;
function TStColonize.LoadConfig(cfg: string): ISuperObject;
begin
Result := inherited LoadConfig(cfg);
FDelMsgEvery := SOAsIntegerDef(Result, 'DelMsgEvery', 0);
FWaitAllShipsAvail := SOAsBooleanDef(Result, 'WaitAllShipsAvail', true);
FFromGalaxy := SOAsIntegerDef(Result, 'FromGalaxy', 0);
FToGalaxy := SOAsIntegerDef(Result, 'ToGalaxy', 0);
FFromSystem := SOAsIntegerDef(Result, 'FromSystem', 0);
FToSystem := SOAsIntegerDef(Result, 'ToSystem', 0);
FFromPlanet := SOAsIntegerDef(Result, 'FromPlanet', 0);
FToPlanet := SOAsIntegerDef(Result, 'ToPlanet', 0);
FWorkPlanetCount := SOAsIntegerDef(Result, 'WorkPlanetCount', 0);
FMaxPlanetFields := SOAsIntegerDef(Result, 'MaxPlanetFields', 300);
FFleet := SOAsShips(Result, 'ships');
end;
{ TStSatelitesBuild }
procedure TStSatelitesBuild.Clear;
begin
inherited;
FLockRes := false;
FIncCount := 0;
end;
constructor TStSatelitesBuild.Create(imp: TImperium; srv: TMoonServerConnect;
db: TMoonDB);
begin
inherited;
FGroupID := 9;
end;
function TStSatelitesBuild.IntExecute: boolean;
var
res: boolean;
Fleet: TFleetOrderArr;
bg,
en: integer;
pl: TPlanet;
i: Integer;
begin
Result := true;
if FIncCount <= 0 then exit;
try
if FFromPlanetID <> 0 then
begin
bg := FImperium.GetPlanetIndx(FFromPlanetID);
en := bg;
if bg < 0 then exit;
end
else
begin
bg := 0;
en := FImperium.PlanetsCount - 1;
end;
Result := true;
for i := bg to en do
begin
SetLength(Fleet, 1);
Fleet[0].Name := 'Солнечный спутник';
Fleet[0].Value := FIncCount;
pl := FImperium.GetPlanetI(i);
if (pl = nil) or (pl.FreeEnergy >= 0) or (pl.ShipsBuilding)
then continue;
res := FImperium.PlanetHaveResources(
pl.ID,
TCalc.ShipsBuildCost(Fleet));
// we dont have needed resources
if (not res) then continue;
Fleet[0].Value :=
( (pl.GetShipsCount(Fleet[0].Name, true, true) +
Fleet[0].Value)
div Fleet[0].Value) * Fleet[0].Value;
res := FServer.BuildFleet(
FImperium, pl.ID, Fleet, false, true);
Result := Result and res;
end;
except
Result := false;
end;
end;
function TStSatelitesBuild.LoadConfig(cfg: string): ISuperObject;
begin
Result := inherited LoadConfig(cfg);
FLockRes := SOAsBooleanDef(Result, 'LockRes', false);
FIncCount := SOAsIntegerDef(Result, 'IncCount', 0);
end;
{ TStMineDarkMatery }
procedure TStMineDarkMatery.Clear;
begin
inherited;
FMinersCount := 1;
FExpeditionsCount := 1;
FMaxDarkMatery := 0;
end;
constructor TStMineDarkMatery.Create(imp: TImperium; srv: TMoonServerConnect;
db: TMoonDB);
begin
inherited;
FGroupID := 10;
end;
function TStMineDarkMatery.IntExecute: boolean;
var
res: boolean;
Fleet: TFleetOrderArr;
bg,
en: integer;
pl: TPlanet;
cnt,
i: Integer;
coords: TGameCoords;
begin
Result := true;
if (FMaxDarkMatery <> 0) and
(FImperium.DarkMatery > FMaxDarkMatery) then exit;
try
if FFromPlanetID <> 0 then
begin
bg := FImperium.GetPlanetIndx(FFromPlanetID);
en := bg;
if bg < 0 then exit;
end
else
begin
bg := 0;
en := FImperium.PlanetsCount - 1;
end;
SetLength(Fleet, 1);
Fleet[0].Name := 'Сборщик Тёмной материи';
Fleet[0].Value := FMinersCount;
Result := true;
cnt := 0;
for i := bg to en do
begin
pl := FImperium.GetPlanetI(i);
if (pl = nil) or
(pl.isMoon) or
(FImperium.GetPlanetC(pl.Coords, true) = nil) or
(pl.GetShipsCount(Fleet[0].Name, true, false) < Fleet[0].Value)
then continue;
coords := pl.Coords;
coords.PlType := ptMoon;
res := FServer.FleetMove(
FImperium, pl.ID, coords, Fleet, foDarkMateryMine, 10, 100);
Result := Result and res;
// only one expedition to the moon (2 moons v.1.4) allowed at 1 time
cnt := cnt + 1;
if cnt >= FExpeditionsCount then break;
end;
except
Result := false;
end;
end;
function TStMineDarkMatery.LoadConfig(cfg: string): ISuperObject;
begin
Result := inherited LoadConfig(cfg);
FMinersCount := SOAsIntegerDef(Result, 'MinersCount', 1);
FExpeditionsCount := SOAsIntegerDef(Result, 'ExpeditionsCount', 10);
FMaxDarkMatery := SOAsIntegerDef(Result, 'MaxDarkMatery', 0);
end;
{ TStFleetMove }
procedure TStFleetMove.Clear;
begin
inherited;
FWaitAllShipsAvail := true;
FFleetOrder := foNone;
FCoords.Clear;
FSpeed := 10;
FTimeThere := 1;
SetLength(FFleet, 0);
end;
constructor TStFleetMove.Create(imp: TImperium; srv: TMoonServerConnect;
db: TMoonDB);
begin
inherited;
FGroupID := 8;
end;
function TStFleetMove.IntExecute: boolean;
var
pl: TPlanet;
cnt,
i: integer;
begin
Result := true;
pl := FImperium.GetPlanet(FFromPlanetID);
if pl = nil then exit;
if FWaitAllShipsAvail then
begin
for i := 0 to length(FFleet) - 1 do
if FFleet[i].Value > pl.GetShipsCount(FFleet[i].Name, true, false)
then exit;
end;
// normalize count
for i := 0 to length(FFleet) - 1 do
begin
cnt := pl.GetShipsCount(FFleet[i].Name, true, false);
if FFleet[i].Value > cnt then
FFleet[i].Value := cnt;
end;
FServer.FleetMove(FImperium, FFromPlanetID, FCoords, FFleet, FFleetOrder, FSpeed, FTimeThere);
end;
function TStFleetMove.LoadConfig(cfg: string): ISuperObject;
begin
Result := inherited LoadConfig(cfg);
FWaitAllShipsAvail := SOAsBooleanDef(Result, 'WaitAllShipsAvail', true);
FFleetOrder := TFleetOrder(SOAsIntegerDef(Result, 'FleetOrder', 0));
FCoords.FromStr(SOAsString(Result, 'coords'));
FSpeed := SOAsIntegerDef(Result, 'Speed', 10);
FTimeThere := SOAsIntegerDef(Result, 'TimeThere', 1);
FFleet := SOAsShips(Result, 'ships');
end;
{ TStPlanetBuild }
procedure TStPlanetBuild.CalcBuildPlan(pl: TPlanet; btree: TGameItems;
var indx: Integer);
var
i: Integer;
bres,
res: TGameRes;
MinResSumm: Int64;
level: Integer;
begin
if pl = nil then exit;
indx := -1;
MinResSumm := -1;
for i := 0 to length(btree) - 1 do
begin
if btree[i].GroupName <> 'Постройки' then continue;
level := pl.GetBuildLevel(btree[i].Name);
res := FDB.GetBuildingRes(btree[i].Name, level);
if res.Eq0 then continue;
bres := pl.CurRes;
res.Sub(bres);
res.NormalizeLow(0);
if (btree[i].Level > level) and
(FImperium.PlanetCanBuild(pl.ID, btree[i].Name)) and
((MinResSumm < 0) or (MinResSumm > res.ResSumm)) then
begin
MinResSumm := res.ResSumm;
indx := i;
end;
end;
end;
procedure TStPlanetBuild.Clear;
begin
inherited;
FLockRes := false;
FBuildType := -1;
FPlaningLock := 60 * 30;
end;
constructor TStPlanetBuild.Create(imp: TImperium; srv: TMoonServerConnect;
db: TMoonDB);
begin
inherited;
end;
function TStPlanetBuild.IntBuildPlanet(PlanetID: integer): boolean;
var
ABuildType: integer;
pl: TPlanet;
btree: TGameItems;
indx: Integer;
begin
Result := false;
try
ABuildType := FBuildType;
pl := FImperium.GetPlanet(PlanetID);
if pl = nil then exit;
if pl.BuildsBuilding then exit;
if pl.FreeFieldsCount <=0 then exit;
if ABuildType < 0 then
begin
ABuildType := FDB.GetPlanetBuildType(PlanetID);
if ABuildType < 0 then exit;
end;
btree := FDB.GetPlanetBuildTree(ABuildType);
CalcBuild(pl, btree, indx);
if indx >= 0 then
begin
Result := FServer.BuildBuilding(FImperium, PlanetID,
btree[indx].Name, btree[indx].Level, false);
exit;
end;
// планирование
CalcBuildPlan(pl, btree, indx);
if indx >= 0 then
begin
pl.BuildingPlan.Clear;
pl.BuildingPlan.Item := btree[indx];
//!!!!!!!!!!!!!!!!!
pl.BuildingPlan.NeedRes := btree[indx].BuildRes;
pl.BuildingPlan.EndPlaningDate :=
Now + 1 / SecsPerDay * FPlaningLock;
end;
except
end;
end;
function TStPlanetBuild.IntExecute: boolean;
var
i: Integer;
begin
Result := true;
// build one planet
if FFromPlanetID <> 0 then
begin
IntBuildPlanet(FFromPlanetID);
exit;
end;
// build all planets
for i := 0 to FImperium.PlanetsCount - 1 do
begin
IntBuildPlanet(FImperium.GetPlanetI(i).ID);
end;
FServer.UpdateImperium(FImperium);
end;
procedure TStPlanetBuild.CalcBuild(pl: TPlanet; btree: TGameItems;
var indx: Integer);
var
i: Integer;
res: TGameRes;
MinResSumm: Int64;
level: Integer;
begin
if pl = nil then exit;
indx := -1;
MinResSumm := -1;
for i := 0 to length(btree) - 1 do
begin
level := pl.GetBuildLevel(btree[i].Name);
res := FDB.GetBuildingRes(btree[i].Name, level);
if (btree[i].GroupName = 'Постройки') and
(btree[i].Level > level) and
(not res.Eq0) and
(pl.HaveResources(res)) and
(FImperium.PlanetCanBuild(pl.ID, btree[i].Name)) and
((MinResSumm < 0) or (MinResSumm > res.EkvResSumm)) then
begin
MinResSumm := res.EkvResSumm;
indx := i;
end;
end;
end;
function TStPlanetBuild.LoadConfig(cfg: string): ISuperObject;
begin
Result := inherited LoadConfig(cfg);
FLockRes := SOAsBooleanDef(Result, 'LockRes', false);
FBuildType := SOAsIntegerDef(Result, 'BuildType', -1);
end;
{ TStInit }
procedure TStInit.Clear;
begin
inherited;
end;
constructor TStInit.Create(imp: TImperium; srv: TMoonServerConnect;
db: TMoonDB);
begin
inherited;
FGroupID := 100;
end;
function TStInit.IntExecute: boolean;
var
techdeps,
tech: TGameItems;
i: integer;
begin
Result := true;
try
// update my_planets into DB
FServer.UpdateImperium(FImperium);
FDB.UpdateMyPlanets(FImperium);
FDB.Commit;
// update technoogy tree
if FServer.UpdateTechnologies(FImperium, tech, techdeps) then
begin
FDB.UpdateTechnologies(tech);
FDB.ClearTechDeps;
FDB.UpdateTechDeps(techdeps);
FDB.Commit;
end;
// update buildings build params
for i := 0 to FImperium.PlanetsCount - 1 do
begin
FServer.UpdateBuildings(FImperium, FImperium.GetPlanetI(i).ID);
end;
// update researching...
FServer.UpdateResearching(FImperium);
except
end;
end;
function TStInit.LoadConfig(cfg: string): ISuperObject;
begin
Result := inherited LoadConfig(cfg);
end;
{ TStResearch }
procedure TStResearch.CalcResearchPlan(rtree: TGameItems; pl: TPlanet;
var indx: Integer);
var
bres,
res: TGameRes;
MinResSumm: Int64;
i: Integer;
level: Integer;
rlen: Integer;
begin
indx := -1;
MinResSumm := -1;
for i := 0 to length(rtree) - 1 do
begin
if rtree[i].GroupName <> 'Исследования' then continue;
level := FImperium.GetResearchLevel(rtree[i].Name);
bres := FDB.GetBuildingRes(rtree[i].Name, level);
if bres.Eq0 then continue;
res := pl.CurRes;
res.Sub(bres);
res.NormalizeLow(0);
rlen := Trunc(FDB.GetBuildingLength(rtree[i].Name, level) * 24 * 60 * 60);
if (rtree[i].Level > level) and
((FMaxLength = 0) or (rlen < FMaxLength)) and
((MinResSumm < 0) or (MinResSumm > res.ResSumm)) and
(FImperium.CanResearch(rtree[i].Name)) then
begin
MinResSumm := res.ResSumm;
indx := i;
end;
end;
end;
procedure TStResearch.Clear;
begin
inherited;
FLockRes := false;
FMaxLength := 0;
FPlaningLock := 60 * 30;
end;
constructor TStResearch.Create(imp: TImperium; srv: TMoonServerConnect;
db: TMoonDB);
begin
inherited;
end;
function TStResearch.IntExecute: boolean;
var
pl: TPlanet;
rtree1,
rtree2: TGameItems;
indx1,
indx2: integer;
begin
Result := true;
try
if FImperium.MakeResearch then exit;
pl := FImperium.GetPlanet(FFromPlanetID);
if (pl = nil) or
(pl.GetBuildLevel('Исследовательская лаборатория') < 1)
then exit;
// пробуем исследовать записанные исследования
rtree1 := FDB.GetPlanetBuildTree(100);
CalcResearch(rtree1, pl, indx1);
// пробуем исследовать исследования для дерева технологий
// необходимых для развития планет
rtree2 := FDB.GetImperiumBuildTree;
CalcResearch(rtree2, pl, indx2);
// выбрать минимальное по времени исследование
if (indx1 >= 0) and (indx2 >= 0) then
begin
if FDB.GetBuildingLength(
rtree1[indx1].Name,
FImperium.GetResearchLevel(rtree1[indx1].Name)) >
FDB.GetBuildingLength(rtree2[indx2].Name,
FImperium.GetResearchLevel(rtree1[indx2].Name))
then
indx1 := 0;
end;
if indx1 >= 0 then
begin
Result := FServer.MakeResearch(FImperium, FFromPlanetID,
rtree1[indx1].Name, rtree1[indx1].Level);
exit;
end;
if indx2 >= 0 then
begin
Result := FServer.MakeResearch(FImperium, FFromPlanetID,
rtree2[indx2].Name, rtree2[indx2].Level);
exit;
end;
// планируем исследования, если счас ничего не исследуется
// или ничего не получилось исследовать
CalcResearchPlan(rtree1, pl, indx1);
CalcResearchPlan(rtree2, pl, indx2);
if indx1 >= 0 then
begin
FImperium.ResearchingPlan.Clear;
FImperium.ResearchingPlan.Item := rtree1[indx1];
FImperium.ResearchingPlan.EndPlaningDate :=
Now + 1 / SecsPerDay * FPlaningLock;
exit;
end;
if indx2 >= 0 then
begin
FImperium.ResearchingPlan.Clear;
FImperium.ResearchingPlan.Item := rtree2[indx2];
FImperium.ResearchingPlan.EndPlaningDate :=
Now + 1 / SecsPerDay * FPlaningLock;
exit;
end;
except
end;
end;
procedure TStResearch.CalcResearch(rtree: TGameItems; pl: TPlanet;
var indx: Integer);
var
res: TGameRes;
MinResSumm: Int64;
i: Integer;
level: Integer;
rlen: Integer;
begin
indx := -1;
MinResSumm := -1;
for i := 0 to length(rtree) - 1 do
begin
if rtree[i].GroupName <> 'Исследования' then continue;
level := FImperium.GetResearchLevel(rtree[i].Name);
res := FDB.GetBuildingRes(rtree[i].Name, level);
rlen := Trunc(FDB.GetBuildingLength(rtree[i].Name, level) * 24 * 60 * 60);
if (rtree[i].Level > level) and
((FMaxLength = 0) or (rlen < FMaxLength)) and
(not res.Eq0) and
(pl.HaveResources(res)) and
((MinResSumm < 0) or (MinResSumm > res.EkvResSumm)) and
(FImperium.CanResearch(rtree[i].Name)) then
begin
MinResSumm := res.EkvResSumm;
indx := i;
end;
end;
end;
function TStResearch.LoadConfig(cfg: string): ISuperObject;
begin
Result := inherited LoadConfig(cfg);
FLockRes := SOAsBooleanDef(Result, 'LockRes', false);
FMaxLength := SOAsIntegerDef(Result, 'MaxLength', 0);
FPlaningLock := SOAsIntegerDef(Result, 'PlaningLock', 60 * 30);
end;
end.
|
program Ems_Test;
{ *************************************************************
* This program shows you how to use the basic functions of *
* the LIM Expanded Memory Specification. Since it does not *
* use any of the LIM EMS 4.0 function calls, you can also *
* use it on systems with EMS versions less than 4.0 *
************************************************************* }
{ Written by:
Peter Immarco.
Thought Dynamics
Manhattan Beach, CA
Compuserve ID# 73770,123
*** Public Domain ***
Used by permission of the author.
}
{ This program does the following:
+------------------------------------------------------------+
| * Makes sure the LIM Expanded Memory Manager (EMM) has |
| been installed in memory |
| * Displays the version number of the EMM present in memory |
| * Determines if there are enough pages (16k blocks) of |
| memory for our test program's usage. It then displays |
| the total number of EMS pages present in the system, |
| and how many are available for our usage |
| * Requests the desired number of pages from the EMM |
| * Maps a logical page onto one of the physical pages given |
| to us |
| * Displays the base address of our EMS memory page frame |
| * Performs a simple read/write test on the EMS memory given|
| to us |
| * Returns the EMS memory given to us back to the EMM, and |
| exits |
+------------------------------------------------------------|}
{ All the calls are structured to return the result or error
code of the Expanded Memory function performed as an integer.
If the error code is not zero, which means the call failed,
a simple error procedure is called and the program terminates.}
uses Crt, Dos;
Type
ST3 = string[3];
ST80 = string[80];
ST5 = string[5];
Const
EMM_INT = $67;
DOS_Int = $21;
GET_PAGE_FRAME = $41;
GET_UNALLOCATED_PAGE_COUNT= $42;
ALLOCATE_PAGES = $43;
MAP_PAGES = $44;
DEALLOCATE_PAGES = $45;
GET_VERSION = $46;
STATUS_OK = 0;
{ We'll say we need 1 EMS page for our application }
APPLICATION_PAGE_COUNT = 1;
Var
Regs: Registers;
Emm_Handle,
Page_Frame_Base_Address,
Pages_Needed,
Physical_Page,
Logical_Page,
Offset,
Error_Code,
Pages_EMS_Available,
Total_EMS_Pages,
Available_EMS_Pages: Word;
Version_Number,
Pages_Number_String: ST3;
Verify: Boolean;
{ * --------------------------------------------------------- * }
{ The function Hex_String converts an Word into a four
character hexadecimal number(string) with leading zeroes. }
Function Hex_String(Number: Word): ST5;
Function Hex_Char(Number: Word): Char;
Begin
If Number<10 then
Hex_Char:=Char(Number+48)
else
Hex_Char:=Char(Number+55);
end; { Function Hex_Char }
Var
S: ST5;
Begin
S:='';
S:=Hex_Char( (Number shr 1) div 2048);
Number:=( ((Number shr 1) mod 2048) shl 1)+
(Number and 1) ;
S:=S+Hex_Char(Number div 256);
Number:=Number mod 256;
S:=S+Hex_Char(Number div 16);
Number:=Number mod 16;
S:=S+Hex_Char(Number);
Hex_String:=S+'h';
end; { Function Hex_String }
{ * --------------------------------------------------------- * }
{ The function Emm_Installed checks to see if the Expanded
Memory Manager (EMM) is loaded in memory. It does this by
looking for the string 'EMMXXXX0', which should be located
at 10 bytes from the beginning of the code segment pointed
to by the EMM interrupt, 67h }
Function Emm_Installed: Boolean;
Var
Emm_Device_Name : string[8];
Int_67_Device_Name : string[8];
Position : Word;
Regs : registers;
Begin
Int_67_Device_Name:='';
Emm_Device_Name :='EMMXXXX0';
with Regs do
Begin
{ Get the code segment pointed to by Interrupt 67h, the EMM
interrupt by using DOS call $35, 'get interrupt vector' }
AH:=$35;
AL:=EMM_INT;
Intr(DOS_int,Regs);
{ The ES pseudo-register contains the segment address pointed
to by Interrupt 67h }
{ Create an 8 character string from the 8 successive bytes
pointed to by ES:$0A (10 bytes from ES) }
For Position:=0 to 7 do
Int_67_Device_Name:=
Int_67_Device_Name+Chr(mem[ES:Position+$0A]);
Emm_Installed:=True;
{ Is it the EMM manager signature, 'EMMXXXX0'? then EMM is
installed and ready for use, if not, then the EMM manager
is not present }
If Int_67_Device_Name<>Emm_Device_Name
then Emm_Installed:=False;
end; { with Regs do }
end; { Function Emm_Installed }
{ * --------------------------------------------------------- * }
{ This function returns the total number of EMS pages present
in the system, and the number of EMS pages that are
available for our use }
Function EMS_Pages_Available
(Var Total_EMS_Pages,Pages_Available: Word): Word;
Var
Regs: Registers;
Begin
with Regs do
Begin
{ Put the desired EMS function number in the AH pseudo-
register }
AH:=Get_Unallocated_Page_Count;
intr(EMM_INT,Regs);
{ The number of EMS pages available is returned in BX }
Pages_Available:=BX;
{ The total number of pages present in the system is
returned in DX }
Total_EMS_Pages:=DX;
{ Return the error code }
EMS_Pages_Available:=AH
end;
end; { EMS_Pages_Available }
{ * --------------------------------------------------------- * }
{ This function requests the desired number of pages from the
EMM }
Function Allocate_Expanded_Memory_Pages
(Pages_Needed: Word; Var Handle: Word ): Word;
Var
Regs: Registers;
Begin
with Regs do
Begin
{ Put the desired EMS function number in the AH pseudo-
register }
AH:= Allocate_Pages;
{ Put the desired number of pages in BX }
BX:=Pages_Needed;
intr(EMM_INT,Regs);
{ Our EMS handle is returned in DX }
Handle:=DX;
{ Return the error code }
Allocate_Expanded_Memory_Pages:=AH;
end;
end; { Function Allocate_Expanded_Memory_Pages }
{ * --------------------------------------------------------- * }
{ This function maps a logical page onto one of the physical
pages made available to us by the
Allocate_Expanded_Memory_Pages function }
Function Map_Expanded_Memory_Pages
(Handle,Logical_Page,Physical_Page: Word): Word;
Var
Regs: Registers;
Begin
with Regs do
Begin
{ Put the desired EMS function number in the AH pseudo-
register }
AH:=Map_Pages;
{ Put the physical page number to be mapped into AL }
AL:=Physical_Page;
{ Put the logical page number to be mapped in BX }
BX:=Logical_Page;
{ Put the EMS handle assigned to us earlier in DX }
DX:=Handle;
Intr(EMM_INT,Regs);
{ Return the error code }
Map_Expanded_Memory_Pages:=AH;
end; { with Regs do }
end; { Function Map_Expanded_Memory_Pages }
{ * --------------------------------------------------------- * }
{ This function gets the physical address of the EMS page
frame we are using. The address returned is the segment
of the page frame. }
Function Get_Page_Frame_Base_Address
(Var Page_Frame_Address: Word): Word;
Var
Regs: Registers;
Begin
with Regs do
Begin
{ Put the desired EMS function number in the AH pseudo-
register }
AH:=Get_Page_Frame;
intr(EMM_INT,Regs);
{ The page frame base address is returned in BX }
Page_Frame_Address:=BX;
{ Return the error code }
Get_Page_Frame_Base_Address:=AH;
end; { Regs }
end; { Function Get_Page_Frame_Base_Address }
{ * --------------------------------------------------------- * }
{ This function releases the EMS memory pages allocated to
us, back to the EMS memory pool. }
Function Deallocate_Expanded_Memory_Pages
(Handle: Word): Word;
Var
Regs: Registers;
Begin
with Regs do
Begin
{ Put the desired EMS function number in the AH pseudo-register }
AH:=DEALLOCATE_PAGES;
{ Put the EMS handle assigned to our EMS memory pages in DX }
DX:=Emm_Handle;
Intr(EMM_INT,Regs);
{ Return the error code }
Deallocate_Expanded_Memory_Pages:=AH;
end; { with Regs do }
end; { Function Deallocate_Expanded_Memory_Pages }
{ * --------------------------------------------------------- * }
{ This function returns the version number of the EMM as
a 3 character string. }
Function Get_Version_Number(Var Version_String: ST3): Word;
Var
Regs: Registers;
Word_Part,Fractional_Part: Char;
Begin
with Regs do
Begin
{ Put the desired EMS function number in the AH pseudo-register }
AH:=GET_VERSION;
Intr(EMM_INT,Regs);
{ See if call was successful }
If AH=STATUS_OK then
Begin
{ The upper four bits of AH are the Word portion of the
version number, the lower four bits are the fractional
portion. Convert the Word value to ASCII by adding 48. }
Word_Part := Char( AL shr 4 + 48);
Fractional_Part:= Char( AL and $F +48);
Version_String:= Word_Part+'.'+Fractional_Part;
end; { If AH=STATUS_OK }
{ Return the function calls error code }
Get_Version_Number:=AH;
end; { with Regs do }
end; { Function Get_Version_Number }
{ * --------------------------------------------------------- * }
{ This procedure prints an error message passed by the caller,
prints the error code passed by the caller in hex, and then
terminates the program with the an error level of 1 }
Procedure Error(Error_Message: ST80; Error_Number: Word);
Begin
Writeln(Error_Message);
Writeln(' Error_Number = ',Hex_String(Error_Number) );
Writeln('EMS test program aborting.');
Halt(1);
end; { Procedure Error_Message }
{ * --------------------------------------------------------- * }
{ EMS_TEST }
{ This program is an example of the basic EMS functions that you
need to execute in order to use EMS memory with Turbo Pascal }
Begin
ClrScr;
Window(5,2,77,22);
{ Determine if the Expanded Memory Manager is installed, If
not, then terminate 'main' with an ErrorLevel code of 1. }
If not (Emm_Installed) then
Begin
Writeln('The LIM Expanded Memory Manager is not installed.');
Halt(1);
end;
{ Get the version number and display it }
Error_Code:= Get_Version_Number(Version_Number);
If Error_Code<>STATUS_OK then
Error('Error trying to get the EMS version number ',
Error_code)
else
Writeln('LIM Expanded Memory Manager, version ',
Version_Number,' is ready for use.');
Writeln;
{ Determine if there are enough expanded memory pages for this
application. }
Pages_Needed:=APPLICATION_PAGE_COUNT;
Error_Code:=
EMS_Pages_Available(Total_EMS_Pages,Available_EMS_Pages);
If Error_Code<>STATUS_OK then
Error('Error trying to determine the number of EMS pages available.',
Error_code);
Writeln('There are a total of ',Total_EMS_Pages,
' expanded memory pages present in this system.');
Writeln(' ',Available_EMS_Pages,
' of those pages are available for your usage.');
Writeln;
{ If there is an insufficient number of pages for our application,
then report the error and terminate the EMS test program }
If Pages_Needed>Available_EMS_Pages then
Begin
Str(Pages_Needed,Pages_Number_String);
Error('We need '+Pages_Number_String+
' EMS pages. There are not that many available.',
Error_Code);
end; { Pages_Needed>Available_EMS_Pages }
{ Allocate expanded memory pages for our usage }
Error_Code:= Allocate_Expanded_Memory_Pages(Pages_Needed,Emm_Handle);
Str(Pages_Needed,Pages_Number_String);
If Error_Code<>STATUS_OK then
Error('EMS test program failed trying to allocate '+Pages_Number_String+
' pages for usage.',Error_Code);
Writeln(APPLICATION_PAGE_COUNT,
' EMS page(s) allocated for the EMS test program.');
Writeln;
{ Map in the required logical pages to the physical pages
given to us, in this case just one page }
Logical_Page :=0;
Physical_Page:=0;
Error_Code:=
Map_Expanded_Memory_Pages(
Emm_Handle,Logical_Page,Physical_Page);
If Error_Code<>STATUS_OK then
Error('EMS test program failed trying to map '+
'logical pages onto physical pages.',Error_Code);
Writeln('Logical Page ',Logical_Page,
' successfully mapped onto Physical Page ',
Physical_Page);
Writeln;
{ Get the expanded memory page frame address }
Error_Code:= Get_Page_Frame_Base_Address(Page_Frame_Base_Address);
If Error_Code<>STATUS_OK then
Error('EMS test program unable to get the base Page'+
' Frame Address.',Error_Code);
Writeln('The base address of the EMS page frame is - '+
Hex_String(Page_Frame_Base_Address) );
Writeln;
{ Write a test pattern to expanded memory }
For Offset:=0 to 16382 do
Mem[Page_Frame_Base_Address:Offset]:=Offset mod 256;
{ Make sure that what is in EMS memory is what we just wrote }
Writeln('Testing EMS memory.');
Offset:=1;
Verify:=True;
while (Offset<=16382) and (Verify=True) do
Begin
If Mem[Page_Frame_Base_Address:Offset]<>Offset mod 256 then
Verify:=False;
Offset:=Succ(Offset);
end; { while (Offset<=16382) and (Verify=True) }
{ If it isn't report the error }
If not Verify then
Error('What was written to EMS memory was not found during '+
'memory verification test.',0);
Writeln('EMS memory test successful.');
Writeln;
{ Return the expanded memory pages given to us back to the
EMS memory pool before terminating our test program }
Error_Code:=Deallocate_Expanded_Memory_Pages(Emm_Handle);
If Error_Code<>STATUS_OK then
Error('EMS test program was unable to deallocate '+
'the EMS pages in use.',Error_Code);
Writeln(APPLICATION_PAGE_COUNT,
' page(s) deallocated.');
Writeln;
Writeln('EMS test program completed.');
end.
|
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls,
StdCtrls, ExtCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
Edit1: TEdit;
Label1: TLabel;
PageControl1: TPageControl;
Panel1: TPanel;
SelectDirectoryDialog1: TSelectDirectoryDialog;
TabSheet1: TTabSheet;
procedure Button1Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure CreateRep; // создать репозитарий
procedure SelectWay; // Управление действием
procedure ShowTree; // отобразить дерево репозитария
private
{ private declarations }
public
{ public declarations }
end;
var
Form1 : TForm1;
way : integer; // указатель для ветвления алгоритма программы
repName : string; // имя репозитария
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
// создать новый репозитарий
begin
label1.Caption:='Имя вашего нового репозитария:';
edit1.Caption:='MyRep';
way:=1;
panel1.Visible:=true;
end;
procedure TForm1.Button6Click(Sender: TObject); // ок панели запроса
begin
panel1.Visible:=false;
selectway
end;
procedure tform1.SelectWay;
begin
case way of
1: createrep;
end;
end;
procedure tform1.CreateRep; // сoздать репозитарий
var
rep: string;
begin
SelectDirectoryDialog1.Title:='Папка для вашего репозитария';
if SelectDirectoryDialog1.Execute then
begin
repName:=edit1.caption;
rep:=SelectDirectoryDialog1.FileName+repName;
createdir(rep);
{
здесь создать основу структуры репозитария (дерево папок)
}
showtree; // отобразить дерево репозитария
end;
end;
procedure tform1.ShowTree;
begin
//treeview1.Items.Clear; // clear tree
//treeview1.Items.Add(nil, 'repName'); // верхний узел
end;
end.
|
unit Kafka.FMX.Helper;
interface
uses
System.Types,
FMX.Grid;
type
TFMXHelper = class
public
const MAX_LOG_LINES = 5000;
public
class procedure SetGridRowCount(const Grid: TGrid; const RowCount: Integer; const ScrollToBottom: Boolean = True); static;
end;
implementation
class procedure TFMXHelper.SetGridRowCount(const Grid: TGrid; const RowCount: Integer; const ScrollToBottom: Boolean);
var
ViewPort, CellRect: TRectF;
SelectedRow, SelectedColumn: Integer;
begin
if RowCount <> Grid.RowCount then
begin
Grid.BeginUpdate;
try
if Grid.Selected <> -1 then
begin
SelectedRow := Grid.Row;
SelectedColumn := Grid.Col;
if SelectedColumn = 1 then
begin
SelectedColumn := 0;
end;
end;
Grid.Selected := -1;
Grid.RowCount := RowCount;
finally
Grid.EndUpdate;
end;
if not Grid.IsFocused then
begin
Grid.ScrollBy(0, MaxInt);
Grid.SelectRow(Grid.RowCount - 1);
Grid.Repaint;
end
else
begin
// This is a tricky workaround for an awful FMX bug
ViewPort := RectF(
0,
Grid.ViewportPosition.Y,
MaxInt,
Grid.ViewportPosition.Y + Grid.ViewportSize.Height);
CellRect := Grid.CellRect(0, SelectedRow);
if ViewPort.Contains(CellRect) then
begin
Grid.SelectCell(SelectedColumn, SelectedRow);
end;
end;
end;
end;
end.
|
unit ncafbMaqConfig;
{
ResourceString: Dario 10/03/13
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmFormBase, dxPSGlbl, dxPSUtl,
dxPSEngn, dxPrnPg, dxBkgnd, dxWrap, dxPrnDev, dxPSCompsProvider,
dxPSFillPatterns, dxPSEdgePatterns, dxBar, dxPSCore, cxGridCustomPopupMenu,
cxGridPopupMenu, cxClasses, ExtCtrls, cxStyles, cxCustomData, cxGraphics,
cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel,
cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, cxMemo, cxMaskEdit, cxSpinEdit, cxContainer,
cxLabel, LMDPNGImage, LMDControl, LMDCustomControl, LMDCustomPanel,
LMDCustomBevelPanel, LMDSimplePanel, cxLookAndFeels, cxLookAndFeelPainters,
dxPSPDFExportCore, dxPSPDFExport, cxDrawTextUtils, dxPSPrVwStd, dxPSPrVwAdv,
dxPSPrVwRibbon, dxPScxPageControlProducer, dxPScxGridLnk,
dxPScxGridLayoutViewLnk, dxPScxEditorProducers, dxPScxExtEditorProducers,
cxNavigator, dxPScxPivotGridLnk;
type
TfbMaqConfig = class(TFrmBase)
Grid: TcxGrid;
TV: TcxGridDBTableView;
GL: TcxGridLevel;
TVNumero: TcxGridDBColumn;
TVNome: TcxGridDBColumn;
TVComputerName: TcxGridDBColumn;
TVIDCliente: TcxGridDBColumn;
TVDisplayWH: TcxGridDBColumn;
TVRAM: TcxGridDBColumn;
TVCPU: TcxGridDBColumn;
TVOS: TcxGridDBColumn;
TVPrinters: TcxGridDBColumn;
TVDrives: TcxGridDBColumn;
TVHDTotal: TcxGridDBColumn;
TVIP: TcxGridDBColumn;
TVHDFree: TcxGridDBColumn;
dxBarSubItem1: TdxBarSubItem;
cmSessoes: TdxBarButton;
LMDSimplePanel1: TLMDSimplePanel;
Image1: TImage;
lbInfo: TcxLabel;
TVMacAddress: TcxGridDBColumn;
cxStyleRepository1: TcxStyleRepository;
cxsVer: TcxStyle;
procedure TVOSGetDisplayText(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AText: string);
procedure TVRAMGetDisplayText(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AText: string);
procedure cmEditarClick(Sender: TObject);
procedure cmNovoClick(Sender: TObject);
procedure cmApagarClick(Sender: TObject);
procedure TVFocusedRecordChanged(Sender: TcxCustomGridTableView;
APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure cmSessoesClick(Sender: TObject);
procedure TVDisplayWHGetDisplayText(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AText: string);
private
{ Private declarations }
public
class function Descricao: String; override;
procedure AtualizaDireitos; override;
procedure AjustaLayoutLargeButton(B : TdxBarLargeButton); override;
procedure AtualizaBotoes;
{ Public declarations }
end;
var
fbMaqConfig: TfbMaqConfig;
implementation
uses ncaDM, ncaFrmPri, ncaFrmMaq, ncClassesBase, ncafbMaq, ncVersoes,
ufmImagens;
// START resource string wizard section
resourcestring
SOpções = 'Opções';
SRemover = '&Remover';
SRecursoDesativadoÉNecessárioComp = '* Recurso desativado. É necessário comprar uma atualização do NexCafé para ativar esse recurso';
SAsInformaçõesDeConfiguraçãoDosCo = 'As informações de configuração dos computadores da loja são coletadas automaticamente pelo NexCafé. ';
SAsMáquinasClientesEnviamOsDadosD = 'As máquinas clientes enviam os dados de sua configuração no momento em que se conectam ao servidor ';
SNexCaféAtravésDoNexGuard = 'NexCafé através do NexGuard.';
SNãoéPossívelApagarUmaMáquinaComA = 'Não é possível apagar uma máquina com acesso em andamento';
SConfirmaAExclusãoDaMáquina = 'Confirma a exclusão da Máquina ';
SInfoMáquinas = 'Info.Máquinas';
// END resource string wizard section
{$R *.dfm}
{ TFrmBase1 }
const
kilobyte = 1;
megabyte = kilobyte * 1024;
gigabyte = megabyte * 1024;
function KByteStr(K: Cardinal): String;
var sufix: String; code: word;
begin
if K>=gigabyte then begin
sufix := 'GB'; // do not localize
Str(K/gigabyte:0:2, result);
end else
if K>=megabyte then
begin
sufix := 'MB'; // do not localize
Str(K/megabyte:0:2, result);
end
else begin
sufix := 'KB'; // do not localize
Result := IntToStr(K);
end;
while (Length(Result)>0) and (Result[Length(Result)] in ['0', '.']) do Delete(Result, Length(Result), 1);
if Result>'0' then
Result := Result + ' ' + sufix else
Result := '';
end;
procedure TfbMaqConfig.AjustaLayoutLargeButton(B: TdxBarLargeButton);
begin
end;
procedure TfbMaqConfig.AtualizaBotoes;
begin
try
with Dados do
if mtMaquina.RecordCount>0 then begin
cmEditar.Enabled := Dados.CM.UA.Admin;
cmApagar.Enabled := Dados.CM.Ua.Admin;
cmNovo.Enabled := Dados.CM.UA.Admin;
end else begin
cmEditar.Caption := SOpções;
cmEditar.Enabled := False;
cmApagar.Caption := SRemover;
cmApagar.Enabled := False;
end;
except
end;
end;
procedure TfbMaqConfig.AtualizaDireitos;
begin
inherited;
if not Versoes.PodeUsar(idre_configmaq) then begin
lbInfo.Caption := SRecursoDesativadoÉNecessárioComp;
lbInfo.Style.TextStyle := [fsBold];
cxsVer.TextColor := clSilver;
end else begin
lbInfo.Caption := SAsInformaçõesDeConfiguraçãoDosCo+
SAsMáquinasClientesEnviamOsDadosD+
SNexCaféAtravésDoNexGuard;
lbInfo.Style.TextStyle := [];
cxsVer.TextColor := clBlack;
end;
AtualizaBotoes;
end;
procedure TfbMaqConfig.cmApagarClick(Sender: TObject);
var M : TncMaquina;
begin
inherited;
with Dados do begin
if mtMaquina.RecordCount=0 then Exit;
if CM.Sessoes.PorMaq[mtMaquinaNumero.Value]<>nil then begin
Beep;
ShowMessage(SNãoéPossívelApagarUmaMáquinaComA);
Exit;
end;
M := CM.Maquinas.PorNumero[mtMaquinaNumero.Value];
if M<>nil then
if MessageDlg(SConfirmaAExclusãoDaMáquina+mtMaquinaNumero.AsString, mtConfirmation,
[mbYes, mbNo], 0) = mrYes then
CM.ApagaObj(M);
end;
end;
procedure TfbMaqConfig.cmEditarClick(Sender: TObject);
var M : TncMaquina;
begin
inherited;
with Dados do
M := CM.Maquinas.PorNumero[mtMaquinaNumero.Value];
if M=nil then Exit;
TFrmMaq.Create(Self).Editar(M);
end;
procedure TfbMaqConfig.cmNovoClick(Sender: TObject);
begin
inherited;
Dados.NovaMaq;
end;
procedure TfbMaqConfig.cmSessoesClick(Sender: TObject);
begin
inherited;
TfbMaq(FrmPri.FM.FormAtivo).Paginas.ActivePageIndex := 0;
end;
class function TfbMaqConfig.Descricao: String;
begin
Result := SInfoMáquinas;
end;
procedure TfbMaqConfig.TVDisplayWHGetDisplayText(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AText: string);
begin
inherited;
if not Versoes.PodeUsar(idre_configmaq) then AText := '*';
end;
procedure TfbMaqConfig.TVFocusedRecordChanged(Sender: TcxCustomGridTableView;
APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
begin
inherited;
AtualizaBotoes;
end;
procedure TfbMaqConfig.TVOSGetDisplayText(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AText: string);
var V: Variant;
begin
inherited;
if not Versoes.PodeUsar(idre_configmaq) then begin
AText := '*';
Exit;
end;
V := ARecord.Values[TVOS.Index];
if V=null then
AText := '' else
AText := V;
if Pos('Windows', AText)=1 then // do not localize
Delete(AText, 1, 8);
end;
procedure TfbMaqConfig.TVRAMGetDisplayText(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AText: string);
var V: Variant;
begin
inherited;
if not Versoes.PodeUsar(idre_configmaq) then begin
AText := '*';
Exit;
end;
V := ARecord.Values[Sender.Index];
if V=null then
AText := '' else
AText := KByteStr(V);
end;
end.
|
(* Chapter 3 - Program 3 *)
program AllSimpleVariableTypes;
var A,B : integer;
C,D : 0..255;
DogTail : real;
Puppy : boolean;
AnimalCookies : char;
begin
A := 4;
B := 5;
C := 212;
D := C + 3;
DogTail := 345.12456;
Puppy := B > A; (* since B is greater than A, Puppy
will be assigned the value TRUE *)
AnimalCookies := 'R'; (* this is a single character *)
Writeln('The integers are',A:5,B:5);
Writeln('The bytes are', C:5,D:5); (* notice that the spaces
prior to the C will be
ignored on output *)
Writeln('The real value is',DogTail:12:2,DogTail:12:4);
Writeln;
Writeln('The boolean value is ',Puppy,Puppy:13);
Writeln('The char variable is an ',AnimalCookies);
end.
{ Result of execution
The integers are 4 5
The bytes are 212 215
The real value is 345.12 345.1246
The boolean value is TRUE TRUE
The char variable is an R
}
|
unit uBuffer;
interface
uses Classes, ExtCtrls;
type
THDMBuffer = class (TObject)
private
fOwner: TComponent;
fTimer: TTimer;
fValue: String;
fOnValueChange: TNotifyEvent;
procedure OnTimer(Sender: TObject);
function GetResetInterval: Integer;
procedure SetResetInterval(const pValue: Integer);
procedure SetValue(const pValue: String);
procedure DebugLog(Value: String);
public
constructor Create(pOwner: TComponent);
destructor Destroy; Override;
procedure Add(const pValue: String);
procedure Clear;
property Value: String read fValue write SetValue;
property ResetInterval: Integer read GetResetInterval write SetResetInterval;
property OnValueChanged: TNotifyEvent read fOnValueChange write fOnValueChange;
end;
implementation
uses uGlobals, SysUtils;
{ THDMBuffer }
procedure THDMBuffer.Add(const pValue: String);
begin
Value := fValue + pValue;
end;
procedure THDMBuffer.Clear;
begin
DebugLog('Buffer clear on Clear call.');
Value := '';
end;
constructor THDMBuffer.Create(pOwner: TComponent);
begin
fOwner := pOwner;
fTimer := TTimer.Create(fOwner);
fTimer.Enabled := False;
fTimer.OnTimer := OnTimer;
fTimer.Interval := 2000;
end;
procedure THDMBuffer.DebugLog(Value: String);
begin
Glb.DebugLog(Value, 'BUF');
end;
destructor THDMBuffer.Destroy;
begin
fTimer.Free;
inherited;
end;
function THDMBuffer.GetResetInterval: Integer;
begin
Result := fTimer.Interval;
end;
procedure THDMBuffer.OnTimer(Sender: TObject);
begin
Value := '';
fTimer.Enabled := False;
DebugLog('Buffer clear on timeout.');
end;
procedure THDMBuffer.SetResetInterval(const pValue: Integer);
begin
if (pValue <> 0) and (pValue < 100) then
fTimer.Interval := 100
else
fTimer.Interval := pValue;
DebugLog('Reset interval is ' + IntToStr(fTimer.Interval) +
', requested ' + IntToStr(pValue));
end;
procedure THDMBuffer.SetValue(const pValue: String);
var
lChanged: Boolean;
begin
lChanged := (fValue <> pValue);
fValue := pValue;
// reset timer
if fTimer.Enabled then
fTimer.Enabled := False; // restart
if fTimer.Interval > 0 then
fTimer.Enabled := True;
if lChanged and Assigned(fOnValueChange) then
fOnValueChange(Self);
DebugLog('Buffer: ' + fValue);
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
//
//主要实现:
用户权限管理
//-----------------------------------------------------------------------------}
unit untGroupRights;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, untEasyPlateDBBaseForm, ExtCtrls, untEasyGroupBox, untGroupRightsObjects,
untEasyToolBar, untEasyToolBarStylers, ComCtrls, untEasyTreeView, ImgList,
DB, DBClient, StdCtrls, ActnList;
//插件导出函数
function ShowBplForm(AParamList: TStrings): TForm; stdcall; exports ShowBplForm;
type
TfrmGroupRights = class(TfrmEasyPlateDBBaseForm)
EasyPanel1: TEasyPanel;
EasyPanel3: TEasyPanel;
EasyPanel4: TEasyPanel;
EasyDockPanel1: TEasyDockPanel;
EasyToolBar1: TEasyToolBar;
EasyToolBarOfficeStyler1: TEasyToolBarOfficeStyler;
Splitter1: TSplitter;
tvUserGroups: TEasyTreeView;
btnAddRole: TEasyToolBarButton;
imgUserGroup: TImageList;
btnEditRole: TEasyToolBarButton;
btnDeleteRole: TEasyToolBarButton;
EasyToolBarButton5: TEasyToolBarButton;
cdsGroups: TClientDataSet;
cdsUsers: TClientDataSet;
cdsResources: TClientDataSet;
EasyPanel2: TEasyPanel;
EasyPanel5: TEasyPanel;
EasyPanel6: TEasyPanel;
Splitter2: TSplitter;
EasyPanel7: TEasyPanel;
Splitter3: TSplitter;
EasyPanel8: TEasyPanel;
tvUserRoles: TEasyTreeView;
EasyPanel9: TEasyPanel;
tvUsers: TEasyTreeView;
tvCheckResources: TEasyCheckTree;
cdsUserResource: TClientDataSet;
actGroupRights: TActionList;
actAddGroup: TAction;
actEditGroup: TAction;
actDelGroup: TAction;
EasyToolBarSeparator2: TEasyToolBarSeparator;
actRoleUsers: TAction;
cdsCompany: TClientDataSet;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure tvUserGroupsClick(Sender: TObject);
procedure tvUserRolesClick(Sender: TObject);
procedure tvUsersClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure actAddGroupExecute(Sender: TObject);
procedure actEditGroupExecute(Sender: TObject);
procedure actEditGroupUpdate(Sender: TObject);
procedure actDelGroupUpdate(Sender: TObject);
procedure actAddGroupUpdate(Sender: TObject);
procedure actRoleUsersUpdate(Sender: TObject);
procedure actRoleUsersExecute(Sender: TObject);
procedure EasyToolBarButton5Click(Sender: TObject);
private
{ Private declarations }
FGroupCompanyList,
FGroupDeptList,
FGroupRoleList,
FGroupUserList,
FGroupRoleResourceList: TList;
//用户组--公司
procedure InitGroupsTree(AClientDataSet: TClientDataSet);
function InitRootGroupTree(AClientDataSet: TClientDataSet): TTreeNode;
function ExistsGroupCompany(AKeyStr: string): Boolean;
//用户组--部门
function InitRootDeptTree(AClientDataSet: TClientDataSet): TTreeNode;
function FindGroupCompany(ACompanyGUID: string): TTreeNode;
function InitDeptTree(AClientDataSet: TClientDataSet): TTreeNode;
function FindGroupDept(ADeptGUID: string): TTreeNode;
//用户组--角色
procedure InitRoleTree(AClientDataSet: TClientDataSet; ADeptGUID: string);
function FindRoleNode(ARoleGUID: string): TTreeNode;
//显示部门下的角色信息
procedure DisplayRoles(ADeptGUID: string);
procedure DisposeGroupRoleList;
//显示角色下对应的员工
procedure DisplayUsers(ARoleGUID: string);
procedure InitUserTree(AClientDataSet: TClientDataSet; ARoleGUID: string);
procedure DisposeGroupUserList;
//显示角色所对应的权限资源
procedure DisplayRole_Resources(ARoleGUID: string);
procedure GetUserResources(ALoginName: string);
procedure DisplayUser_Resources(AClientDataSet: TClientDataSet; ALoginName: string);
//系统权限树
procedure InitResourcesTree(AClientDataSet: TClientDataSet);
function FindResourceParentNode(AParentRightGUID: string): TTreeNode;
//权限资源管理时的刷新操作
procedure RefreshRoleResouse;
public
{ Public declarations }
end;
var
frmGroupRights: TfrmGroupRights;
implementation
uses untGroupRightsOperate, untEasyUtilConst, untEasyUtilMethod,
untGroupRoleUserOperate;
{$R *.dfm}
//引出函数实现
function ShowBplForm(AParamList: TStrings): TForm;
begin
frmGroupRights := TfrmGroupRights.Create(Application);
if frmGroupRights.FormStyle <> fsMDIChild then
frmGroupRights.FormStyle := fsMDIChild;
if frmGroupRights.WindowState <> wsMaximized then
frmGroupRights.WindowState := wsMaximized;
Result := frmGroupRights;
end;
//此公司是否已生成对应树节点
function TfrmGroupRights.ExistsGroupCompany(AKeyStr: string): Boolean;
var
J: Integer;
begin
Result := False;
for J := 0 to FGroupCompanyList.Count - 1 do
begin
if TGroupCompany(FGroupCompanyList.Items[J]).GUID = AKeyStr then
begin
Result := True;
Break;
end;
end;
end;
procedure TfrmGroupRights.FormCreate(Sender: TObject);
var
sCompanySQL,
sGroupsSQL,
sUsersSQL,
sRoleResourceSQL: string;
ASQLOLE,
AResult: OleVariant;
begin
inherited;
if not Assigned(FGroupCompanyList) then
FGroupCompanyList := TList.Create;
if not Assigned(FGroupDeptList) then
FGroupDeptList := TList.Create;
if not Assigned(FGroupRoleList) then
FGroupRoleList := TList.Create;
if not Assigned(FGroupUserList) then
FGroupUserList := TList.Create;
if not Assigned(FGroupRoleResourceList) then
FGroupRoleResourceList := TList.Create;
FormId := '{3477B007-80AE-414E-BF67-9709FEEB3DD8}';
ASQLOLE := VarArrayCreate([0, 3], varVariant);
sGroupsSQL := 'SELECT * FROM vw_Groups ORDER BY sCompanyID, iDeptOrder, iRoleOrder';
ASQLOLE[0] := sGroupsSQL;
// cdsGroups.Data := EasyRDMDisp.EasyGetRDMData(sGroupsSQL);
sUsersSQL := 'SELECT LoginGUID, sLoginName, sRoleGUID, sEmployeeGUID, sEmployeeCName,'
+' sEmployeeEName, sSexGUID FROM vw_InitUser '
+' WHERE bEnable = 1 ORDER BY iOrderNo';
{sUsersSQL := 'SELECT A.LoginGUID, A.sLoginName, A.sRoleGUID, A.sEmployeeGUID, A.sEmployeeCName,'
+' A.sEmployeeEName, A.sSexGUID '
+' FROM sysRole_user B LEFT JOIN vw_InitUser A ON B.LoginGUID = A.LoginGUID '
+' WHERE bEnable = 1 AND GETDATE() < dDisenableTime '
+' ORDER BY iOrderNo';}
ASQLOLE[1] := sUsersSQL;
// cdsUsers.Data := EasyRDMDisp.EasyGetRDMData(sUsersSQL);
sRoleResourceSQL := 'SELECT * FROM vw_RoleResource';
ASQLOLE[2] := sRoleResourceSQL;
// cdsResources.Data := EasyRDMDisp.EasyGetRDMData(sRoleResourceSQL);
sCompanySQL := 'SELECT * FROM vw_Company';
ASQLOLE[3] := sCompanySQL;
AResult := EasyRDMDisp.EasyGetRDMDatas(ASQLOLE);
cdsGroups.Data := AResult[0];
cdsUsers.Data := AResult[1];
cdsResources.Data := AResult[2];
cdsCompany.Data := AResult[3];
end;
procedure TfrmGroupRights.InitGroupsTree(AClientDataSet: TClientDataSet);
var
I : Integer;
ARootNode,
AGroupRootNode: TTreeNode;
AGroupCompany : TGroupCompany;
begin
{
正常情况
|--公司
| --部门
| --角色
特殊一点
|--公司
| --部门
| --部门
| --角色
| --角色
角色的父节点主要解决【权限的继承】问题、不实现树结构
本函数解决 特殊一点 的实现
}
//公司信息初始化到组
//只处理总公司和分公司两种关系、公司嵌套未实现
//初始化总公司
tvUserGroups.Items.BeginUpdate;
AGroupRootNode := InitRootGroupTree(cdsCompany);
if AGroupRootNode <> nil then
begin
AClientDataSet.Filtered := False;
AClientDataSet.Filter := 'sParentCompanyGUID <> ' + QuotedStr('{00000000-0000-0000-0000-000000000001}');
AClientDataSet.Filtered := True;
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
if not ExistsGroupCompany(AClientDataSet.fieldbyname('CompanyGUID').AsString) then
begin
AGroupCompany := TGroupCompany.Create;
with AGroupCompany do
begin
GUID := AClientDataSet.fieldbyname('CompanyGUID').AsString;
CompanyCName := AClientDataSet.fieldbyname('sCompanyCName').AsString;
CompanyEName := AClientDataSet.fieldbyname('sCompanyEName').AsString;
CompanyID := AClientDataSet.fieldbyname('sCompanyID').AsString;
ParentCompanyGUID := AClientDataSet.fieldbyname('sParentCompanyGUID').AsString;
end;
FGroupCompanyList.Add(AGroupCompany);
ARootNode := tvUserGroups.Items.AddChild(AGroupRootNode, AGroupCompany.CompanyCName);
ARootNode.ImageIndex := 16;
ARootNode.SelectedIndex := ARootNode.ImageIndex + 1;
ARootNode.Data := AGroupCompany;
end;
AClientDataSet.Next;
end;
AClientDataSet.Filtered := False;
end
else
begin
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
if not ExistsGroupCompany(AClientDataSet.fieldbyname('CompanyGUID').AsString) then
begin
AGroupCompany := TGroupCompany.Create;
with AGroupCompany do
begin
GUID := AClientDataSet.fieldbyname('CompanyGUID').AsString;
CompanyCName := AClientDataSet.fieldbyname('sCompanyCName').AsString;
CompanyEName := AClientDataSet.fieldbyname('sCompanyEName').AsString;
CompanyID := AClientDataSet.fieldbyname('sCompanyID').AsString;
ParentCompanyGUID := AClientDataSet.fieldbyname('sParentCompanyGUID').AsString;
end;
FGroupCompanyList.Add(AGroupCompany);
ARootNode := tvUserGroups.Items.AddChild(nil, AGroupCompany.CompanyCName);
ARootNode.ImageIndex := 16;
ARootNode.SelectedIndex := ARootNode.ImageIndex + 1;
ARootNode.Data := AGroupCompany;
end;
AClientDataSet.Next;
end;
end;
//初始化部门树
//实现部门嵌套
InitRootDeptTree(cdsGroups);
//嵌套二级部门
InitDeptTree(cdsGroups);
tvUserGroups.FullExpand;
tvUserGroups.Items.EndUpdate;
end;
procedure TfrmGroupRights.FormShow(Sender: TObject);
begin
inherited;
InitGroupsTree(cdsCompany);
InitResourcesTree(cdsResources);
end;
procedure TfrmGroupRights.FormDestroy(Sender: TObject);
var
I: Integer;
begin
inherited;
for I := FGroupCompanyList.Count - 1 downto 0 do
TObject(FGroupCompanyList.Items[I]).Free;
for I := FGroupDeptList.Count - 1 downto 0 do
TObject(FGroupDeptList.Items[I]).Free;
for I := FGroupUserList.Count - 1 downto 0 do
TObject(FGroupUserList.Items[I]).Free;
DisposeGroupRoleList;
for I := FGroupRoleResourceList.Count - 1 downto 0 do
TObject(FGroupRoleResourceList.Items[I]).Free;
end;
function TfrmGroupRights.InitRootGroupTree(
AClientDataSet: TClientDataSet): TTreeNode;
var
AGroupCompany: TGroupCompany;
begin
Result := nil;
AClientDataSet.Filtered := False;
AClientDataSet.Filter := 'sParentCompanyGUID = ' + QuotedStr('{00000000-0000-0000-0000-000000000001}');
AClientDataSet.Filtered := True;
//集团总公司只允许存在一个,此处没有判断有且只为1的条件
if AClientDataSet.RecordCount > 0 then
begin
AGroupCompany := TGroupCompany.Create;
with AGroupCompany do
begin
GUID := AClientDataSet.fieldbyname('sCompanyCName').AsString;
CompanyCName := AClientDataSet.fieldbyname('sCompanyCName').AsString;
CompanyEName := AClientDataSet.fieldbyname('sCompanyCName').AsString;
CompanyID := AClientDataSet.fieldbyname('sCompanyCName').AsString;
ParentCompanyGUID := AClientDataSet.fieldbyname('sParentCompanyGUID').AsString;
end;
FGroupCompanyList.Add(AGroupCompany);
Result := tvUserGroups.Items.AddChild(nil, AGroupCompany.CompanyCName);
Result.ImageIndex := 12;
Result.SelectedIndex := Result.ImageIndex + 1;
Result.Data := AGroupCompany;
end;
AClientDataSet.Filtered := False;
end;
function TfrmGroupRights.InitRootDeptTree(
AClientDataSet: TClientDataSet): TTreeNode;
var
I : Integer;
AGroupDept: TGroupDept;
begin
Result := nil;
AClientDataSet.Filtered := False;
AClientDataSet.Filter := 'sParentDeptGUID = ' + QuotedStr('{00000000-0000-0000-0000-000000000002}')
+ ' AND DeptGUID <> ' + QuotedStr('');
AClientDataSet.Filtered := True;
if AClientDataSet.RecordCount > 0 then
begin
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
AGroupDept := TGroupDept.Create;
with AGroupDept do
begin
DeptGUID := AClientDataSet.fieldbyname('DeptGUID').AsString;
DeptCName := AClientDataSet.fieldbyname('sDeptCName').AsString;
DeptEName := AClientDataSet.fieldbyname('sDeptEName').AsString;
iOrder := AClientDataSet.fieldbyname('iDeptOrder').AsInteger;
ParentDeptGUID := AClientDataSet.fieldbyname('sParentDeptGUID').AsString;
CompanyGUID := AClientDataSet.fieldbyname('CompanyGUID').AsString;
end;
FGroupDeptList.Add(AGroupDept);
//将部门节点挂靠到对应的公司下面
Result := tvUserGroups.Items.AddChild(FindGroupCompany(AGroupDept.CompanyGUID),
AGroupDept.DeptCName);
Result.Data := AGroupDept;
Result.ImageIndex := 17;
Result.SelectedIndex := Result.ImageIndex + 1;
AClientDataSet.Next;
end;
end;
AClientDataSet.Filtered := False;
end;
function TfrmGroupRights.FindGroupCompany(ACompanyGUID: string): TTreeNode;
var
I : Integer;
ATmpPointer: Pointer;
begin
Result := nil;
ATmpPointer := nil;
for I := 0 to FGroupCompanyList.Count - 1 do
begin
if TGroupCompany(FGroupCompanyList.Items[I]).GUID = ACompanyGUID then
begin
ATmpPointer := FGroupCompanyList.Items[I];
Break;
end;
end;
if ATmpPointer <> nil then
begin
for I := 0 to tvUserGroups.Items.Count - 1 do
begin
if tvUserGroups.Items.Item[I].Data = ATmpPointer then
begin
Result := tvUserGroups.Items.Item[I];
Break;
end;
end;
end;
end;
function TfrmGroupRights.InitDeptTree(
AClientDataSet: TClientDataSet): TTreeNode;
var
I : Integer;
AGroupDept: TGroupDept;
ATmpTreeNode: TTreeNode;
begin
Result := nil;
AClientDataSet.Filtered := False;
AClientDataSet.Filter := 'sParentDeptGUID <> ' + QuotedStr('{00000000-0000-0000-0000-000000000002}')
+ ' AND DeptGUID <> ' + QuotedStr('');
AClientDataSet.Filtered := True;
if AClientDataSet.RecordCount > 0 then
begin
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
if FindGroupDept(AClientDataSet.fieldbyname('DeptGUID').AsString) = nil then
begin
AGroupDept := TGroupDept.Create;
with AGroupDept do
begin
DeptGUID := AClientDataSet.fieldbyname('DeptGUID').AsString;
DeptCName := AClientDataSet.fieldbyname('sDeptCName').AsString;
DeptEName := AClientDataSet.fieldbyname('sDeptEName').AsString;
iOrder := AClientDataSet.fieldbyname('iDeptOrder').AsInteger;
ParentDeptGUID := AClientDataSet.fieldbyname('sParentDeptGUID').AsString;
CompanyGUID := AClientDataSet.fieldbyname('CompanyGUID').AsString;
end;
FGroupDeptList.Add(AGroupDept);
//将部门节点挂靠到对应的父部门节点下面 第二级
//如果不存在父节点就直接挂靠在对应的部门下面
ATmpTreeNode := FindGroupDept(AGroupDept.ParentDeptGUID);
if ATmpTreeNode <> nil then
begin
Result := tvUserGroups.Items.AddChild(ATmpTreeNode, AGroupDept.DeptCName);
end
else
begin
Result := tvUserGroups.Items.AddChild(FindGroupCompany(AGroupDept.CompanyGUID),
AGroupDept.DeptCName);
end;
Result.Data := AGroupDept;
end;
Result.ImageIndex := 17;
Result.SelectedIndex := Result.ImageIndex + 1;
AClientDataSet.Next;
end;
end;
AClientDataSet.Filtered := False;
end;
function TfrmGroupRights.FindGroupDept(ADeptGUID: string): TTreeNode;
var
I : Integer;
ATmpPointer: Pointer;
begin
Result := nil;
ATmpPointer := nil;
for I := 0 to FGroupDeptList.Count - 1 do
begin
if TGroupDept(FGroupDeptList.Items[I]).DeptGUID = ADeptGUID then
begin
ATmpPointer := FGroupDeptList.Items[I];
Break;
end;
end;
if ATmpPointer <> nil then
begin
for I := 0 to tvUserGroups.Items.Count - 1 do
begin
if tvUserGroups.Items.Item[I].Data = ATmpPointer then
begin
Result := tvUserGroups.Items.Item[I];
Break;
end;
end;
end;
end;
procedure TfrmGroupRights.InitRoleTree(AClientDataSet: TClientDataSet; ADeptGUID: string);
var
I : Integer;
AGroupRole: TGroupRole;
ATmpRoleNode: TTreeNode;
begin
AClientDataSet.Filtered := False;
AClientDataSet.Filter := ' DeptGUID = ' + QuotedStr(ADeptGUID)
+ ' AND sParentRoleGUID = ' + QuotedStr('{00000000-0000-0000-0000-000000000004}')
+ ' AND Trim(RoleGUID) <> ' + QuotedStr('');
AClientDataSet.Filtered := True;
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
AGroupRole := TGroupRole.Create;
with AGroupRole do
begin
RoleGUID := AClientDataSet.fieldbyname('RoleGUID').AsString;
RoleName := AClientDataSet.fieldbyname('sRoleName').AsString;
ParentRoleGUID := AClientDataSet.fieldbyname('sParentRoleGUID').AsString;
iOrder := AClientDataSet.fieldbyname('iRoleOrder').AsInteger;
Description := AClientDataSet.fieldbyname('sDiscription').AsString;
DeptGUID := AClientDataSet.fieldbyname('DeptGUID').AsString;
end;
FGroupRoleList.Add(AGroupRole);
//将角色节点挂靠到对应的部门节点下面
ATmpRoleNode := tvUserRoles.Items.AddChild(nil, AGroupRole.RoleName);
ATmpRoleNode.Data := AGroupRole;
ATmpRoleNode.ImageIndex := 3;
ATmpRoleNode.SelectedIndex := ATmpRoleNode.ImageIndex + 1;
AClientDataSet.Next;
end;
AClientDataSet.Filtered := False;
//挂靠二级角色 FindRoleNode
AClientDataSet.Filtered := False;
AClientDataSet.Filter := ' DeptGUID = ' + QuotedStr(ADeptGUID)
+ ' AND sParentRoleGUID <> ' + QuotedStr('{00000000-0000-0000-0000-000000000004}')
+ ' AND Trim(RoleGUID) <> ' + QuotedStr('');
AClientDataSet.Filtered := True;
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
AGroupRole := TGroupRole.Create;
with AGroupRole do
begin
RoleGUID := AClientDataSet.fieldbyname('RoleGUID').AsString;
RoleName := AClientDataSet.fieldbyname('sRoleName').AsString;
ParentRoleGUID := AClientDataSet.fieldbyname('sParentRoleGUID').AsString;
iOrder := AClientDataSet.fieldbyname('iRoleOrder').AsInteger;
Description := AClientDataSet.fieldbyname('sDiscription').AsString;
DeptGUID := AClientDataSet.fieldbyname('DeptGUID').AsString;
end;
FGroupRoleList.Add(AGroupRole);
//将角色节点挂靠到对应的部门节点下面
ATmpRoleNode := tvUserRoles.Items.AddChild(FindRoleNode(AGroupRole.ParentRoleGUID), AGroupRole.RoleName);
ATmpRoleNode.Data := AGroupRole;
ATmpRoleNode.ImageIndex := 3;
ATmpRoleNode.SelectedIndex := ATmpRoleNode.ImageIndex + 1;
AClientDataSet.Next;
end;
AClientDataSet.Filtered := False;
tvUserRoles.FullExpand;
end;
procedure TfrmGroupRights.tvUserGroupsClick(Sender: TObject);
begin
inherited;
DisplayRoles(TGroupDept(tvUserGroups.Selected.Data).DeptGUID);
end;
procedure TfrmGroupRights.DisplayRoles(ADeptGUID: string);
begin
tvUserRoles.Items.BeginUpdate;
tvUserRoles.Items.Clear;
//先释放之前的角色对象
DisposeGroupRoleList;
InitRoleTree(cdsGroups, ADeptGUID);
tvUserRoles.Items.EndUpdate;
end;
procedure TfrmGroupRights.tvUserRolesClick(Sender: TObject);
begin
inherited;
//显示此角色下的所有用户
DisplayUsers(TGroupRole(tvUserRoles.Selected.Data).RoleGUID);
//显示此角色所对应的权限资源
if TGroupRole(tvUserRoles.Selected.Data).ParentRoleGUID <> '{00000000-0000-0000-0000-000000000004}' then
DisplayRole_Resources(TGroupRole(tvUserRoles.Selected.Data).ParentRoleGUID)
else
DisplayRole_Resources(TGroupRole(tvUserRoles.Selected.Data).RoleGUID);
end;
procedure TfrmGroupRights.DisplayUsers(ARoleGUID: string);
begin
tvUsers.Items.BeginUpdate;
tvUsers.Items.Clear;
DisposeGroupUserList;
InitUserTree(cdsUsers, ARoleGUID);
tvUsers.Items.EndUpdate;
end;
procedure TfrmGroupRights.InitUserTree(AClientDataSet: TClientDataSet;
ARoleGUID: string);
var
I : Integer;
AGroupUser : TGroupUser;
ATmpUserNode: TTreeNode;
begin
AClientDataSet.Filtered := False;
AClientDataSet.Filter := ' sRoleGUID = ' + QuotedStr(ARoleGUID);
AClientDataSet.Filtered := True;
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
AGroupUser := TGroupUser.Create;
with AGroupUser do
begin
LoginGUID := AClientDataSet.fieldbyname('LoginGUID').AsString;
LoginName := AClientDataSet.fieldbyname('sLoginName').AsString;
RoleGUID := AClientDataSet.fieldbyname('sRoleGUID').AsString;
EmployeeGUID := AClientDataSet.fieldbyname('sEmployeeGUID').AsString;
EmployeeCName := AClientDataSet.fieldbyname('sEmployeeCName').AsString;
EmployeeEName := AClientDataSet.fieldbyname('sEmployeeEName').AsString;
SexGUID := AClientDataSet.fieldbyname('sSexGUID').AsString;
end;
FGroupUserList.Add(AGroupUser);
//将角色节点挂靠到对应的部门节点下面
ATmpUserNode := tvUsers.Items.AddChild(nil, AGroupUser.EmployeeCName);
ATmpUserNode.Data := AGroupUser;
if AGroupUser.SexGUID = '{CEE37D8D-A822-459A-8352-A723C12C5294}' then
begin
ATmpUserNode.ImageIndex := 1;
ATmpUserNode.SelectedIndex := ATmpUserNode.ImageIndex + 1;
end
else
begin
ATmpUserNode.ImageIndex := 0;
ATmpUserNode.SelectedIndex := ATmpUserNode.ImageIndex + 1;
end;
AClientDataSet.Next;
end;
AClientDataSet.Filtered := False;
end;
procedure TfrmGroupRights.DisposeGroupRoleList;
var
I: Integer;
begin
for I := FGroupRoleList.Count - 1 downto 0 do
TGroupRole(FGroupRoleList.Items[I]).Free;
FGroupRoleList.Clear;
end;
procedure TfrmGroupRights.DisposeGroupUserList;
var
I: Integer;
begin
for I := FGroupUserList.Count - 1 downto 0 do
TGroupUser(FGroupUserList.Items[I]).Free;
FGroupUserList.Clear;
end;
procedure TfrmGroupRights.InitResourcesTree(AClientDataSet: TClientDataSet);
var
I: Integer;
// ATmpResourceNode: TTreeNode;
AGroupResource : TGroupRoleResource;
begin
//先初始化模块
AClientDataSet.Filtered := False;
AClientDataSet.Filter := 'sParentResourceGUID = ' + QuotedStr('{00000000-0000-0000-0000-000000000003}');
AClientDataSet.Filtered := True;
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
AGroupResource := TGroupRoleResource.Create;
with AGroupResource do
begin
GUID := AClientDataSet.fieldbyname('GUID').AsString;
RoleGUID := AClientDataSet.fieldbyname('RoleGUID').AsString;
ResourceGUID := AClientDataSet.fieldbyname('ResourceGUID').AsString;
ResourceName := AClientDataSet.fieldbyname('sResourceName').AsString;
ParentResourceGUID := AClientDataSet.fieldbyname('sParentResourceGUID').AsString;
iOrder := AClientDataSet.fieldbyname('iOrder').AsInteger;
Checked := False;
end;
// ATmpResourceNode := tvCheckResources.Items.AddChild(nil, AGroupResource.ResourceName);
// ATmpResourceNode.Data := AGroupResource;
FGroupRoleResourceList.Add(AGroupResource);
// ATmpResourceNode.ImageIndex := 15;
// ATmpResourceNode.SelectedIndex := ATmpResourceNode.ImageIndex + 1;
AClientDataSet.Next;
end;
AClientDataSet.Filtered := False;
//挂靠可操作资源
AClientDataSet.Filtered := False;
AClientDataSet.Filter := 'sParentResourceGUID <> ' + QuotedStr('{00000000-0000-0000-0000-000000000003}');
AClientDataSet.Filtered := True;
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
AGroupResource := TGroupRoleResource.Create;
with AGroupResource do
begin
GUID := AClientDataSet.fieldbyname('GUID').AsString;
RoleGUID := AClientDataSet.fieldbyname('RoleGUID').AsString;
ResourceGUID := AClientDataSet.fieldbyname('ResourceGUID').AsString;
ResourceName := AClientDataSet.fieldbyname('sResourceName').AsString;
ParentResourceGUID := AClientDataSet.fieldbyname('sParentResourceGUID').AsString;
iOrder := AClientDataSet.fieldbyname('iOrder').AsInteger;
Checked := False;
end;
// ATmpResourceNode := tvCheckResources.Items.AddChild(
// FindResourceParentNode(AGroupResource.ParentResourceGUID),
// AGroupResource.ResourceName);
// ATmpResourceNode.Data := AGroupResource;
FGroupRoleResourceList.Add(AGroupResource);
// ATmpResourceNode.ImageIndex := 15;
// ATmpResourceNode.SelectedIndex := ATmpResourceNode.ImageIndex + 1;
AClientDataSet.Next;
end;
AClientDataSet.Filtered := False;
end;
function TfrmGroupRights.FindResourceParentNode(
AParentRightGUID: string): TTreeNode;
var
I: Integer;
begin
Result := nil;
for I := 0 to tvCheckResources.Items.Count - 1 do
begin
if TGroupRoleResource(tvCheckResources.Items.Item[I].Data).ResourceGUID = AParentRightGUID then
begin
Result := tvCheckResources.Items.Item[I];
Break;
end;
end;
end;
procedure TfrmGroupRights.DisplayRole_Resources(ARoleGUID: string);
var
I: Integer;
ATmpResourceNode: TTreeNode;
AGroupResource : TGroupRoleResource;
begin
tvCheckResources.Items.BeginUpdate;
tvCheckResources.Items.Clear;
for I := 0 to FGroupRoleResourceList.Count - 1 do
begin
AGroupResource := TGroupRoleResource(FGroupRoleResourceList.Items[I]);
if (AGroupResource.RoleGUID = ARoleGUID) and
(AGroupResource.ParentResourceGUID = '{00000000-0000-0000-0000-000000000003}') then
begin
ATmpResourceNode := tvCheckResources.Items.AddChild(nil, AGroupResource.ResourceName);
ATmpResourceNode.Data := FGroupRoleResourceList.Items[I];
ATmpResourceNode.ImageIndex := 15;
ATmpResourceNode.SelectedIndex := ATmpResourceNode.ImageIndex + 1;
end;
end;
for I := 0 to FGroupRoleResourceList.Count - 1 do
begin
AGroupResource := TGroupRoleResource(FGroupRoleResourceList.Items[I]);
if (AGroupResource.RoleGUID = ARoleGUID) and
(AGroupResource.ParentResourceGUID <> '{00000000-0000-0000-0000-000000000003}') then
begin
ATmpResourceNode := tvCheckResources.Items.AddChild(
FindResourceParentNode(AGroupResource.ParentResourceGUID),
AGroupResource.ResourceName);
ATmpResourceNode.Data := FGroupRoleResourceList.Items[I];
ATmpResourceNode.ImageIndex := 15;
ATmpResourceNode.SelectedIndex := ATmpResourceNode.ImageIndex + 1;
end;
end;
tvCheckResources.FullExpand;
tvCheckResources.Items.EndUpdate;
end;
procedure TfrmGroupRights.DisplayUser_Resources(AClientDataSet: TClientDataSet; ALoginName: string);
var
I: Integer;
begin
tvCheckResources.CascadeChecks := False;
for I := 0 to tvCheckResources.Items.Count - 1 do
begin
if AClientDataSet.Locate('ResourceGUID',
VarArrayOf([TGroupRoleResource(tvCheckResources.Items.Item[I].Data).ResourceGUID]),
[loCaseInsensitive]) then
tvCheckResources.ChangeNodeCheckState(tvCheckResources.Items.Item[I], csUnchecked)
else
tvCheckResources.ChangeNodeCheckState(tvCheckResources.Items.Item[I], csChecked);
end;
tvCheckResources.CascadeChecks := True;
end;
procedure TfrmGroupRights.GetUserResources(ALoginName: string);
var
sUserResourceSQL: string;
begin
sUserResourceSQL := 'SELECT * FROM sysLoginUser_Resource WHERE LoginName = '
+ QuotedStr(ALoginName);
cdsUserResource.Data := null;
cdsUserResource.Data := EasyRDMDisp.EasyGetRDMData(sUserResourceSQL);
DisplayUser_Resources(cdsUserResource, ALoginName);
end;
procedure TfrmGroupRights.tvUsersClick(Sender: TObject);
begin
inherited;
GetUserResources(TGroupUser(tvUsers.Selected.Data).LoginName);
end;
procedure TfrmGroupRights.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
cdsGroups.Data := null;
cdsUserResource.Data := null;
cdsResources.Data := null;
cdsUsers.Data := null;
end;
function TfrmGroupRights.FindRoleNode(ARoleGUID: string): TTreeNode;
var
I: Integer;
begin
Result := nil;
for I := 0 to tvUserRoles.Items.Count - 1 do
begin
if TGroupRole(tvUserRoles.Items[I].Data).RoleGUID = ARoleGUID then
begin
Result := tvUserRoles.Items[I];
Break;
end;
end;
end;
procedure TfrmGroupRights.actAddGroupExecute(Sender: TObject);
var
bCancel: Boolean;
sRoleResourceSQL: string;
begin
inherited;
bCancel := False;
if tvUserRoles.Selected.Parent <> nil then
begin
EasyHint(EASY_RIGHT_TOPARENT);
Exit;
end;
frmGroupRightsOperate := TfrmGroupRightsOperate.Create(Self);
with frmGroupRightsOperate do
begin
FOperateType := eotAdd;
FRoleGUID := '';
if tvUserRoles.Selected <> nil then
begin
//如果选择的是根节点,就将新增的父节点设置为根节点的RoleGUID
if TGroupRole(tvUserRoles.Selected.Data).ParentRoleGUID = '{00000000-0000-0000-0000-000000000004}' then
edtRoleName.EditLabel.Hint := TGroupRole(tvUserRoles.Selected.Data).RoleGUID
else
edtRoleName.EditLabel.Hint := '{00000000-0000-0000-0000-000000000004}';
end
else
edtRoleName.EditLabel.Hint := '{00000000-0000-0000-0000-000000000004}';
end;
frmGroupRightsOperate.ShowModal;
if frmGroupRightsOperate.ModalResult = mrCancel then
bCancel := True;
frmGroupRightsOperate.Free;
if not bCancel then
begin
//返回操作则执行刷新
sRoleResourceSQL := 'SELECT * FROM vw_RoleResource ORDER BY sParentResourceGUID, iOrder';
cdsResources.Data := null;
cdsResources.Data := EasyRDMDisp.EasyGetRDMData(sRoleResourceSQL);
RefreshRoleResouse;
end;
end;
procedure TfrmGroupRights.actEditGroupExecute(Sender: TObject);
var
bCancel: Boolean;
sRoleResourceSQL: string;
begin
inherited;
bCancel := False;
if tvUserRoles.Selected.Parent <> nil then
begin
EasyHint(EASY_RIGHT_TOPARENT);
Exit;
end;
frmGroupRightsOperate := TfrmGroupRightsOperate.Create(Self);
with frmGroupRightsOperate do
begin
FOperateType := eotEdit;
FRoleGUID := TGroupRole(tvUserRoles.Selected.Data).RoleGUID;
edtRoleName.EditLabel.Hint := TGroupRole(tvUserRoles.Selected.Data).RoleGUID;
edtRoleName.Text := TGroupRole(tvUserRoles.Selected.Data).RoleName;
edtParentRole.EditLabel.Hint := TGroupRole(tvUserRoles.Selected.Data).RoleGUID;
if tvUserRoles.Selected.Parent <> nil then
edtParentRole.Text := TGroupRole(tvUserRoles.Selected.Parent.Data).RoleName
else
edtParentRole.Text := 'NULL';
end;
frmGroupRightsOperate.ShowModal;
if frmGroupRightsOperate.ModalResult = mrCancel then
bCancel := True;
frmGroupRightsOperate.Free;
if not bCancel then
begin
//返回操作则执行刷新
sRoleResourceSQL := 'SELECT * FROM vw_RoleResource ORDER BY sParentResourceGUID, iOrder';
cdsResources.Data := null;
cdsResources.Data := EasyRDMDisp.EasyGetRDMData(sRoleResourceSQL);
RefreshRoleResouse;
end;
end;
procedure TfrmGroupRights.actEditGroupUpdate(Sender: TObject);
begin
inherited;
actEditGroup.Enabled := (tvUserRoles.Selected <> nil) and
(TGroupRole(tvUserRoles.Selected.Data).ParentRoleGUID = '{00000000-0000-0000-0000-000000000004}');
end;
procedure TfrmGroupRights.actDelGroupUpdate(Sender: TObject);
begin
inherited;
actDelGroup.Enabled := tvUserRoles.Selected <> nil;
end;
procedure TfrmGroupRights.RefreshRoleResouse;
begin
EasyFreeAndNilList(FGroupRoleResourceList);
//显示此角色所对应的权限资源
InitResourcesTree(cdsResources);
if TGroupRole(tvUserRoles.Selected.Data).ParentRoleGUID <> '{00000000-0000-0000-0000-000000000004}' then
DisplayRole_Resources(TGroupRole(tvUserRoles.Selected.Data).ParentRoleGUID)
else
DisplayRole_Resources(TGroupRole(tvUserRoles.Selected.Data).RoleGUID);
end;
procedure TfrmGroupRights.actAddGroupUpdate(Sender: TObject);
begin
inherited;
actAddGroup.Enabled := not (tvUserGroups.Selected.HasChildren);
end;
procedure TfrmGroupRights.actRoleUsersUpdate(Sender: TObject);
begin
inherited;
actRoleUsers.Enabled := (tvUserRoles.Selected <> nil);
end;
procedure TfrmGroupRights.actRoleUsersExecute(Sender: TObject);
begin
inherited;
if tvUserRoles.Selected = nil then Exit;
frmGroupRoleUserOperate := TfrmGroupRoleUserOperate.Create(Application);
with frmGroupRoleUserOperate do
begin
edtRoleName.Text := TGroupRole(tvUserRoles.Selected.Data).RoleName;
edtRoleName.EditLabel.Hint := TGroupRole(tvUserRoles.Selected.Data).RoleGUID;
end;
frmGroupRoleUserOperate.ShowModal;
frmGroupRoleUserOperate.Free;
end;
procedure TfrmGroupRights.EasyToolBarButton5Click(Sender: TObject);
begin
inherited;
Close;
end;
end.
|
{ *********************************************************************** }
{ }
{ Copyright (c) 2003 Borland Software Corporation }
{ }
{ Written by: Rick Beerendonk (rick@beerendonk.com) }
{ Microloon BV }
{ The Netherlands }
{ }
{ ----------------------------------------------------------------------- }
{ THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY }
{ KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE }
{ IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A }
{ PARTICULAR PURPOSE. }
{ }
{ *********************************************************************** }
unit Borland.Examples.Delphi.RichTextBox.Find;
interface
uses
System.Data,
System.Drawing,
System.Collections,
System.ComponentModel,
System.Windows.Forms;
type
TFindForm = class(System.Windows.Forms.Form)
{$REGION 'Designer Managed Code'}
strict private
/// <summary>
/// Required designer variable.
/// </summary>
Components: System.ComponentModel.Container;
FindButton: System.Windows.Forms.Button;
CancelButton: System.Windows.Forms.Button;
FindTextBox: System.Windows.Forms.TextBox;
FindLabel: System.Windows.Forms.Label;
MatchCaseCheckBox: System.Windows.Forms.CheckBox;
ReverseCheckBox: System.Windows.Forms.CheckBox;
MatchWholeWordOnlyCheckBox: System.Windows.Forms.CheckBox;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure InitializeComponent;
private
function GetSearchText: string;
procedure SetSearchText(const Value: string);
function GetSearchOptions: RichTextBoxFinds;
procedure SetSearchOptions(const Value: RichTextBoxFinds);
{$ENDREGION}
strict protected
/// <summary>
/// Clean up any resources being used.
/// </summary>
procedure Dispose(Disposing: Boolean); override;
public
constructor Create;
property SearchOptions: RichTextBoxFinds read GetSearchOptions write SetSearchOptions;
property SearchText: string read GetSearchText write SetSearchText;
end;
[assembly: RuntimeRequiredAttribute(TypeOf(TFindForm))]
implementation
{$REGION 'Windows Form Designer generated code'}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
procedure TFindForm.InitializeComponent;
begin
Self.FindButton := System.Windows.Forms.Button.Create;
Self.CancelButton := System.Windows.Forms.Button.Create;
Self.FindTextBox := System.Windows.Forms.TextBox.Create;
Self.FindLabel := System.Windows.Forms.Label.Create;
Self.MatchCaseCheckBox := System.Windows.Forms.CheckBox.Create;
Self.ReverseCheckBox := System.Windows.Forms.CheckBox.Create;
Self.MatchWholeWordOnlyCheckBox := System.Windows.Forms.CheckBox.Create;
Self.SuspendLayout;
//
// FindButton
//
Self.FindButton.Anchor := (System.Windows.Forms.AnchorStyles((System.Windows.Forms.AnchorStyles.Bottom
or System.Windows.Forms.AnchorStyles.Right)));
Self.FindButton.DialogResult := System.Windows.Forms.DialogResult.OK;
Self.FindButton.Location := System.Drawing.Point.Create(152, 128);
Self.FindButton.Name := 'FindButton';
Self.FindButton.TabIndex := 5;
Self.FindButton.Text := 'Find';
//
// CancelButton
//
Self.CancelButton.Anchor := (System.Windows.Forms.AnchorStyles((System.Windows.Forms.AnchorStyles.Bottom
or System.Windows.Forms.AnchorStyles.Right)));
Self.CancelButton.DialogResult := System.Windows.Forms.DialogResult.Cancel;
Self.CancelButton.Location := System.Drawing.Point.Create(240, 128);
Self.CancelButton.Name := 'CancelButton';
Self.CancelButton.TabIndex := 6;
Self.CancelButton.Text := 'Cancel';
//
// FindTextBox
//
Self.FindTextBox.Anchor := (System.Windows.Forms.AnchorStyles(((System.Windows.Forms.AnchorStyles.Top
or System.Windows.Forms.AnchorStyles.Left) or System.Windows.Forms.AnchorStyles.Right)));
Self.FindTextBox.Location := System.Drawing.Point.Create(72, 16);
Self.FindTextBox.Name := 'FindTextBox';
Self.FindTextBox.Size := System.Drawing.Size.Create(240, 20);
Self.FindTextBox.TabIndex := 1;
Self.FindTextBox.Text := '';
//
// FindLabel
//
Self.FindLabel.Location := System.Drawing.Point.Create(8, 16);
Self.FindLabel.Name := 'FindLabel';
Self.FindLabel.Size := System.Drawing.Size.Create(64, 20);
Self.FindLabel.TabIndex := 0;
Self.FindLabel.Text := 'Fi&nd what:';
Self.FindLabel.TextAlign := System.Drawing.ContentAlignment.MiddleLeft;
//
// MatchCaseCheckBox
//
Self.MatchCaseCheckBox.Location := System.Drawing.Point.Create(72, 48);
Self.MatchCaseCheckBox.Name := 'MatchCaseCheckBox';
Self.MatchCaseCheckBox.Size := System.Drawing.Size.Create(184, 24);
Self.MatchCaseCheckBox.TabIndex := 2;
Self.MatchCaseCheckBox.Text := 'Match &case';
//
// ReverseCheckBox
//
Self.ReverseCheckBox.Location := System.Drawing.Point.Create(72, 96);
Self.ReverseCheckBox.Name := 'ReverseCheckBox';
Self.ReverseCheckBox.Size := System.Drawing.Size.Create(184, 24);
Self.ReverseCheckBox.TabIndex := 3;
Self.ReverseCheckBox.Text := '&Reverse';
//
// MatchWholeWordOnlyCheckBox
//
Self.MatchWholeWordOnlyCheckBox.Location := System.Drawing.Point.Create(72, 72);
Self.MatchWholeWordOnlyCheckBox.Name := 'MatchWholeWordOnlyCheckBox';
Self.MatchWholeWordOnlyCheckBox.Size := System.Drawing.Size.Create(184, 24);
Self.MatchWholeWordOnlyCheckBox.TabIndex := 4;
Self.MatchWholeWordOnlyCheckBox.Text := 'Match &whole word only';
//
// TFindForm
//
Self.AcceptButton := Self.FindButton;
Self.AutoScaleBaseSize := System.Drawing.Size.Create(5, 13);
Self.ClientSize := System.Drawing.Size.Create(322, 160);
Self.ControlBox := False;
Self.Controls.Add(Self.MatchWholeWordOnlyCheckBox);
Self.Controls.Add(Self.ReverseCheckBox);
Self.Controls.Add(Self.MatchCaseCheckBox);
Self.Controls.Add(Self.FindLabel);
Self.Controls.Add(Self.FindTextBox);
Self.Controls.Add(Self.CancelButton);
Self.Controls.Add(Self.FindButton);
Self.FormBorderStyle := System.Windows.Forms.FormBorderStyle.FixedDialog;
Self.MaximizeBox := False;
Self.MinimizeBox := False;
Self.Name := 'TFindForm';
Self.ShowInTaskbar := False;
Self.StartPosition := System.Windows.Forms.FormStartPosition.CenterParent;
Self.Text := 'Find';
Self.ResumeLayout(False);
end;
{$ENDREGION}
procedure TFindForm.Dispose(Disposing: Boolean);
begin
if Disposing then
begin
if Components <> nil then
Components.Dispose();
end;
inherited Dispose(Disposing);
end;
constructor TFindForm.Create;
begin
inherited Create;
//
// Required for Windows Form Designer support
//
InitializeComponent;
//
// TODO: Add any constructor code after InitializeComponent call
//
end;
function TFindForm.GetSearchText: string;
begin
Result := FindTextBox.Text;
end;
procedure TFindForm.SetSearchText(const Value: string);
begin
FindTextBox.Text := Value;
end;
function TFindForm.GetSearchOptions: RichTextBoxFinds;
begin
Result := System.Windows.Forms.RichTextBoxFinds.None;
if MatchCaseCheckBox.Checked then
Result := Result or System.Windows.Forms.RichTextBoxFinds.MatchCase;
if ReverseCheckBox.Checked then
Result := Result or System.Windows.Forms.RichTextBoxFinds.Reverse;
if MatchWholeWordOnlyCheckBox.Checked then
Result := Result or System.Windows.Forms.RichTextBoxFinds.WholeWord;
end;
procedure TFindForm.SetSearchOptions(const Value: RichTextBoxFinds);
begin
MatchCaseCheckBox.Checked := (Value and RichTextBoxFinds.MatchCase) <> RichTextBoxFinds.None;
ReverseCheckBox.Checked := (Value and RichTextBoxFinds.Reverse) <> RichTextBoxFinds.None;
MatchWholeWordOnlyCheckBox.Checked := (Value and RichTextBoxFinds.WholeWord) <> RichTextBoxFinds.None;
end;
end.
|
unit datetime_test_1;
interface
implementation
uses VM_System, VM_SysUtils, VM_DateUtils;
type
TCalcResult = (CalcSuccess, CalcExpireDate, CalcNotEnoughMoney);
var
R: TCalcResult;
DT, NDT: TDateTime;
procedure Test;
begin
DT := Now();
NDT := Now();
if DT > NDT then
R := CalcSuccess
else
R := CalcExpireDate;
end;
initialization
Test();
finalization
Assert(R = CalcExpireDate);
end. |
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Vcl.WinXPickers;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.Generics.Collections,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.ExtCtrls,
Vcl.Forms;
const
DefaultPickerWidth = 150;
DefaultPickerHeight = 32;
DefaultPickerDropDownCount = 7;
DefaultPickerHotColor = clBtnHighlight;
DefaultPickerHighlightColor = clBtnFace;
DefaultPickerSelectionColor = clHighlight;
DefaultPickerSelectionFontColor = clHighlightText;
type
TPickerPopupControl = class;
TPickerCellDrawInfo = class;
TBasePickerControl = class;
/// <summary>
/// TDrawPickerCellEvent represents the method type used for cell draw events in picker based controls.
/// </summary>
TDrawPickerCellEvent = procedure(Sender: TObject; PickerCellDrawInfo: TPickerCellDrawInfo) of object;
TPickerButtonState = (pbsNone, pbsHot, pbsPressed);
TPickerButtonType = (pbtNone, pbtUp, pbtDown, pbtOk, pbtCancel);
TMinuteIncrement = 1 .. 30;
/// <summary>
/// Support class used to represent a scroll button in a picker column.
/// </summary>
TPickerButton = class
strict private
FBoundsRect: TRect;
FButtonType: TPickerButtonType;
FState: TPickerButtonState;
public
property BoundsRect: TRect read FBoundsRect write FBoundsRect;
property ButtonType: TPickerButtonType read FButtonType write FButtonType;
property State: TPickerButtonState read FState write FState;
end;
/// <summary>
/// Abstract class that represents a data column in a picker-based control.
/// </summary>
TPickerColumn = class abstract
strict private
FBounds: TRect;
FDownButton: TPickerButton;
FDrawOffset: Integer;
FDropDownBounds: TRect;
FUpButton: TPickerButton;
procedure SetDrawOffset(Value: Integer);
strict protected
function GetCurrentValue: Integer; virtual; abstract;
procedure SetCurrentValue(Value: Integer); virtual; abstract;
public
constructor Create; virtual;
destructor Destroy; override;
function CalcNextValue(Value: Integer; out NewNextValue: Integer; Delta: Integer): Integer; virtual;
function GetCyclicValue(Value: Integer): Integer; virtual;
function GetMaxValue: Integer; virtual; abstract;
function GetMinSize(Canvas: TCanvas; Font: TFont): TSize; virtual;
function GetMinValue: Integer; virtual; abstract;
function GetValueString(Value: Integer): string; virtual;
function IsCyclic: Boolean; virtual;
function LimitValue(Value: Integer): Integer; virtual;
function NextValue(Value: Integer; out NextValue: Integer): Boolean; virtual;
function PreviousValue(Value: Integer; out PrevValue: Integer): Boolean; virtual;
property Bounds: TRect read FBounds write FBounds;
property CurrentValue: Integer read GetCurrentValue write SetCurrentValue;
property DownButton: TPickerButton read FDownButton write FDownButton;
property DrawOffset: Integer read FDrawOffset write SetDrawOffset;
property DropDownBounds: TRect read FDropDownBounds write FDropDownBounds;
property UpButton: TPickerButton read FUpButton write FUpButton;
end;
TPickerColumnClass = class of TPickerColumn;
IDateProvider = interface
['{DA63E195-F908-471E-84A7-471D47430EC7}']
function GetDate: TDate;
function GetMaxYear: Integer;
function GetMinYear: Integer;
procedure SetDate(Value: TDate);
procedure SetMaxYear(Value: Integer);
procedure SetMinYear(Value: Integer);
property Date: TDate read GetDate write SetDate;
property MaxYear: Integer read GetMaxYear write SetMaxYear;
property MinYear: Integer read GetMinYear write SetMinYear;
end;
ITimeProvider = interface
['{F73D637B-8A48-49EF-9D5A-51B4C8E933F4}']
function GetMinutesIncrement: TMinuteIncrement;
function GetTime: TTime;
function GetUseAmPm: Boolean;
procedure SetMinutesIncrement(Value: TMinuteIncrement);
procedure SetTime(Value: TTime);
procedure SetUseAmPm(Value: Boolean);
property MinutesIncrement: TMinuteIncrement read GetMinutesIncrement write SetMinutesIncrement;
property Time: TTime read GetTime write SetTime;
property UseAmPm: Boolean read GetUseAmPm write SetUseAmPm;
end;
TDateProvider = class(TInterfacedObject, IDateProvider)
strict private
FDate: TDate;
FMaxYear: Integer;
FMinYear: Integer;
function GetDate: TDate;
function GetMaxYear: Integer;
function GetMinYear: Integer;
procedure SetDate(Value: TDate);
procedure SetMaxYear(Value: Integer);
procedure SetMinYear(Value: Integer);
public
property Date: TDate read GetDate write SetDate;
property MaxYear: Integer read GetMaxYear write SetMaxYear;
property MinYear: Integer read GetMinYear write SetMinYear;
end;
TTimeProvider = class(TInterfacedObject, ITimeProvider)
strict private
FMinutesIncrement: TMinuteIncrement;
FTime: TTime;
FUseAmPm: Boolean;
function GetMinutesIncrement: TMinuteIncrement;
function GetTime: TTime;
function GetUseAmPm: Boolean;
procedure SetMinutesIncrement(Value: TMinuteIncrement);
procedure SetTime(Value: TTime);
procedure SetUseAmPm(Value: Boolean);
public
property MinutesIncrement: TMinuteIncrement read GetMinutesIncrement write SetMinutesIncrement;
property Time: TTime read GetTime write SetTime;
property UseAmPm: Boolean read GetUseAmPm write SetUseAmPm;
end;
/// <summary>
/// Base class for date-related picker columns.
/// </summary>
TDateColumn = class(TPickerColumn)
strict private
FDateProvider: IDateProvider;
function GetActualDate: TDate;
procedure SetActualDate(Value: TDate);
public
constructor Create(const DateProvider: IDateProvider); reintroduce; virtual;
property ActualDate: TDate read GetActualDate write SetActualDate;
property DateProvider: IDateProvider read FDateProvider;
end;
/// <summary>
/// TPickerColumn descendant for handling the month portion of a date.
/// </summary>
TPickerMonthColumn = class(TDateColumn)
strict private
FMonthFormat: string;
strict protected
function GetCurrentValue: Integer; override;
procedure SetCurrentValue(Value: Integer); override;
public
function GetMaxValue: Integer; override;
function GetMinValue: Integer; override;
function GetValueString(Value: Integer): string; override;
property MonthFormat: string read FMonthFormat write FMonthFormat;
end;
/// <summary>
/// TPickerColumn descendant for handling the day portion of a date.
/// </summary>
TPickerDayColumn = class(TDateColumn)
strict private
FDaysFormat: string;
strict protected
function GetCurrentValue: Integer; override;
procedure SetCurrentValue(Value: Integer); override;
public
function GetMaxValue: Integer; override;
function GetMinValue: Integer; override;
function GetValueString(Value: Integer): string; override;
property DaysFormat: string read FDaysFormat write FDaysFormat;
end;
/// <summary>
/// TPickerColumn descendant for handling the year portion of a date.
/// </summary>
TPickerYearColumn = class(TDateColumn)
strict private
FYearFormat: string;
strict protected
function GetCurrentValue: Integer; override;
procedure SetCurrentValue(Value: Integer); override;
public
function GetMaxValue: Integer; override;
function GetMinValue: Integer; override;
function GetValueString(Value: Integer): string; override;
function IsCyclic: Boolean; override;
property YearFormat: string read FYearFormat write FYearFormat;
end;
/// <summary>
/// Base class for time-related picker columns.
/// </summary>
TTimeColumn = class(TPickerColumn)
strict private
FTimeProvider: ITimeProvider;
function GetActualTime: TTime;
procedure SetActualTime(Value: TTime);
public
constructor Create(const TimeProvider: ITimeProvider); reintroduce; virtual;
property ActualTime: TTime read GetActualTime write SetActualTime;
property TimeProvider: ITimeProvider read FTimeProvider;
end;
/// <summary>
/// TPickerColumn descendant for handling the hour portion of a time.
/// </summary>
TPickerHourColumn = class(TTimeColumn)
strict private
FHourFormat: string;
procedure SetHourFormat(const Value: string);
strict protected
function GetCurrentValue: Integer; override;
procedure SetCurrentValue(Value: Integer); override;
public
function GetMaxValue: Integer; override;
function GetMinValue: Integer; override;
function GetValueString(Value: Integer): string; override;
property HourFormat: string read FHourFormat write SetHourFormat;
end;
/// <summary>
/// TPickerColumn descendant for handling the minute portion of a time.
/// </summary>
TPickerMinuteColumn = class(TTimeColumn)
strict private
FMinuteFormat: string;
procedure SetMinuteFormat(const Value: string);
strict protected
function GetCurrentValue: Integer; override;
procedure SetCurrentValue(Value: Integer); override;
public
function GetMaxValue: Integer; override;
function GetMinValue: Integer; override;
function GetValueString(Value: Integer): string; override;
function NextValue(Value: Integer; out NextValue: Integer): Boolean; override;
function PreviousValue(Value: Integer; out PrevValue: Integer): Boolean; override;
property MinuteFormat: string read FMinuteFormat write SetMinuteFormat;
end;
/// <summary>
/// TPickerColumn descendant for handling the second portion of a time.
/// </summary>
TPickerSecondColumn = class(TTimeColumn)
strict private
FSecondFormat: string;
procedure SetSecondFormat(const Value: string);
strict protected
function GetCurrentValue: Integer; override;
procedure SetCurrentValue(Value: Integer); override;
public
function GetMaxValue: Integer; override;
function GetMinValue: Integer; override;
function GetValueString(Value: Integer): string; override;
property SecondFormat: string read FSecondFormat write SetSecondFormat;
end;
/// <summary>
/// TPickerColumn descendant for handling the AM/PM portion of a time.
/// </summary>
TPickerAMPMColumn = class(TTimeColumn)
strict private
FAm: Boolean;
FAMPMFormat: string;
procedure SetAMPMFormat(const Value: string);
strict protected
function GetCurrentValue: Integer; override;
procedure SetCurrentValue(Value: Integer); override;
public
function GetMaxValue: Integer; override;
function GetMinValue: Integer; override;
function GetValueString(Value: Integer): string; override;
function IsCyclic: Boolean; override;
property AMPMFormat: string read FAMPMFormat write SetAMPMFormat;
end;
/// <summary>
/// Support class to manage visualization attributes of the picker.
/// </summary>
TPickerViewInfo = class
private
FBorderColor: TColor;
FBorderSize: Integer;
FColor: TColor;
FDropDownCount: Integer;
FFont: TFont;
FHighlightColor: TColor;
FItemHeight: Integer;
FShowOkCancel: Boolean;
procedure SetFont(Value: TFont);
public
constructor Create;
destructor Destroy; override;
property BorderColor: TColor read FBorderColor write FBorderColor;
property BorderSize: Integer read FBorderSize write FBorderSize;
property Color: TColor read FColor write FColor;
property DropDownCount: Integer read FDropDownCount write FDropDownCount;
property Font: TFont read FFont write SetFont;
property HighlightColor: TColor read FHighlightColor write FHighlightColor;
property ItemHeight: Integer read FItemHeight write FItemHeight;
property ShowOkCancel: Boolean read FShowOkCancel write FShowOkCancel;
end;
/// <summary>
/// Support class that represents the elements necessary to draw a picker column cell.
/// </summary>
TPickerCellDrawInfo = class
strict private
FBounds: TRect;
FColor: TColor;
FFont: TFont;
FHighlightColor: TColor;
FHighlighted: Boolean;
FText: string;
procedure SetFont(Value: TFont);
public
constructor Create;
destructor Destroy; override;
property Bounds: TRect read FBounds write FBounds;
property Color: TColor read FColor write FColor;
property Font: TFont read FFont write SetFont;
property HighlightColor: TColor read FHighlightColor write FHighlightColor;
property Highlighted: Boolean read FHighlighted write FHighlighted;
property Text: string read FText write FText;
end;
TPickerCellDrawInfoInternal = class(TPickerCellDrawInfo)
strict private
FBorderColor: TColor;
FBorderSize: Integer;
FSelected: Boolean;
public
property BorderColor: TColor read FBorderColor write FBorderColor;
property BorderSize: Integer read FBorderSize write FBorderSize;
property Selected: Boolean read FSelected write FSelected;
end;
/// <summary>
/// Support class that represents the elements necessary to draw a picker button.
/// </summary>
TPickerButtonDrawInfo = class
strict private
FBorderWidth: Integer;
FButton: TPickerButton;
FColor: TColor;
FForegroundColor: TColor;
FPenWidth: Integer;
function GetButtonType: TPickerButtonType;
public
property BorderWidth: Integer read FBorderWidth write FBorderWidth;
property Button: TPickerButton read FButton write FButton;
property ButtonType: TPickerButtonType read GetButtonType;
property Color: TColor read FColor write FColor;
property ForegroundColor: TColor read FForegroundColor write FForegroundColor;
property PenWidth: Integer read FPenWidth write FPenWidth;
end;
TPickerOkCancelButtons = class
private
FBounds: TRect;
FCancelButton: TPickerButton;
FOkButton: TPickerButton;
public
constructor Create;
destructor Destroy; override;
procedure Calculate(Rect: TRect; ItemHeight, BorderWidth: Integer);
property Bounds: TRect read FBounds write FBounds;
property CancelButton: TPickerButton read FCancelButton write FCancelButton;
property OkButton: TPickerButton read FOkButton write FOkButton;
end;
/// <summary>
/// Abstract class that defines the various methods necessary to draw a picker control.
/// </summary>
TPickerDrawer = class abstract
strict protected
FPickerControl: TBasePickerControl;
function MiddleColor(Color1, Color2: TColor; Coeff: Double = 0.5): TColor;
public
constructor Create(Picker: TBasePickerControl); virtual;
procedure DrawCell(Canvas: TCanvas; DrawInfo: TPickerCellDrawInfoInternal); virtual;
procedure DrawOkCancel(Canvas: TCanvas; Buttons: TPickerOkCancelButtons;
DrawInfo: TPickerButtonDrawInfo; BorderColor: TColor); virtual;
procedure DrawPickerBorder(Canvas: TCanvas; BorderWidth: Integer;
PickerColumn: TPickerColumn; BorderColor: TColor); virtual;
procedure DrawPickerButton(Canvas: TCanvas; DrawInfo: TPickerButtonDrawInfo); virtual;
procedure DrawPickerCell(Canvas: TCanvas; DrawInfo: TPickerCellDrawInfoInternal); virtual;
procedure DrawPickerColumn(Canvas: TCanvas; DrawRect: TRect; Color: TColor);
procedure DrawSelectedRect(Canvas: TCanvas; var DrawRect: TRect; BorderWidth: Integer);
function GetBorderColor(Hot, Pressed: Boolean): TColor; virtual;
function GetButtonColor(Hot, Pressed: Boolean): TColor; virtual;
function GetButtonFontColor(Hot, Pressed: Boolean): TColor; virtual;
function GetColor(Hot, Pressed, Enabled: Boolean): TColor; virtual;
function GetFontColor: TColor; virtual;
function GetHighlightColor: TColor; virtual;
function GetPopupColor: TColor; virtual;
function GetSelectionColor: TColor; virtual;
function GetSelectionFontColor: TColor; virtual;
end;
/// <summary>
/// TPickerDrawer descendant class that is used to draw a picker control when not using a custom VCL style.
/// </summary>
TPickerDrawerNative = class(TPickerDrawer)
end;
/// <summary>
/// TPickerDrawer descendant class that is used to draw a picker control when using a custom VCL style.
/// </summary>
TPickerDrawerStyled = class(TPickerDrawer)
public
function GetBorderColor(Hot, Pressed: Boolean): TColor; override;
function GetButtonColor(Hot, Pressed: Boolean): TColor; override;
function GetButtonFontColor(Hot, Pressed: Boolean): TColor; override;
function GetColor(Hot, Pressed, Enabled: Boolean): TColor; override;
function GetFontColor: TColor; override;
function GetHighlightColor: TColor; override;
function GetPopupColor: TColor; override;
function GetSelectionColor: TColor; override;
function GetSelectionFontColor: TColor; override;
end;
/// <summary>
/// Base class that defines basic behavior of a picker style control.
/// </summary>
TBasePickerControl = class abstract(TCustomControl)
strict private
FBorderColor: TColor;
FBorderStyle: TBorderStyle;
FDropDownCount: Integer;
FDroppedDown: Boolean;
FHighlightColor: TColor;
FHotColor: TColor;
FHot: Boolean;
FOnChange: TNotifyEvent;
FOnCloseUp: TNotifyEvent;
FOnDrawCell: TDrawPickerCellEvent;
FOnDrawPickerCell: TDrawPickerCellEvent;
FPopupColor: TColor;
FPressed: Boolean;
FSelectionColor: TColor;
FSelectionFontColor: TColor;
FShowOkCancel: Boolean;
procedure SetBorderColor(Value: TColor);
procedure SetBorderStyle(Value: TBorderStyle);
procedure SetDropDownCount(Value: Integer);
procedure SetHighlightColor(Value: TColor);
procedure SetHot(Value: Boolean);
procedure SetHotColor(Value: TColor);
procedure SetPopupColor(Value: TColor);
procedure SetPressed(Value: Boolean);
procedure SetSelectionColor(Value: TColor);
procedure SetSelectionFontColor(Value: TColor);
procedure SetShowOkCancel(Value: Boolean);
property Hot: Boolean read FHot write SetHot;
property Pressed: Boolean read FPressed write SetPressed;
procedure CMCancelMode(var Msg: TCMCancelMode); message CM_CANCELMODE;
procedure CMDialogKey(var Msg: TCMDialogKey); message CM_DIALOGKEY;
procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Msg: TMessage); message CM_MOUSELEAVE;
procedure CMStyleChanged(var Msg: TMessage); message CM_STYLECHANGED;
procedure CNKeyDown(var Msg: TMessage); message CN_KEYDOWN;
procedure WMKillFocus(var Msg: TWMKillFocus); message WM_KILLFOCUS;
procedure WMLButtonDown(var Msg: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMLButtonUp(var Msg: TWMLButtonUp); message WM_LBUTTONUP;
procedure WMSetFocus(var Msg: TWMSetFocus); message WM_SETFOCUS;
protected const
DefaultBorderColor = clBtnShadow;
DefaultPopupColor = clWindow;
DefaultFontSize = 12;
protected
FBorderSize: Integer;
FColumns: TObjectList<TPickerColumn>;
FDrawer: TPickerDrawer;
FPopupControl: TPickerPopupControl;
procedure AcceptDropDown; virtual; abstract;
procedure AdjustSize; override;
function CalcSizes(MinSize: TSize): TSize;
function CanResize(var NewWidth, NewHeight: Integer): Boolean; override;
procedure ChangeScale(M, D: Integer; isDpiChange: Boolean); override;
procedure Click; override;
function CreateDrawer: TPickerDrawer; virtual;
procedure CreateWnd; override;
procedure DefineColumns(Columns: TList<TPickerColumn>); virtual; abstract;
procedure InitColumns; virtual; abstract;
procedure InitPopup;
procedure DoDrawPickerCell(Sender: TObject; PickerCellDrawInfo: TPickerCellDrawInfo);
function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; override;
function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; override;
procedure DoOnChange;
function GetColumnByClass<T: TPickerColumn>: T;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
function NeedDrawer: TPickerDrawer;
procedure Paint; override;
procedure ParseFormat(const Format: string); virtual; abstract;
procedure RejectDropDown; virtual; abstract;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
/// <summary>
/// Call CanModify to determine if the picker control can be modified.
/// </summary>
function CanModify: Boolean; virtual;
/// <summary>
/// Use this method to close up the popup picker columns.
/// </summary>
/// <param name="Accept">
/// When True, use the currently selected column values to set the underlying data value. When False, reset the
/// underlying data value to the value before the popup was invoked.
/// </param>
procedure CloseUp(Accept: Boolean);
/// <summary>
/// Use this method to programmatically display the popup columns for the picker control.
/// </summary>
procedure DropDown;
/// <summary>
/// Specifies the color of the border.
/// </summary>
property BorderColor: TColor read FBorderColor write SetBorderColor default DefaultBorderColor;
/// <summary>
/// Specifies the style of the border: single or none.
/// </summary>
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
/// <summary>
/// Specifies the number of cells displayed in each picker column when the popup is visible.
/// </summary>
property DropDownCount: Integer read FDropDownCount write SetDropDownCount default DefaultPickerDropDownCount;
/// <summary>
/// Specifies the color used when highlighting a cell.
/// </summary>
property HighlightColor: TColor read FHighlightColor write SetHighlightColor default DefaultPickerHighlightColor;
/// <summary>
/// Specifies the background color of the cells when the control has focus or the mouse is positioned over the
/// control.
/// </summary>
property HotColor: TColor read FHotColor write SetHotColor default DefaultPickerHotColor;
/// <summary>
/// Specifies the background color of the popup panel.
/// </summary>
property PopupColor: TColor read FPopupColor write SetPopupColor default DefaultPopupColor;
/// <summary>
/// Specifies the color of the currently selected column values.
/// </summary>
property SelectionColor: TColor read FSelectionColor write SetSelectionColor default DefaultPickerSelectionColor;
/// <summary>
/// Specifies the color of the font for the currently selected column values
/// </summary>
property SelectionFontColor: TColor read FSelectionFontColor write SetSelectionFontColor default DefaultPickerSelectionFontColor;
/// <summary>
/// Specifies whether OK and Cancel buttons are visible on the popup panel.
/// </summary>
property ShowOkCancel: Boolean read FShowOkCancel write SetShowOkCancel default True;
/// <summary>
/// Occurs when the underlying data value represented by the picker control changes.
/// </summary>
property OnChange: TNotifyEvent read FOnChange write FOnChange;
/// <summary>
/// Occurs when the popup panel is closed.
/// </summary>
property OnCloseUp: TNotifyEvent read FOnCloseUp write FOnCloseUp;
/// <summary>
/// Occurs when a cell needs to be drawn and the popup panel is not visible.
/// </summary>
property OnDrawCell: TDrawPickerCellEvent read FOnDrawCell write FOnDrawCell;
/// <summary>
/// Occurs when a popup column cell needs to be drawn.
/// </summary>
property OnDrawPickerCell: TDrawPickerCellEvent read FOnDrawPickerCell write FOnDrawPickerCell;
end;
/// <summary>
/// TCustomDatePicker defines the base functionality of a date picker.
/// </summary>
TCustomDatePicker = class(TBasePickerControl)
strict private
FDate: TDate;
FDateFormat: string;
FDateProvider: IDateProvider;
function GetDate: TDate;
function GetDateFromColumns: TDate;
function GetDayVisible: Boolean;
function GetMaxYear: Integer;
function GetMinYear: Integer;
function GetMonthVisible: Boolean;
function GetYearVisible: Boolean;
procedure SetDate(Value: TDate);
procedure SetDateFormat(const Value: string);
procedure SetDateToColumns(Value: TDate);
procedure SetMaxYear(Value: Integer);
procedure SetMinYear(Value: Integer);
protected
procedure DefineColumns(Columns: TList<TPickerColumn>); override;
procedure InitColumns; override;
procedure AcceptDropDown; override;
procedure RejectDropDown; override;
procedure ParseFormat(const Format: string); override;
protected const
DefaultMinYear = 1900;
DefaultMaxYear = 3000;
public
constructor Create(AOwner: TComponent); override;
/// <summary>
/// Specifies the date value of the picker control.
/// </summary>
property Date: TDate read GetDate write SetDate;
/// <summary>
/// Specifies the format of the date elements used to define which columns are visible.
/// </summary>
property DateFormat: string read FDateFormat write SetDateFormat;
/// <summary>
/// Use this property to determine if the day date element is a visible column in the date picker.
/// </summary>
property DayVisible: Boolean read GetDayVisible;
/// <summary>
/// Specifies the maximum year that can be represented by the date picker. Default is 3000.
/// </summary>
property MaxYear: Integer read GetMaxYear write SetMaxYear default DefaultMaxYear;
/// <summary>
/// Specifies the minimum year that can be represented by the date picker. Default is 1900.
/// </summary>
property MinYear: Integer read GetMinYear write SetMinYear default DefaultMinYear;
/// <summary>
/// Use this property to determine if the month date element is a visible column in the date picker.
/// </summary>
property MonthVisible: Boolean read GetMonthVisible;
/// <summary>
/// Use this property to determine if the year date element is a visible column in the date picker.
/// </summary>
property YearVisible: Boolean read GetYearVisible;
end;
/// <summary>
/// TCustomTimePicker defines the base functionality of a time picker.
/// </summary>
TCustomTimePicker = class(TBasePickerControl)
strict private
FTime: TTime;
FTimeFormat: string;
FTimeProvider: ITimeProvider;
function GetMinuteIncrement: TMinuteIncrement;
function GetTimeFromColumns: TTime;
procedure SetMinuteIncrement(Value: TMinuteIncrement);
procedure SetTime(Value: TTime);
procedure SetTimeFormat(const Value: string);
procedure SetTimeToColumns(Value: TTime);
protected
procedure DefineColumns(Columns: TList<TPickerColumn>); override;
procedure InitColumns; override;
procedure AcceptDropDown; override;
procedure RejectDropDown; override;
procedure ParseFormat(const Format: string); override;
public
constructor Create(AOwner: TComponent); override;
/// <summary>
/// Specifies the granularity of minute values available in the minute column when the popup panel is visible.
/// </summary>
property MinuteIncrement: TMinuteIncrement read GetMinuteIncrement write SetMinuteIncrement default 1;
/// <summary>
/// Specifies the time value of the picker control.
/// </summary>
property Time: TTime read FTime write SetTime;
/// <summary>
/// Specifies the format of the time elements used to define which columns are visible.
/// </summary>
property TimeFormat: string read FTimeFormat write SetTimeFormat;
end;
/// <summary>
/// TDatePicker is a picker style control that allows the user to specify a date. Each element of the date (day,
/// month, year) is selected using a popup scrolling list of values appropriate for the date element.
/// </summary>
TDatePicker = class(TCustomDatePicker)
published
property Align;
property Anchors;
property BorderStyle;
property Color default clWindow;
property Date;
property DateFormat;
property DropDownCount;
property Enabled;
property Font;
property Height default DefaultPickerHeight;
property HighlightColor;
property MaxYear;
property MinYear;
property PopupColor;
property PopupMenu;
property SelectionColor;
property SelectionFontColor;
property ShowHint;
property ShowOkCancel;
property StyleElements;
property TabOrder;
property TabStop default True;
property Width default DefaultPickerWidth;
property OnChange;
property OnClick;
property OnCloseUp;
property OnDblClick;
property OnDrawCell;
property OnDrawPickerCell;
end;
/// <summary>
/// TTimePicker is a picker style control that allows the user to specify a time. Each element of the time (hour,
/// minute, second, am/pm) is selected using a popup scrolling list of values appropriate for the time element.
/// </summary>
TTimePicker = class(TCustomTimePicker)
published
property Align;
property Anchors;
property BorderStyle;
property Color default clWindow;
property DropDownCount;
property Enabled;
property Font;
property Height default DefaultPickerHeight;
property HighlightColor;
property MinuteIncrement;
property PopupColor;
property PopupMenu;
property SelectionColor;
property SelectionFontColor;
property ShowHint;
property ShowOkCancel;
property StyleElements;
property TabOrder;
property TabStop default True;
property Time;
property TimeFormat;
property Width default DefaultPickerWidth;
property OnChange;
property OnClick;
property OnCloseUp;
property OnDblClick;
property OnDrawCell;
property OnDrawPickerCell;
end;
TBasePickerAnimation = class
strict private
FDuration: Cardinal;
FInterval: Cardinal;
FIsStarted: Boolean;
FOnFinished: TNotifyEvent;
FOnStarted: TNotifyEvent;
FTimer: TTimer;
FWhenStarted: Cardinal;
procedure TimerTick(Sender: TObject);
strict protected
procedure Animate(Current: Cardinal); virtual; abstract;
procedure DoOnFinish; virtual;
procedure DoPrepare; virtual;
public
destructor Destroy; override;
procedure Finish;
procedure Start(Duration, Interval: Cardinal);
procedure StartDefault;
property Duration: Cardinal read FDuration write FDuration;
property Interval: Cardinal read FInterval write FInterval;
property IsStarted: Boolean read FIsStarted write FIsStarted;
property WhenStarted: Cardinal read FWhenStarted;
property OnFinished: TNotifyEvent read FOnFinished write FOnFinished;
property OnStarted: TNotifyEvent read FOnStarted write FOnStarted;
end;
TPickerSlideAnimation = class(TBasePickerAnimation)
strict private
FCoef: Double;
FColumn: TPickerColumn;
FControl: TPickerPopupControl;
FDelta: Integer;
FNextValue: Integer;
strict protected
procedure Animate(Current: Cardinal); override;
procedure DoOnFinish; override;
procedure DoPrepare; override;
public
property Column: TPickerColumn read FColumn write FColumn;
property Control: TPickerPopupControl read FControl write FControl;
property Delta: Integer read FDelta write FDelta;
property NextValue: Integer read FNextValue write FNextValue;
end;
/// <summary>
/// Support class that is used to manage the showing and hiding of the popup picker columns associated with a
/// picker control.
/// </summary>
TPickerPopupControl = class(TCustomControl)
private
FAnimation: TBasePickerAnimation;
FBorderColor: TColor;
FBorderSize: Integer;
FColumns: TArray<TPickerColumn>;
FDrawer: TPickerDrawer;
FDropDownCount: Integer;
FHighlightColor: TColor;
FHotColor: TColor;
FItemHeight: Integer;
FMouseOver: Integer;
FMouseOverPoint: TPoint;
FMouseOverValue: Integer;
FOkCancelButtons: TPickerOkCancelButtons;
FOnDrawCell: TDrawPickerCellEvent;
FParentOwner: TWinControl;
FSelectionColor: TColor;
FSelectionFontColor: TColor;
FSelectRect: TRect;
FShowOkCancel: Boolean;
procedure AnimateColumnValueChanged(Column: TPickerColumn; NextValue, Delta: Integer);
procedure Calculate;
function GetCellValueByMousePos(Point: TPoint; out ResultValue, ResultDelta: Integer): Boolean;
function GetColumnByMousePos(Point: TPoint): TPickerColumn;
procedure SetBorderColor(Value: TColor);
procedure SetDropDownCount(Value: Integer);
procedure SetHighlightColor(Value: TColor);
procedure SetHotColor(Value: TColor);
procedure SetMouseOver(Value: Integer);
procedure SetMouseOverPoint(Value: TPoint);
procedure SetMouseOverValue(Value: Integer);
procedure SetSelectionColor(Value: TColor);
procedure SetSelectionFontColor(Value: TColor);
procedure SetShowOkCancel(Value: Boolean);
procedure UpdateHoverItems(Point: TPoint);
procedure CMMouseActivate(var Msg: TCMMouseActivate); message CM_MOUSEACTIVATE;
procedure CMMouseLeave(var Msg: TMessage); message CM_MOUSELEAVE;
procedure CNKeyDown(var Msg: TWMKeyDown); message CN_KEYDOWN;
procedure WMGetDlgCode(var Msg: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMLButtonDown(var Msg: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMLButtonUp(var Msg: TWMLButtonUp); message WM_LBUTTONUP;
protected const
ArrowWidth = 2;
ScrollButtonHeight = 16;
protected
procedure DoDrawCell(Sender: TObject; PickerCellDrawInfo: TPickerCellDrawInfo);
function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; override;
function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure Paint; override;
procedure PaintCell(Canvas: TCanvas; Rect: TRect; const Text: string;
Drawer: TPickerDrawer; Highlighted, Selected: Boolean); virtual;
procedure PaintColumn(Canvas: TCanvas; Column: TPickerColumn;
Drawer: TPickerDrawer; ColumnIndex: Integer); overload; virtual;
procedure PaintColumn(Column: TPickerColumn; Drawer: TPickerDrawer;
ColumnIndex: Integer); overload; virtual;
procedure PaintOkCancel(Canvas: TCanvas; Drawer: TPickerDrawer); virtual;
property MouseOver: Integer read FMouseOver write SetMouseOver;
property MouseOverPoint: TPoint read FMouseOverPoint write SetMouseOverPoint;
property MouseOverValue: Integer read FMouseOverValue write SetMouseOverValue;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AnimationFinished(Sender: TObject);
procedure CreateParams(var Params: TCreateParams); override;
procedure Init(ParentOwner: TWinControl; Columns: TList<TPickerColumn>;
ViewInfo: TPickerViewInfo; OnDrawEvent: TDrawPickerCellEvent; Drawer: TPickerDrawer);
procedure PaintColumns(const Canvas: TCanvas; const Drawer: TPickerDrawer);
property BorderColor: TColor read FBorderColor write SetBorderColor;
property DropDownCount: Integer read FDropDownCount write SetDropDownCount default DefaultPickerDropDownCount;
property HighlightColor: TColor read FHighlightColor write SetHighlightColor default DefaultPickerHighlightColor;
property HotColor: TColor read FHotColor write SetHotColor default DefaultPickerHotColor;
property SelectionColor: TColor read FSelectionColor write SetSelectionColor default DefaultPickerSelectionColor;
property SelectionFontColor: TColor read FSelectionFontColor write SetSelectionFontColor default DefaultPickerSelectionFontColor;
property ShowOkCancel: Boolean read FShowOkCancel write SetShowOkCancel;
property OnDrawCell: TDrawPickerCellEvent read FOnDrawCell write FOnDrawCell;
end;
implementation
uses
System.SysUtils,
System.Math,
System.DateUtils,
System.Types,
System.UIConsts,
Vcl.Themes,
Vcl.Styles,
System.RegularExpressions;
{$WARN IMPLICIT_INTEGER_CAST_LOSS OFF}
{$WARN IMPLICIT_CONVERSION_LOSS OFF}
{ TPickerColumn }
constructor TPickerColumn.Create;
begin
inherited;
FUpButton := TPickerButton.Create;
FUpButton.ButtonType := pbtUp;
FDownButton := TPickerButton.Create;
FDownButton.ButtonType := pbtDown;
end;
destructor TPickerColumn.Destroy;
begin
FreeAndNil(FUpButton);
FreeAndNil(FDownButton);
inherited;
end;
function TPickerColumn.CalcNextValue(Value: Integer; out NewNextValue: Integer; Delta: Integer): Integer;
begin
Result := 0;
NewNextValue := Value;
while Delta <> 0 do
begin
if Delta < 0 then
begin
if not PreviousValue(NewNextValue, NewNextValue) then
Exit;
Inc(Delta);
Dec(Result);
end
else
begin
if not NextValue(NewNextValue, NewNextValue) then
Exit;
Dec(Delta);
Inc(Result);
end;
end;
end;
function TPickerColumn.GetCyclicValue(Value: Integer): Integer;
var
RangeSize, ModValue: Integer;
begin
RangeSize := (GetMaxValue - GetMinValue) + 1;
ModValue := (Value - GetMinValue) mod RangeSize;
if ModValue < 0 then
ModValue := RangeSize + ModValue;
Result := ModValue + GetMinValue;
end;
function TPickerColumn.GetMinSize(Canvas: TCanvas; Font: TFont): TSize;
var
Str: string;
MinRect: TRect;
Delta: Integer;
begin
Str := GetValueString(GetMaxValue);
MinRect := Rect(0, 0, 10, 10);
DrawText(Canvas.Handle, PChar(Str), Str.Length, MinRect, DT_CALCRECT);
Delta := MinRect.Height div 3;
InflateRect(MinRect, Delta, Delta);
Result := MinRect.Size;
end;
function TPickerColumn.GetValueString(Value: Integer): string;
begin
Result := IntToStr(Value);
end;
function TPickerColumn.IsCyclic: Boolean;
begin
Result := True;
end;
function TPickerColumn.LimitValue(Value: Integer): Integer;
begin
Result := Min(GetMaxValue, Max(GetMinValue, Value));
end;
function TPickerColumn.NextValue(Value: Integer; out NextValue: Integer): Boolean;
begin
Result := True;
if Value >= GetMaxValue then
begin
if IsCyclic then
NextValue := GetMinValue
else
Result := False;
end
else
NextValue := Value + 1;
end;
function TPickerColumn.PreviousValue(Value: Integer; out PrevValue: Integer): Boolean;
begin
Result := True;
if Value <= GetMinValue then
begin
if IsCyclic then
PrevValue := GetMaxValue
else
Result := False;
end
else
PrevValue := Value - 1;
end;
procedure TPickerColumn.SetDrawOffset(Value: Integer);
begin
FDrawOffset := Value;
end;
{ TPickerMonthColumn }
function TPickerMonthColumn.GetCurrentValue: Integer;
begin
Result := MonthOf(ActualDate);
end;
function TPickerMonthColumn.GetMaxValue: Integer;
begin
Result := 12;
end;
function TPickerMonthColumn.GetMinValue: Integer;
begin
Result := 1;
end;
function TPickerMonthColumn.GetValueString(Value: Integer): string;
begin
Result := FormatDateTime(MonthFormat, EncodeDate(1901, Value, 1));
end;
procedure TPickerMonthColumn.SetCurrentValue(Value: Integer);
var
Year, Month, Day, MaxDays: Word;
begin
DecodeDate(ActualDate, Year, Month, Day);
MaxDays := DaysInMonth(EncodeDate(Year, Value, 1));
if Day > MaxDays then
Day := MaxDays;
ActualDate := EncodeDate(Year, Value, Day);
end;
{ TPickerDrawer }
constructor TPickerDrawer.Create(Picker: TBasePickerControl);
begin
inherited Create;
FPickerControl := Picker;
end;
procedure TPickerDrawer.DrawCell(Canvas: TCanvas; DrawInfo: TPickerCellDrawInfoInternal);
var
DrawRect: TRect;
Text: string;
begin
DrawRect := DrawInfo.Bounds;
Text := DrawInfo.Text;
Canvas.Brush.Style := bsClear;
Canvas.Font.Assign(DrawInfo.Font);
DrawRect.Inflate(-DrawInfo.BorderSize, -DrawInfo.BorderSize);
if not DrawInfo.Selected then
begin
if DrawInfo.Highlighted then
Canvas.Brush.Color := DrawInfo.HighlightColor
else
Canvas.Brush.Color := DrawInfo.Color;
Canvas.Brush.Style := bsSolid;
Canvas.FillRect(DrawInfo.Bounds);
end
else
Canvas.Font.Color := GetSelectionFontColor;
Canvas.TextRect(DrawRect, Text, [tfCenter, tfVerticalCenter, tfSingleLine]);
end;
procedure TPickerDrawer.DrawOkCancel(Canvas: TCanvas; Buttons: TPickerOkCancelButtons;
DrawInfo: TPickerButtonDrawInfo; BorderColor: TColor);
var
DrawButtonInfo: TPickerButtonDrawInfo;
begin
Canvas.Brush.Color := DrawInfo.Color;
Canvas.Pen.Width := DrawInfo.BorderWidth;
Canvas.Pen.Color := BorderColor;
Canvas.Pen.Style := psInsideFrame;
Canvas.Rectangle(Buttons.Bounds);
DrawButtonInfo := TPickerButtonDrawInfo.Create;
try
DrawButtonInfo.Button := Buttons.OkButton;
DrawButtonInfo.BorderWidth := DrawInfo.BorderWidth;
DrawButtonInfo.Color := DrawInfo.Color;
DrawButtonInfo.ForegroundColor := DrawInfo.ForegroundColor;
DrawButtonInfo.PenWidth := DrawInfo.PenWidth;
DrawPickerButton(Canvas, DrawButtonInfo);
DrawButtonInfo.Button := Buttons.CancelButton;
DrawPickerButton(Canvas, DrawButtonInfo);
finally
FreeAndNil(DrawButtonInfo);
end;
end;
procedure TPickerDrawer.DrawPickerBorder(Canvas: TCanvas; BorderWidth: Integer;
PickerColumn: TPickerColumn; BorderColor: TColor);
var
DrawRect: TRect;
begin
DrawRect := PickerColumn.DropDownBounds;
if BorderWidth <> 0 then
begin
Canvas.Pen.Style := psInsideFrame;
Canvas.Pen.Color := BorderColor;
Canvas.Pen.Width := BorderWidth;
Canvas.Brush.Style := bsClear;
Canvas.Rectangle(DrawRect);
DrawRect.Inflate(-BorderWidth, -BorderWidth);
end;
end;
procedure TPickerDrawer.DrawPickerButton(Canvas: TCanvas; DrawInfo: TPickerButtonDrawInfo);
procedure DrawArrow(const DrawRect: TRect; Up: Boolean);
var
Points: array [0 .. 2] of TPoint;
TriangleHeight, TriangleWidth, TriangleBotton, TriangleTop: Integer;
begin
TriangleHeight := DrawRect.Height div 2;
TriangleWidth := TriangleHeight * 2;
TriangleBotton := (DrawRect.Height - TriangleHeight) div 2 + DrawRect.Top +
TriangleHeight;
TriangleTop := (DrawRect.Height - TriangleHeight) div 2 + DrawRect.Top;
if Up then
begin
Points[0] := Point(DrawRect.Left, TriangleBotton);
Points[1] := Point(DrawRect.Left + TriangleHeight,
(DrawRect.Height - TriangleHeight) div 2 + DrawRect.Top);
Points[2] := Point(DrawRect.Left + TriangleWidth, TriangleBotton);
end
else
begin
Points[0] := Point(DrawRect.Left, TriangleTop);
Points[1] := Point(DrawRect.Left + TriangleHeight,
(DrawRect.Height - TriangleHeight) div 2 + DrawRect.Top +
TriangleHeight);
Points[2] := Point(DrawRect.Left + TriangleWidth, TriangleTop);
end;
Canvas.Polyline(Points);
end;
procedure DrawOk(const DrawRect: TRect);
var
Points: array [0 .. 2] of TPoint;
CheckHeight, CheckWidth, CheckTop: Integer;
begin
Canvas.Pen.Width := DrawInfo.PenWidth;
CheckHeight := DrawRect.Height div 2;
CheckWidth := CheckHeight * 2;
CheckTop := (DrawRect.Height - CheckHeight) div 2 + DrawRect.Top;
Points[0] := Point(DrawRect.Left + (CheckHeight div 3) * 2,
CheckTop + (CheckHeight div 3) * 2);
Points[1] := Point(DrawRect.Left + CheckHeight,
(DrawRect.Height - CheckHeight) div 2 + DrawRect.Top + CheckHeight);
Points[2] := Point(DrawRect.Left + CheckWidth, CheckTop);
Canvas.Polyline(Points);
end;
procedure DrawCancel(const DrawRect: TRect);
var
XHeight: Integer;
begin
Canvas.Pen.Width := DrawInfo.PenWidth;
XHeight := (DrawRect.Height div 4);
DrawRect.Inflate(-XHeight, -XHeight);
Canvas.MoveTo(DrawRect.Left, DrawRect.Top);
Canvas.LineTo(DrawRect.Right, DrawRect.Bottom);
Canvas.MoveTo(DrawRect.Right, DrawRect.Top);
Canvas.LineTo(DrawRect.Left, DrawRect.Bottom);
end;
var
ButtonRect, ArrowRect: TRect;
RectHeigth: Integer;
begin
ButtonRect := DrawInfo.Button.BoundsRect;
RectHeigth := ButtonRect.Height;
Canvas.Brush.Color := GetButtonColor(DrawInfo.Button.State = pbsHot, DrawInfo.Button.State = pbsPressed);
Canvas.FillRect(ButtonRect);
Canvas.Pen.Width := DrawInfo.PenWidth;
Canvas.Pen.Color := GetButtonFontColor(DrawInfo.Button.State = pbsHot, DrawInfo.Button.State = pbsPressed);
ArrowRect := ButtonRect;
ArrowRect.Inflate(-(ButtonRect.Width - RectHeigth) div 2, 0);
if ArrowRect.Width > ArrowRect.Height then
ArrowRect.Inflate(-(ArrowRect.Width - ArrowRect.Height) div 2, 0)
else
ArrowRect.Inflate(0, -(ArrowRect.Height - ArrowRect.Width) div 2);
if ArrowRect.Height <> ArrowRect.Width then
ArrowRect.Width := ArrowRect.Height;
case DrawInfo.ButtonType of
pbtUp:
DrawArrow(ArrowRect, True);
pbtDown:
DrawArrow(ArrowRect, False);
pbtOk:
DrawOk(ArrowRect);
pbtCancel:
DrawCancel(ArrowRect);
end;
end;
procedure TPickerDrawer.DrawPickerCell(Canvas: TCanvas; DrawInfo: TPickerCellDrawInfoInternal);
var
DrawRect: TRect;
Text: string;
begin
DrawRect := DrawInfo.Bounds;
Canvas.Pen.Width := DrawInfo.BorderSize;
Canvas.Pen.Style := psInsideFrame;
Canvas.Brush.Color := DrawInfo.Color;
Canvas.Pen.Color := DrawInfo.BorderColor;
Canvas.FillRect(DrawRect);
if DrawInfo.BorderSize <> 0 then
Canvas.Rectangle(DrawRect);
Text := DrawInfo.Text;
Canvas.Font.Assign(DrawInfo.Font);
DrawRect.Inflate(-DrawInfo.BorderSize, -DrawInfo.BorderSize);
Canvas.TextRect(DrawRect, Text, [tfCenter, tfVerticalCenter, tfSingleLine]);
end;
procedure TPickerDrawer.DrawPickerColumn(Canvas: TCanvas; DrawRect: TRect; Color: TColor);
begin
Canvas.Pen.Style := psClear;
Canvas.Brush.Color := Color;
Canvas.Brush.Style := bsSolid;
Canvas.FillRect(DrawRect);
end;
procedure TPickerDrawer.DrawSelectedRect(Canvas: TCanvas; var DrawRect: TRect;
BorderWidth: Integer);
begin
DrawRect.Inflate(-BorderWidth, 0);
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := GetSelectionColor;
Canvas.Pen.Style := psInsideFrame;
Canvas.FillRect(DrawRect);
end;
function TPickerDrawer.GetBorderColor(Hot, Pressed: Boolean): TColor;
begin
if Pressed then
Result := clBtnHighlight
else if Hot then
Result := clWindowFrame
else
Result := FPickerControl.BorderColor;
end;
function TPickerDrawer.GetButtonColor(Hot, Pressed: Boolean): TColor;
begin
if Pressed then
Result := clBtnShadow
else if Hot then
Result := clInactiveBorder
else
Result := clBtnFace;
end;
function TPickerDrawer.GetButtonFontColor(Hot, Pressed: Boolean): TColor;
begin
Result := clBtnText;
end;
function TPickerDrawer.GetColor(Hot, Pressed, Enabled: Boolean): TColor;
begin
if Hot then
Result := FPickerControl.HotColor
else if not Enabled then
Result := clBtnFace
else
Result := FPickerControl.Color;
end;
function TPickerDrawer.GetFontColor: TColor;
begin
Result := FPickerControl.Font.Color;
end;
function TPickerDrawer.GetHighlightColor: TColor;
begin
Result := FPickerControl.HighlightColor;
end;
function TPickerDrawer.GetPopupColor: TColor;
begin
Result := FPickerControl.PopupColor;
end;
function TPickerDrawer.GetSelectionColor: TColor;
begin
Result := FPickerControl.SelectionColor;
end;
function TPickerDrawer.GetSelectionFontColor: TColor;
begin
Result := FPickerControl.SelectionFontColor;
end;
function TPickerDrawer.MiddleColor(Color1, Color2: TColor;
Coeff: Double = 0.5): TColor;
function Approx(C1, C2: Integer): Integer;
begin
Result := C1 + Round((C2 - C1) * Coeff);
end;
begin
Color1 := ColorToRGB(Color1);
Color2 := ColorToRGB(Color2);
Result := RGB(Approx(GetRValue(Color1), GetRValue(Color2)),
Approx(GetGValue(Color1), GetGValue(Color2)), Approx(GetBValue(Color1),
GetBValue(Color2)));
end;
{ TDateColumn }
constructor TDateColumn.Create(const DateProvider: IDateProvider);
begin
inherited Create;
Assert(DateProvider <> nil);
FDateProvider := DateProvider;
end;
function TDateColumn.GetActualDate: TDate;
begin
Result := DateProvider.Date;
end;
procedure TDateColumn.SetActualDate(Value: TDate);
begin
DateProvider.Date := Value;
end;
{ TPickerDayColumn }
function TPickerDayColumn.GetCurrentValue: Integer;
begin
Result := DayOf(ActualDate);
end;
function TPickerDayColumn.GetMaxValue: Integer;
begin
Result := DaysInAMonth(YearOf(ActualDate), MonthOf(ActualDate));
end;
function TPickerDayColumn.GetMinValue: Integer;
begin
Result := 1;
end;
function TPickerDayColumn.GetValueString(Value: Integer): string;
begin
Result := FormatDateTime(DaysFormat, EncodeDate(YearOf(ActualDate),
MonthOf(ActualDate), Value));
end;
procedure TPickerDayColumn.SetCurrentValue(Value: Integer);
var
Year, Month, Day, MaxDays: Word;
begin
DecodeDate(ActualDate, Year, Month, Day);
Day := Value;
MaxDays := DaysInMonth(EncodeDate(Year, Month, 1));
if Day > MaxDays then
Day := MaxDays;
ActualDate := EncodeDate(Year, Month, Day);
end;
{ TPickerCellDrawInfo }
constructor TPickerCellDrawInfo.Create;
begin
inherited;
FFont := TFont.Create;
end;
destructor TPickerCellDrawInfo.Destroy;
begin
FreeAndNil(FFont);
inherited;
end;
procedure TPickerCellDrawInfo.SetFont(Value: TFont);
begin
FFont.Assign(Value);
end;
{ TBasePickerControl }
constructor TBasePickerControl.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := [csCaptureMouse, csNeedsBorderPaint, csClickEvents, csOpaque,
csDoubleClicks, csReflector, csPannable];
Font.Color := clWindowText;
Font.Name := 'Segoe UI'; // do not localize
Font.Size := DefaultFontSize;
HighlightColor := DefaultPickerHighlightColor;
HotColor := DefaultPickerHotColor;
SelectionColor := DefaultPickerSelectionColor;
SelectionFontColor := DefaultPickerSelectionFontColor;
FDropDownCount := DefaultPickerDropDownCount;
ShowOkCancel := True;
FColumns := TObjectList<TPickerColumn>.Create(True);
FBorderSize := 1;
BorderStyle := bsSingle;
ParentColor := False;
Color := clWindow;
BorderColor := DefaultBorderColor;
PopupColor := DefaultPopupColor;
TabStop := True;
Width := DefaultPickerWidth;
Height := DefaultPickerHeight;
end;
destructor TBasePickerControl.Destroy;
begin
if FDroppedDown then
CloseUp(False);
FreeAndNil(FColumns);
FreeAndNil(FDrawer);
inherited;
end;
procedure TBasePickerControl.AdjustSize;
var
NewSize: TSize;
begin
if not(csLoading in ComponentState) and HandleAllocated then
begin
NewSize := CalcSizes(ClientRect.Size);
SetWindowPos(Handle, 0, 0, 0, NewSize.cx, NewSize.cy, SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOZORDER);
RequestAlign;
end;
end;
function TBasePickerControl.CalcSizes(MinSize: TSize): TSize;
var
Columns: TList<TPickerColumn>;
LastItem, CurrentColumn: TPickerColumn;
I, Offset, ContentWidth, LMinColumnsWidth, NewWidth, MinHeight: Integer;
NewSize: TSize;
Coeff: Double;
begin
Columns := TList<TPickerColumn>.Create;
try
DefineColumns(Columns);
if Columns.Count = 0 then
begin
Result := MinSize;
Exit;
end;
LMinColumnsWidth := 0;
MinHeight := MinSize.cy;
for CurrentColumn in Columns do
begin
NewSize := CurrentColumn.GetMinSize(Canvas, Font);
CurrentColumn.Bounds := TRect.Create(Point(0, 0), NewSize.cx, NewSize.cy);
MinHeight := Max(NewSize.cy, MinHeight);
Inc(LMinColumnsWidth, NewSize.cx);
end;
ContentWidth := Max(LMinColumnsWidth, MinSize.cx - FBorderSize * 2);
NewWidth := ContentWidth + FBorderSize * 2;
Coeff := ContentWidth / LMinColumnsWidth;
Offset := 0;
for I := 0 to Columns.Count - 1 do
begin
CurrentColumn := Columns[I];
CurrentColumn.Bounds := TRect.Create(Point(Offset, 0), Trunc(CurrentColumn.Bounds.Width * Coeff), MinHeight);
Offset := CurrentColumn.Bounds.Right;
end;
if Offset < NewWidth - FBorderSize then
begin
LastItem := Columns[Columns.Count - 1];
LastItem.Bounds.Width := LastItem.Bounds.Width + NewWidth - Offset;
end;
Result.cx := NewWidth;
Result.cy := MinHeight;
finally
FreeAndNil(Columns);
end;
end;
function TBasePickerControl.CanModify: Boolean;
begin
Result := True;
end;
function TBasePickerControl.CanResize(var NewWidth, NewHeight: Integer)
: Boolean;
var
NewSize: TSize;
begin
Result := inherited CanResize(NewWidth, NewHeight);
if Result then
begin
NewSize := CalcSizes(TSize.Create(NewWidth, NewHeight));
NewWidth := NewSize.cx;
NewHeight := NewSize.cy;
end;
end;
procedure TBasePickerControl.ChangeScale(M, D: Integer; isDpiChange: Boolean);
begin
inherited ChangeScale(M, D, isDpiChange);
FBorderSize := MulDiv(FBorderSize, M, D);
if Assigned(FPopupControl) then
FPopupControl.ChangeScale(M, D, isDpiChange);
end;
procedure TBasePickerControl.Click;
begin
inherited;
if FDroppedDown then
CloseUp(True)
else
DropDown;
end;
procedure TBasePickerControl.CloseUp(Accept: Boolean);
begin
if FDroppedDown then
begin
if GetCapture <> 0 then
SendMessage(GetCapture, WM_CANCELMODE, 0, 0);
if HandleAllocated then
SetWindowPos(FPopupControl.Handle, 0, 0, 0, 0, 0, SWP_NOZORDER or
SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE or SWP_HIDEWINDOW);
FDroppedDown := False;
if Accept and CanModify then
AcceptDropDown
else
RejectDropDown;
Invalidate;
if Assigned(FOnCloseUp) then
FOnCloseUp(Self);
end;
end;
procedure TBasePickerControl.CMCancelMode(var Msg: TCMCancelMode);
begin
if (Msg.Sender <> Self) and (Msg.Sender <> FPopupControl) then
CloseUp(not ShowOkCancel);
end;
procedure TBasePickerControl.CMDialogKey(var Msg: TCMDialogKey);
begin
if (Msg.CharCode in [VK_RETURN, VK_ESCAPE]) and FDroppedDown then
begin
CloseUp(Msg.CharCode = VK_RETURN);
Msg.Result := 1;
end
else
inherited;
end;
procedure TBasePickerControl.CMMouseEnter(var Msg: TMessage);
begin
Hot := True;
inherited;
end;
procedure TBasePickerControl.CMMouseLeave(var Msg: TMessage);
begin
Hot := False;
inherited;
end;
procedure TBasePickerControl.CMStyleChanged(var Msg: TMessage);
begin
inherited;
FreeAndNil(FDrawer);
end;
procedure TBasePickerControl.CNKeyDown(var Msg: TMessage);
begin
if Msg.WParam in [VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN] then
FPopupControl.Perform(Msg.Msg, Msg.WParam, Msg.LParam)
else
inherited;
end;
function TBasePickerControl.CreateDrawer: TPickerDrawer;
begin
if TStyleManager.IsCustomStyleActive then
Result := TPickerDrawerStyled.Create(Self)
else
Result := TPickerDrawerNative.Create(Self);
end;
procedure TBasePickerControl.CreateWnd;
begin
inherited;
AdjustSize;
end;
procedure TBasePickerControl.DoDrawPickerCell(Sender: TObject; PickerCellDrawInfo: TPickerCellDrawInfo);
begin
if Assigned(FOnDrawPickerCell) then
FOnDrawPickerCell(Sender, PickerCellDrawInfo);
end;
function TBasePickerControl.DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean;
begin
Result := False;
if FDroppedDown then
Result := FPopupControl.DoMouseWheelDown(Shift, MousePos);
end;
function TBasePickerControl.DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean;
begin
Result := False;
if FDroppedDown then
Result := FPopupControl.DoMouseWheelUp(Shift, MousePos);
end;
procedure TBasePickerControl.DoOnChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TBasePickerControl.DropDown;
function CalcDropDownPosition: TPoint;
begin
Result := ClientToScreen(ParentToClient(Point(Left, Top)));
Result.Offset(-(FPopupControl.Width - Width) div 2,
-(FPopupControl.Height - Height) div 2 + FPopupControl.FItemHeight div 2);
if Result.Y + FPopupControl.Height > Screen.DesktopHeight then
Result.Y := Screen.DesktopHeight - FPopupControl.Height;
if Result.X + FPopupControl.Width > Screen.DesktopWidth then
Result.X := Screen.DesktopWidth - FPopupControl.Width;
if Result.Y < 0 then
Result.Y := 0;
if Result.X < 0 then
Result.X := 0;
end;
var
LPosition: TPoint;
begin
if FDroppedDown then
Exit;
InitPopup;
LPosition := CalcDropDownPosition;
SetWindowPos(FPopupControl.Handle, HWND_TOP, LPosition.X, LPosition.Y, 0, 0,
SWP_NOSIZE or SWP_NOACTIVATE or SWP_FRAMECHANGED or SWP_SHOWWINDOW);
FDroppedDown := True;
end;
function TBasePickerControl.GetColumnByClass<T>: T;
var
Column: TPickerColumn;
begin
for Column in FColumns do
if Column is T then
Exit(Column as T);
Result := nil;
end;
procedure TBasePickerControl.InitPopup;
var
LColumns: TList<TPickerColumn>;
ViewInfo: TPickerViewInfo;
begin
LColumns := TList<TPickerColumn>.Create;
try
DefineColumns(LColumns);
if FPopupControl = nil then
FPopupControl := TPickerPopupControl.Create(Self);
ViewInfo := TPickerViewInfo.Create;
try
ViewInfo.BorderColor := BorderColor;
ViewInfo.BorderSize := FBorderSize;
ViewInfo.Color := PopupColor;
ViewInfo.Font := Font;
ViewInfo.DropDownCount := DropDownCount;
ViewInfo.ItemHeight := ClientHeight;
ViewInfo.ShowOkCancel := ShowOkCancel;
ViewInfo.HighlightColor := HighlightColor;
FPopupControl.Init(Self, LColumns, ViewInfo, FOnDrawCell, NeedDrawer);
finally
FreeAndNil(ViewInfo);
end;
finally
LColumns.Free;
end;
end;
procedure TBasePickerControl.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited;
if ((ssAlt in Shift) and ((Key = VK_UP) or (Key = VK_DOWN))) or
(Key = VK_RETURN) or (Key = VK_SPACE) then
begin
if FDroppedDown then
CloseUp(True)
else
DropDown;
end;
if Key = VK_BACK then
CloseUp(False);
end;
function TBasePickerControl.NeedDrawer: TPickerDrawer;
begin
if FDrawer = nil then
FDrawer := CreateDrawer;
Result := FDrawer;
end;
procedure TBasePickerControl.Paint;
var
Column: TPickerColumn;
DrawInfo: TPickerCellDrawInfoInternal;
Bitmap: TBitmap;
begin
Bitmap := TBitmap.Create;
try
Bitmap.SetSize(Width, Height);
for Column in FColumns do
begin
DrawInfo := TPickerCellDrawInfoInternal.Create;
try
DrawInfo.Bounds := Column.Bounds;
DrawInfo.BorderColor := NeedDrawer.GetBorderColor(Hot or Focused, Pressed);
DrawInfo.BorderSize := FBorderSize;
DrawInfo.Color := NeedDrawer.GetColor(Hot or Focused, Pressed, Enabled);
DrawInfo.Font.Assign(Font);
DrawInfo.Font.Color := NeedDrawer.GetFontColor;
DrawInfo.Text := Column.GetValueString(Column.CurrentValue);
DoDrawPickerCell(Self, DrawInfo);
NeedDrawer.DrawPickerCell(Bitmap.Canvas, DrawInfo);
finally
FreeAndNil(DrawInfo);
end;
end;
Canvas.CopyRect(ClientRect, Bitmap.Canvas, ClientRect);
finally
FreeAndNil(Bitmap);
end;
end;
procedure TBasePickerControl.SetBorderColor(Value: TColor);
begin
FBorderColor := Value;
if Assigned(FPopupControl) then
FPopupControl.BorderColor := Value;
Invalidate;
end;
procedure TBasePickerControl.SetBorderStyle(Value: TBorderStyle);
begin
if FBorderStyle = Value then
Exit;
FBorderStyle := Value;
if FBorderStyle = bsSingle then
FBorderSize := MulDiv(1, Screen.PixelsPerInch, 96)
else
FBorderSize := 0;
Invalidate;
end;
procedure TBasePickerControl.SetDropdownCount(Value: Integer);
begin
FDropDownCount := Value;
end;
procedure TBasePickerControl.SetHighlightColor(Value: TColor);
begin
FHighlightColor := Value;
Invalidate;
end;
procedure TBasePickerControl.SetHotColor(Value: TColor);
begin
FHotColor := Value;
Invalidate;
end;
procedure TBasePickerControl.SetHot(Value: Boolean);
begin
FHot := Value;
Invalidate;
end;
procedure TBasePickerControl.SetPopupColor(Value: TColor);
begin
FPopupColor := Value;
Invalidate;
end;
procedure TBasePickerControl.SetPressed(Value: Boolean);
begin
if FPressed = Value then
Exit;
FPressed := Value;
Invalidate;
end;
procedure TBasePickerControl.SetSelectionColor(Value: TColor);
begin
FSelectionColor := Value;
Invalidate;
end;
procedure TBasePickerControl.SetSelectionFontColor(Value: TColor);
begin
FSelectionFontColor := Value;
Invalidate;
end;
procedure TBasePickerControl.SetShowOkCancel(Value: Boolean);
begin
FShowOkCancel := Value;
end;
procedure TBasePickerControl.WMKillFocus(var Msg: TWMKillFocus);
begin
inherited;
CloseUp(False);
Invalidate;
end;
procedure TBasePickerControl.WMLButtonDown(var Msg: TWMLButtonDown);
begin
if CanFocus then
SetFocus;
Pressed := True;
inherited;
end;
procedure TBasePickerControl.WMLButtonUp(var Msg: TWMLButtonUp);
begin
Pressed := False;
inherited;
end;
procedure TBasePickerControl.WMSetFocus(var Msg: TWMSetFocus);
begin
Invalidate;
inherited;
end;
{ TCustomDatePicker }
constructor TCustomDatePicker.Create(AOwner: TComponent);
begin
inherited;
FDateProvider := TDateProvider.Create;
FDateFormat := FormatSettings.ShortDateFormat;
Date := Today;
ParseFormat(FDateFormat);
MaxYear := DefaultMaxYear;
MinYear := DefaultMinYear;
InitColumns;
end;
procedure TCustomDatePicker.AcceptDropDown;
begin
Date := GetDateFromColumns;
end;
procedure TCustomDatePicker.DefineColumns(Columns: TList<TPickerColumn>);
var
Column: TPickerColumn;
begin
if Assigned(FColumns) then
begin
for Column in FColumns do
Columns.Add(Column);
SetDateToColumns(Date);
end;
end;
function TCustomDatePicker.GetDate: TDate;
begin
Result := FDate;
end;
function TCustomDatePicker.GetDateFromColumns: TDate;
var
Column: TPickerColumn;
DayColumn: TPickerDayColumn absolute Column;
YearColumn: TPickerYearColumn absolute Column;
MonthColumn: TPickerMonthColumn absolute Column;
Year, Month, Day: Word;
begin
DecodeDate(FDate, Year, Month, Day);
if Assigned(FColumns) then
for Column in FColumns do
begin
if Column is TPickerYearColumn then
Year := YearColumn.CurrentValue
else if Column is TPickerMonthColumn then
Month := MonthColumn.CurrentValue
else if Column is TPickerDayColumn then
Day := DayColumn.CurrentValue
end;
Result := EncodeDate(Year, Month, Day);
end;
function TCustomDatePicker.GetDayVisible: Boolean;
var
Column: TPickerColumn;
begin
for Column in FColumns do
if Column is TPickerDayColumn then
Exit(True);
Result := False;
end;
function TCustomDatePicker.GetMaxYear: Integer;
begin
Result := FDateProvider.MaxYear;
end;
function TCustomDatePicker.GetMinYear: Integer;
begin
Result := FDateProvider.MinYear;
end;
function TCustomDatePicker.GetMonthVisible: Boolean;
var
Column: TPickerColumn;
begin
for Column in FColumns do
if Column is TPickerMonthColumn then
Exit(True);
Result := False;
end;
function TCustomDatePicker.GetYearVisible: Boolean;
var
Column: TPickerColumn;
begin
for Column in FColumns do
if Column is TPickerYearColumn then
Exit(True);
Result := False;
end;
procedure TCustomDatePicker.InitColumns;
begin
SetDateToColumns(Date);
if HandleAllocated then
CalcSizes(ClientRect.Size);
end;
procedure TCustomDatePicker.ParseFormat(const Format: string);
const
DateFormatRegExpt = '(yyyy|yy|y)|(m{1,4})|(d{1,6})'; // do not localize
var
Match: TMatch;
Matches: TMatchCollection;
Value: string;
DayColumn: TPickerDayColumn;
YearColumn: TPickerYearColumn;
MonthColumn: TPickerMonthColumn;
begin
FreeAndNil(FColumns);
FColumns := TObjectList<TPickerColumn>.Create(True);
Matches := TRegEx.Matches(Format, DateFormatRegExpt, [roSingleLine, roIgnoreCase, roNotEmpty]);
for Match in Matches do
begin
if not Match.Success then
Continue;
Value := Match.Value;
if Value.Length = 0 then
Continue;
case LowerCase(Value)[1] of
'y':
begin
YearColumn := TPickerYearColumn.Create(FDateProvider);
YearColumn.YearFormat := Value;
FColumns.Add(YearColumn);
end;
'm':
begin
MonthColumn := TPickerMonthColumn.Create(FDateProvider);
MonthColumn.MonthFormat := Value;
FColumns.Add(MonthColumn);
end;
'd':
begin
DayColumn := TPickerDayColumn.Create(FDateProvider);
DayColumn.DaysFormat := Value;
FColumns.Add(DayColumn);
end;
end;
end;
end;
procedure TCustomDatePicker.RejectDropDown;
begin
SetDateToColumns(Date);
end;
procedure TCustomDatePicker.SetDate(Value: TDate);
begin
if FDate = Value then
Exit;
FDate := Value;
DoOnChange;
SetDateToColumns(FDate);
Invalidate;
end;
procedure TCustomDatePicker.SetDateFormat(const Value: string);
begin
if FDateFormat = Value then
Exit;
FDateFormat := Value;
ParseFormat(FDateFormat);
InitColumns;
Invalidate;
end;
procedure TCustomDatePicker.SetDateToColumns(Value: TDate);
var
DayColumn: TPickerDayColumn;
YearColumn: TPickerYearColumn;
MonthColumn: TPickerMonthColumn;
Year, Month, Day: Word;
begin
DecodeDate(Value, Year, Month, Day);
if Assigned(FColumns) then
begin
YearColumn := GetColumnByClass<TPickerYearColumn>;
if Assigned(YearColumn) then
YearColumn.CurrentValue := Year;
MonthColumn := GetColumnByClass<TPickerMonthColumn>;;
if Assigned(MonthColumn) then
MonthColumn.CurrentValue := Month;
DayColumn := GetColumnByClass<TPickerDayColumn>;;
if Assigned(DayColumn) then
DayColumn.CurrentValue := Day;
end;
end;
procedure TCustomDatePicker.SetMaxYear(Value: Integer);
begin
FDateProvider.MaxYear := Value;
end;
procedure TCustomDatePicker.SetMinYear(Value: Integer);
begin
FDateProvider.MinYear := Value;
end;
{ TPickerYearColumn }
function TPickerYearColumn.GetCurrentValue: Integer;
begin
Result := YearOf(ActualDate);
end;
function TPickerYearColumn.GetMaxValue: Integer;
begin
Result := DateProvider.MaxYear;
end;
function TPickerYearColumn.GetMinValue: Integer;
begin
Result := DateProvider.MinYear;
end;
function TPickerYearColumn.GetValueString(Value: Integer): string;
begin
Result := FormatDateTime(YearFormat, EncodeDate(Value, 1, 1));
end;
function TPickerYearColumn.IsCyclic: Boolean;
begin
Result := False;
end;
procedure TPickerYearColumn.SetCurrentValue(Value: Integer);
var
Year, Month, Day, MaxDays: Word;
begin
DecodeDate(ActualDate, Year, Month, Day);
MaxDays := DaysInMonth(EncodeDate(Value, Month, 1));
if Day > MaxDays then
Day := MaxDays;
ActualDate := EncodeDate(Value, Month, Day);
end;
{ TPickerPopupControl }
constructor TPickerPopupControl.Create(AOwner: TComponent);
begin
inherited;
DoubleBuffered := True;
Height := 300;
Width := 200;
FBorderSize := 2;
FMouseOver := -1;
FDropDownCount := DefaultPickerDropDownCount;
FHighlightColor := DefaultPickerHighlightColor;
FHotColor := DefaultPickerHotColor;
FSelectionColor := DefaultPickerSelectionColor;
FSelectionFontColor := DefaultPickerSelectionFontColor;
FOkCancelButtons := TPickerOkCancelButtons.Create
end;
destructor TPickerPopupControl.Destroy;
begin
FreeAndNil(FOkCancelButtons);
FreeAndNil(FAnimation);
inherited;
end;
procedure TPickerPopupControl.AnimateColumnValueChanged(Column: TPickerColumn;
NextValue, Delta: Integer);
var
Animation: TPickerSlideAnimation;
begin
if FAnimation <> nil then
FAnimation.Finish;
FreeAndNil(FAnimation);
Animation := TPickerSlideAnimation.Create;
FAnimation := Animation;
Animation.NextValue := NextValue;
Animation.Control := Self;
Animation.Duration := 250;
Animation.Interval := 10;
Animation.Column := Column;
Animation.Delta := -Delta;
Animation.StartDefault;
Animation.OnFinished := AnimationFinished;
end;
procedure TPickerPopupControl.AnimationFinished(Sender: TObject);
var
Animation: TPickerSlideAnimation;
begin
Animation := (Sender as TPickerSlideAnimation);
Animation.Column.CurrentValue := (Sender as TPickerSlideAnimation).NextValue;
UpdateHoverItems(Self.ScreenToClient(Mouse.CursorPos));
Invalidate;
end;
procedure TPickerPopupControl.Calculate;
var
Column: TPickerColumn;
NewWidth, NewHeight, OkCancelHeight: Integer;
begin
NewHeight := DropDownCount * FItemHeight;
NewWidth := 0;
for Column in FColumns do
begin
Column.DropDownBounds := Rect(Column.Bounds.Left, 0, Column.Bounds.Right,
NewHeight);
Column.UpButton.BoundsRect := Column.DropDownBounds.SplitRect(srTop,
MulDiv(ScrollButtonHeight, Screen.PixelsPerInch, 96));
Column.UpButton.BoundsRect.Inflate(-FBorderSize, -FBorderSize);
Column.DownButton.BoundsRect := Column.DropDownBounds.SplitRect(srBottom,
MulDiv(ScrollButtonHeight, Screen.PixelsPerInch, 96));
Column.DownButton.BoundsRect.Inflate(-FBorderSize, -FBorderSize);
NewWidth := NewWidth + Column.DropDownBounds.Width;
end;
if ShowOkCancel then
begin
NewHeight := NewHeight + FItemHeight;
OkCancelHeight := FItemHeight;
end else
OkCancelHeight := 0;
SetBounds(Left, Top, NewWidth, NewHeight);
FSelectRect := Rect(0, Round((NewHeight - FItemHeight) / 2 - OkCancelHeight div 2), Width,
Round((NewHeight - FItemHeight) / 2) + FItemHeight - OkCancelHeight div 2);
if ShowOkCancel then
FOkCancelButtons.Calculate(ClientRect, FItemHeight, FBorderSize);
end;
procedure TPickerPopupControl.CMMouseActivate(var Msg: TCMMouseActivate);
begin
Msg.Result := MA_NOACTIVATE;
end;
procedure TPickerPopupControl.CMMouseLeave(var Msg: TMessage);
begin
MouseOver := -1;
FOkCancelButtons.OkButton.State := pbsNone;
FOkCancelButtons.CancelButton.State := pbsNone;
InvalidateRect(Handle, FOkCancelButtons.Bounds, False);
inherited;
end;
procedure TPickerPopupControl.CNKeyDown(var Msg: TWMKeyDown);
var
NextValue, Delta: Integer;
Column: TPickerColumn;
begin
case Msg.CharCode of
VK_UP, VK_DOWN:
begin
MouseOver := Max(0, MouseOver);
Column := FColumns[MouseOver];
if Assigned(Column) then
begin
Delta := 1;
if Msg.CharCode = VK_UP then
Delta := Column.CalcNextValue(Column.CurrentValue,
NextValue, -Delta)
else
Delta := Column.CalcNextValue(Column.CurrentValue,
NextValue, Delta);
if Delta <> 0 then
AnimateColumnValueChanged(Column, NextValue, Delta);
end;
end;
VK_LEFT:
if MouseOver > 0 then
MouseOver := MouseOver - 1;
VK_RIGHT:
if MouseOver < Length(FColumns) - 1 then
MouseOver := MouseOver + 1;
end;
end;
procedure TPickerPopupControl.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.Style := (Params.Style or WS_POPUP) and (not WS_CHILD);
Params.ExStyle := Params.ExStyle or WS_EX_TOOLWINDOW;
Params.WindowClass.Style := Params.WindowClass.Style or CS_DROPSHADOW;
Params.WndParent := FParentOwner.Handle;
end;
procedure TPickerPopupControl.DoDrawCell(Sender: TObject; PickerCellDrawInfo: TPickerCellDrawInfo);
begin
if Assigned(FOnDrawCell) then
FOnDrawCell(Sender, PickerCellDrawInfo);
end;
function TPickerPopupControl.DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean;
var
Column: TPickerColumn;
NextValue, Delta: Integer;
begin
MousePos := ScreenToClient(MousePos);
Column := GetColumnByMousePos(MousePos);
Result := False;
if ssCtrl in Shift then
Delta := Mouse.WheelScrollLines
else
Delta := 1;
if Assigned(Column) then
begin
Delta := Column.CalcNextValue(Column.CurrentValue, NextValue, Delta);
if Delta <> 0 then
begin
AnimateColumnValueChanged(Column, NextValue, Delta);
Result := True;
end;
end;
end;
function TPickerPopupControl.DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean;
var
Column: TPickerColumn;
PrevValue, Delta: Integer;
begin
MousePos := ScreenToClient(MousePos);
Column := GetColumnByMousePos(MousePos);
Result := False;
if ssCtrl in Shift then
Delta := -Mouse.WheelScrollLines
else
Delta := -1;
if Assigned(Column) then
begin
Delta := Column.CalcNextValue(Column.CurrentValue, PrevValue, Delta);
if Delta <> 0 then
begin
AnimateColumnValueChanged(Column, PrevValue, Delta);
Result := True;
end;
end;
end;
function TPickerPopupControl.GetCellValueByMousePos(Point: TPoint;
out ResultValue, ResultDelta: Integer): Boolean;
var
Value, Delta: Integer;
Column: TPickerColumn;
begin
Column := GetColumnByMousePos(Point);
if not Assigned(Column) then
Exit(False);
Value := Column.CurrentValue;
ResultDelta := 0;
if FSelectRect.Contains(Point) then
Exit(True);
if Point.Y < FSelectRect.Top then
Delta := (Point.Y - FSelectRect.Top) div (FItemHeight - FBorderSize * 2) - 1
else
Delta := (Point.Y - FSelectRect.Bottom)
div (FItemHeight - FBorderSize * 2) + 1;
Result := Column.CalcNextValue(Value, Value, Delta) = Delta;
if Result then
begin
ResultValue := Value;
ResultDelta := Delta;
end;
end;
function TPickerPopupControl.GetColumnByMousePos(Point: TPoint): TPickerColumn;
var
Column: TPickerColumn;
begin
for Column in FColumns do
if Column.DropDownBounds.Contains(Point) then
Exit(Column);
Result := nil;
end;
procedure TPickerPopupControl.Init(ParentOwner: TWinControl; Columns: TList<TPickerColumn>;
ViewInfo: TPickerViewInfo; OnDrawEvent: TDrawPickerCellEvent; Drawer: TPickerDrawer);
begin
FParentOwner := ParentOwner;
FColumns := Columns.ToArray;
DropDownCount := ViewInfo.DropDownCount;
FItemHeight := ViewInfo.ItemHeight;
FDrawer := Drawer;
Font.Assign(ViewInfo.Font);
BorderColor := ViewInfo.BorderColor;
Color := ViewInfo.Color;
HighlightColor := ViewInfo.HighlightColor;
FBorderSize := ViewInfo.BorderSize;
ShowOkCancel := ViewInfo.ShowOkCancel;
OnDrawCell := OnDrawEvent;
Calculate;
end;
procedure TPickerPopupControl.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
UpdateHoverItems(Point(X, Y));
inherited;
end;
procedure TPickerPopupControl.Paint;
var
Bitmap: TBitmap;
DrawRect: TRect;
begin
DrawRect := ClientRect;
Bitmap := TBitmap.Create;
try
Bitmap.SetSize(DrawRect.Width, DrawRect.Height);
PaintColumns(Bitmap.Canvas, FDrawer);
PaintOkCancel(Bitmap.Canvas, FDrawer);
Canvas.CopyRect(DrawRect, Bitmap.Canvas, DrawRect);
finally
FreeAndNil(Bitmap);
end;
end;
procedure TPickerPopupControl.PaintCell(Canvas: TCanvas; Rect: TRect; const Text: string;
Drawer: TPickerDrawer; Highlighted, Selected: Boolean);
var
DrawInfo: TPickerCellDrawInfoInternal;
begin
DrawInfo := TPickerCellDrawInfoInternal.Create;
try
DrawInfo.Bounds := Rect;
DrawInfo.Text := Text;
DrawInfo.BorderColor := Drawer.GetBorderColor(False, False);
DrawInfo.Font.Assign(Font);
DrawInfo.Color := Drawer.GetPopupColor;
DrawInfo.HighlightColor := Drawer.GetHighlightColor;
DrawInfo.Highlighted := Highlighted;
DrawInfo.Font.Color := Drawer.GetFontColor;
DrawInfo.Selected := Selected;
DrawInfo.BorderSize := FBorderSize;
DoDrawCell(Self, DrawInfo);
Drawer.DrawCell(Canvas, DrawInfo);
finally
FreeAndNil(DrawInfo);
end;
end;
procedure TPickerPopupControl.PaintColumn(Canvas: TCanvas; Column: TPickerColumn;
Drawer: TPickerDrawer; ColumnIndex: Integer);
procedure LocalPaintCell(DrawRect: TRect; Value: Integer; DrawHighlighted, DrawSelected: Boolean);
var
Highlighted: Boolean;
SelectedPart, UnselectedPart: TRect;
DrawRegion: HRGN;
begin
Highlighted := DrawHighlighted and (ColumnIndex = FMouseOver) and
(FMouseOverValue = Value) and (DrawRect.Contains(MouseOverPoint)) and
not FSelectRect.Contains(MouseOverPoint);
if FSelectRect.IntersectsWith(DrawRect) then
begin
SelectedPart := TRect.Intersect(FSelectRect, DrawRect);
SubtractRect(UnselectedPart, DrawRect, SelectedPart);
DrawRegion := CreateRectRgn(SelectedPart.Left, SelectedPart.Top, SelectedPart.Right, SelectedPart.Bottom);
try
SelectClipRgn(Canvas.Handle, DrawRegion);
PaintCell(Canvas, DrawRect, Column.GetValueString(Value), Drawer,
Highlighted, True);
SelectClipRgn(Canvas.Handle, HRGN(nil));
finally
DeleteObject(DrawRegion);
end;
DrawRegion := CreateRectRgn(UnselectedPart.Left, UnselectedPart.Top, UnselectedPart.Right, UnselectedPart.Bottom);
try
SelectClipRgn(Canvas.Handle, DrawRegion);
PaintCell(Canvas, DrawRect, Column.GetValueString(Value), Drawer,
Highlighted, False);
SelectClipRgn(Canvas.Handle, HRGN(nil));
finally
DeleteObject(DrawRegion);
end;
end
else
PaintCell(Canvas, DrawRect, Column.GetValueString(Value), Drawer, Highlighted, DrawSelected);
end;
var
CurrentValue, DrawArrowWidth: Integer;
PickerRect, DrawRect, SelectedRect: TRect;
DrawButtonInfo: TPickerButtonDrawInfo;
begin
Drawer.DrawPickerColumn(Canvas, Column.DropDownBounds, Drawer.GetPopupColor);
PickerRect := Column.DropDownBounds;
// draw selected rect
SelectedRect := Rect(PickerRect.Left, FSelectRect.Top, PickerRect.Right, FSelectRect.Bottom);
CurrentValue := Column.CurrentValue;
DrawRect := SelectedRect;
Drawer.DrawSelectedRect(Canvas, SelectedRect, FBorderSize);
// draw upper values
DrawRect.Offset(0, Column.DrawOffset);
while (DrawRect.Top + DrawRect.Height >= 0) and
(CurrentValue >= Column.GetMinValue) do
begin
LocalPaintCell(DrawRect, CurrentValue, Column.DrawOffset = 0,
(Column.CurrentValue = CurrentValue) and (DrawRect.IntersectsWith(SelectedRect)));
DrawRect.Offset(0, -DrawRect.Height);
if not Column.PreviousValue(CurrentValue, CurrentValue) then
Break;
end;
// draw lower values
DrawRect := SelectedRect;
DrawRect.Offset(0, Column.DrawOffset);
CurrentValue := Column.CurrentValue;
while Column.NextValue(CurrentValue, CurrentValue) and
((DrawRect.Bottom - PickerRect.Bottom) < (0)) and
(CurrentValue <= Column.GetMaxValue) do
begin
DrawRect.Offset(0, DrawRect.Height);
LocalPaintCell(DrawRect, CurrentValue, Column.DrawOffset = 0,
DrawRect = SelectedRect);
end;
Drawer.DrawPickerBorder(Canvas, FBorderSize, Column, Drawer.GetBorderColor(False, False));
if ColumnIndex = FMouseOver then
begin
DrawArrowWidth := MulDiv(ArrowWidth, Screen.PixelsPerInch, 96);
DrawButtonInfo := TPickerButtonDrawInfo.Create;
try
DrawButtonInfo.Button := Column.UpButton;
DrawButtonInfo.BorderWidth := BorderWidth;
DrawButtonInfo.Color := Color;
DrawButtonInfo.ForegroundColor := Drawer.GetFontColor;
DrawButtonInfo.PenWidth := DrawArrowWidth;
Drawer.DrawPickerButton(Canvas, DrawButtonInfo);
DrawButtonInfo.Button := Column.DownButton;
Drawer.DrawPickerButton(Canvas, DrawButtonInfo);
finally
FreeAndNil(DrawButtonInfo);
end;
end;
end;
procedure TPickerPopupControl.PaintColumn(Column: TPickerColumn; Drawer: TPickerDrawer;
ColumnIndex: Integer);
var
Bitmap: TBitmap;
DestRect: TRect;
begin
Bitmap := TBitmap.Create;
try
Bitmap.SetSize(Width, Height);
PaintColumn(Bitmap.Canvas, Column, Drawer, ColumnIndex);
DestRect := Column.DropDownBounds;
DestRect.Offset(FBorderSize, FBorderSize);
Canvas.CopyRect(Column.DropDownBounds, Bitmap.Canvas, Column.DropDownBounds);
finally
FreeAndNil(Bitmap);
end;
end;
procedure TPickerPopupControl.PaintColumns(const Canvas: TCanvas;
const Drawer: TPickerDrawer);
var
I: Integer;
begin
for I := 0 to Length(FColumns) - 1 do
PaintColumn(Canvas, FColumns[I], FDrawer, I);
end;
procedure TPickerPopupControl.PaintOkCancel(Canvas: TCanvas; Drawer: TPickerDrawer);
var
Bitmap: TBitmap;
DrawButtonInfo: TPickerButtonDrawInfo;
DrawArrowWidth: Integer;
begin
if not ShowOkCancel then
Exit;
Bitmap := TBitmap.Create;
try
Bitmap.SetSize(Width, Height);
DrawArrowWidth := MulDiv(ArrowWidth, Screen.PixelsPerInch, 96);
DrawButtonInfo := TPickerButtonDrawInfo.Create;
try
DrawButtonInfo.Button := FOkCancelButtons.OkButton;
DrawButtonInfo.BorderWidth := BorderWidth;
DrawButtonInfo.Color := Color;
DrawButtonInfo.ForegroundColor := Drawer.GetFontColor;
DrawButtonInfo.PenWidth := DrawArrowWidth;
Drawer.DrawOkCancel(Bitmap.Canvas, FOkCancelButtons, DrawButtonInfo, Drawer.GetBorderColor(False, False));
finally
FreeAndNil(DrawButtonInfo);
end;
Canvas.CopyRect(FOkCancelButtons.Bounds, Bitmap.Canvas, FOkCancelButtons.Bounds);
finally
FreeAndNil(Bitmap);
end;
end;
procedure TPickerPopupControl.SetBorderColor(Value: TColor);
begin
FBorderColor := Value;
Invalidate;
end;
procedure TPickerPopupControl.SetDropdownCount(Value: Integer);
begin
FDropDownCount := Value;
end;
procedure TPickerPopupControl.SetHighlightColor(Value: TColor);
begin
FHighlightColor := Value;
Invalidate;
end;
procedure TPickerPopupControl.SetHotColor(Value: TColor);
begin
FHotColor := Value;
Invalidate;
end;
procedure TPickerPopupControl.SetMouseOver(Value: Integer);
begin
if FMouseOver = Value then
Exit;
if FMouseOver <> -1 then
PaintColumn(FColumns[FMouseOver], FDrawer, Value);
FMouseOver := Value;
if Value <> -1 then
PaintColumn(FColumns[FMouseOver], FDrawer, Value);
end;
procedure TPickerPopupControl.SetMouseOverPoint(Value: TPoint);
begin
if FMouseOverPoint = Value then
Exit;
FMouseOverPoint := Value
end;
procedure TPickerPopupControl.SetMouseOverValue(Value: Integer);
begin
if FMouseOverValue = Value then
Exit;
FMouseOverValue := Value;
end;
procedure TPickerPopupControl.SetSelectionColor(Value: TColor);
begin
FSelectionColor := Value;
Invalidate;
end;
procedure TPickerPopupControl.SetSelectionFontColor(Value: TColor);
begin
FSelectionFontColor := Value;
Invalidate;
end;
procedure TPickerPopupControl.SetShowOkCancel(Value: Boolean);
begin
FShowOkCancel := Value;
end;
procedure TPickerPopupControl.UpdateHoverItems(Point: TPoint);
var
i, Value, Delta: Integer;
begin
for i := 0 to Length(FColumns) - 1 do
begin
if FColumns[i].DropDownBounds.Contains(Point) then
begin
MouseOver := i;
if FColumns[i].UpButton.BoundsRect.Contains(Point) then
begin
MouseOverValue := -1;
FColumns[i].UpButton.State := pbsHot;
end
else if FColumns[i].DownButton.BoundsRect.Contains(Point) then
begin
MouseOverValue := -1;
FColumns[i].DownButton.State := pbsHot
end
else
begin
FColumns[i].UpButton.State := pbsNone;
FColumns[i].DownButton.State := pbsNone;
if GetCellValueByMousePos(Point, Value, Delta) then
begin
MouseOverValue := Value;
MouseOverPoint := Point;
end;
end;
InvalidateRect(Handle, FColumns[i].DropDownBounds, False);
Break;
end
else
begin
FColumns[i].UpButton.State := pbsNone;
FColumns[i].DownButton.State := pbsNone;
InvalidateRect(Handle, FColumns[i].UpButton.BoundsRect, False);
InvalidateRect(Handle, FColumns[i].DownButton.BoundsRect, False);
end;
end;
if ShowOkCancel and FOkCancelButtons.OkButton.BoundsRect.Contains(Point) then
begin
FOkCancelButtons.OkButton.State := pbsHot;
MouseOver := -1;
end
else
FOkCancelButtons.OkButton.State := pbsNone;
if ShowOkCancel and FOkCancelButtons.CancelButton.BoundsRect.Contains(Point)
then
begin
FOkCancelButtons.CancelButton.State := pbsHot;
MouseOver := -1;
end
else
FOkCancelButtons.CancelButton.State := pbsNone;
InvalidateRect(Handle, FOkCancelButtons.Bounds, False);
end;
procedure TPickerPopupControl.WMGetDlgCode(var Msg: TWMGetDlgCode);
begin
Msg.Result := Msg.Result or DLGC_WANTARROWS;
end;
procedure TPickerPopupControl.WMLButtonDown(var Msg: TWMLButtonDown);
var
P: TPoint;
Value, Delta: Integer;
Column: TPickerColumn;
begin
inherited;
P := Point(Msg.XPos, Msg.YPos);
if FOkCancelButtons.OkButton.BoundsRect.Contains(P) and
(FParentOwner is TBasePickerControl) then
begin
FOkCancelButtons.OkButton.State := pbsPressed;
PaintOkCancel(Canvas, FDrawer);
end
else if FOkCancelButtons.CancelButton.BoundsRect.Contains(P) and
(FParentOwner is TBasePickerControl) then
begin
FOkCancelButtons.CancelButton.State := pbsPressed;
PaintOkCancel(Canvas, FDrawer);
end;
Column := GetColumnByMousePos(P);
if not Assigned(Column) then
Exit;
if Column.UpButton.BoundsRect.Contains(P) then
begin
if Column.PreviousValue(Column.CurrentValue, Value) then
AnimateColumnValueChanged(Column, Value, -1);
Column.UpButton.State := pbsPressed;
end
else if Column.DownButton.BoundsRect.Contains(P) then
begin
if Column.NextValue(Column.CurrentValue, Value) then
AnimateColumnValueChanged(Column, Value, 1);
Column.DownButton.State := pbsPressed;
end
else if GetCellValueByMousePos(P, Value, Delta) and (Delta <> 0) then
AnimateColumnValueChanged(Column, Value, Delta);
end;
procedure TPickerPopupControl.WMLButtonUp(var Msg: TWMLButtonUp);
var
P: TPoint;
begin
inherited;
P := Point(Msg.XPos, Msg.YPos);
if FOkCancelButtons.OkButton.BoundsRect.Contains(P) and
(FParentOwner is TBasePickerControl) then
(FParentOwner as TBasePickerControl).CloseUp(True)
else if FOkCancelButtons.CancelButton.BoundsRect.Contains(P) and
(FParentOwner is TBasePickerControl) then
(FParentOwner as TBasePickerControl).CloseUp(False);
end;
{ TPickerSlideAnimation }
procedure TPickerSlideAnimation.Animate(Current: Cardinal);
begin
Column.DrawOffset := Round(FCoef * Current);
FControl.PaintColumn(Column, FControl.FDrawer, FControl.MouseOver);
end;
procedure TPickerSlideAnimation.DoOnFinish;
begin
Column.DrawOffset := 0;
Column.CurrentValue := NextValue;
inherited;
end;
procedure TPickerSlideAnimation.DoPrepare;
begin
inherited;
FCoef := (Delta * FControl.FItemHeight) / Duration;
FControl.MouseOverValue := -1;
end;
{ TDateProvider }
function TDateProvider.GetDate: TDate;
begin
Result := FDate;
end;
function TDateProvider.GetMaxYear: Integer;
begin
Result := FMaxYear;
end;
function TDateProvider.GetMinYear: Integer;
begin
Result := FMinYear;
end;
procedure TDateProvider.SetDate(Value: TDate);
begin
FDate := Value;
end;
procedure TDateProvider.SetMaxYear(Value: Integer);
begin
FMaxYear := Value;
end;
procedure TDateProvider.SetMinYear(Value: Integer);
begin
FMinYear := Value;
end;
destructor TBasePickerAnimation.Destroy;
begin
FreeAndNil(FTimer);
inherited;
end;
procedure TBasePickerAnimation.DoOnFinish;
begin
if Assigned(OnFinished) then
OnFinished(Self);
end;
procedure TBasePickerAnimation.DoPrepare;
begin
end;
procedure TBasePickerAnimation.Finish;
begin
if (IsStarted) then
begin
Animate(Duration);
FreeAndNil(FTimer);
FIsStarted := False;
DoOnFinish;
end;
end;
procedure TBasePickerAnimation.Start(Duration, Interval: Cardinal);
begin
FDuration := Duration;
FInterval := Interval;
StartDefault;
end;
procedure TBasePickerAnimation.StartDefault;
begin
FWhenStarted := GetTickCount;
DoPrepare;
FreeAndNil(FTimer);
FTimer := TTimer.Create(nil);
FTimer.OnTimer := TimerTick;
FTimer.Interval := Interval;
FTimer.Enabled := True;
FIsStarted := True;
TimerTick(FTimer);
if Assigned(OnStarted) then
OnStarted(Self);
end;
procedure TBasePickerAnimation.TimerTick(Sender: TObject);
var
Current: Cardinal;
begin
Current := GetTickCount - WhenStarted;
if (Current + Interval >= Duration) then
Finish
else
Animate(Current);
end;
{ TTimeProvider }
function TTimeProvider.GetMinutesIncrement: TMinuteIncrement;
begin
Result := FMinutesIncrement;
end;
function TTimeProvider.GetTime: TTime;
begin
Result := FTime;
end;
function TTimeProvider.GetUseAmPm: Boolean;
begin
Result := FUseAmPm;
end;
procedure TTimeProvider.SetMinutesIncrement(Value: TMinuteIncrement);
begin
FMinutesIncrement := Value;
end;
procedure TTimeProvider.SetTime(Value: TTime);
begin
FTime := Value;
end;
procedure TTimeProvider.SetUseAmPm(Value: Boolean);
begin
FUseAmPm := Value;
end;
{ TTimeColumn }
constructor TTimeColumn.Create(const TimeProvider: ITimeProvider);
begin
inherited Create;
FTimeProvider := TimeProvider;
end;
function TTimeColumn.GetActualTime: TTime;
begin
Result := FTimeProvider.Time;
end;
procedure TTimeColumn.SetActualTime(Value: TTime);
begin
FTimeProvider.Time := Value;
end;
function TPickerHourColumn.GetCurrentValue: Integer;
begin
if TimeProvider.UseAmPm and (HourOf(ActualTime) > 12) then
Result := HourOf(ActualTime) - 12
else
Result := HourOf(ActualTime);
if TimeProvider.UseAmPm and (Result = 0) then
Result := 12;
end;
function TPickerHourColumn.GetMaxValue: Integer;
begin
if TimeProvider.UseAmPm then
Result := 12
else
Result := 23;
end;
function TPickerHourColumn.GetMinValue: Integer;
begin
Result := Ord(TimeProvider.UseAmPm);
end;
function TPickerHourColumn.GetValueString(Value: Integer): string;
begin
if (TimeProvider.UseAmPm) and (Value > 12) then
Result := FormatDateTime(FHourFormat, EncodeTime(Value - 12,
MinuteOf(ActualTime), SecondOf(ActualTime), MilliSecondOf(ActualTime)))
else
begin
if (TimeProvider.UseAmPm) and (Value = 0) then
Value := 12;
Result := FormatDateTime(FHourFormat,
EncodeTime(Value, MinuteOf(ActualTime), SecondOf(ActualTime),
MilliSecondOf(ActualTime)));
end;
end;
procedure TPickerHourColumn.SetCurrentValue(Value: Integer);
var
Hour, Minute, Second, MiliSecond: Word;
begin
DecodeTime(ActualTime, Hour, Minute, Second, MiliSecond);
ActualTime := EncodeTime(Value, Minute, Second, MiliSecond);
end;
procedure TPickerHourColumn.SetHourFormat(const Value: string);
begin
FHourFormat := Value;
end;
function TPickerMinuteColumn.GetCurrentValue: Integer;
begin
Result := MinuteOf(ActualTime);
end;
function TPickerMinuteColumn.GetMaxValue: Integer;
begin
Result := Trunc(59 / TimeProvider.MinutesIncrement) *
TimeProvider.MinutesIncrement;
end;
function TPickerMinuteColumn.GetMinValue: Integer;
begin
Result := 0;
end;
function TPickerMinuteColumn.GetValueString(Value: Integer): string;
var
TempFormat: string;
// 'mm' pattern could be treated as minutes or months as well, so it should be forced to 'nn'
begin
TempFormat := StringReplace(FMinuteFormat, 'm', 'n',
[rfReplaceAll, rfIgnoreCase]);
Result := FormatDateTime(TempFormat, EncodeTime(HourOf(ActualTime), Value,
SecondOf(ActualTime), MilliSecondOf(ActualTime)));
end;
function TPickerMinuteColumn.NextValue(Value: Integer; out NextValue: Integer): Boolean;
begin
Result := True;
if Value >= GetMaxValue then
begin
if IsCyclic then
NextValue := GetMinValue
else
Result := False;
end
else
begin
NextValue := Round(Value / TimeProvider.MinutesIncrement) *
TimeProvider.MinutesIncrement + TimeProvider.MinutesIncrement;
end;
end;
function TPickerMinuteColumn.PreviousValue(Value: Integer; out PrevValue: Integer): Boolean;
begin
Result := True;
if Value <= GetMinValue then
begin
if IsCyclic then
PrevValue := GetMaxValue
else
Result := False;
end
else
begin
PrevValue := Round(Value / TimeProvider.MinutesIncrement) *
TimeProvider.MinutesIncrement - TimeProvider.MinutesIncrement;
end;
end;
procedure TPickerMinuteColumn.SetCurrentValue(Value: Integer);
var
Hour, Minute, Second, MiliSecond: Word;
begin
DecodeTime(ActualTime, Hour, Minute, Second, MiliSecond);
ActualTime := EncodeTime(Hour, Trunc(Value / TimeProvider.MinutesIncrement) *
TimeProvider.MinutesIncrement, Second, MiliSecond);
end;
procedure TPickerMinuteColumn.SetMinuteFormat(const Value: string);
begin
FMinuteFormat := Value;
end;
function TPickerAMPMColumn.GetCurrentValue: Integer;
begin
Result := Ord(not FAm);
end;
function TPickerAMPMColumn.GetMaxValue: Integer;
begin
Result := 1;
end;
function TPickerAMPMColumn.GetMinValue: Integer;
begin
Result := 0;
end;
function TPickerAMPMColumn.GetValueString(Value: Integer): string;
begin
if Value = 1 then
Result := FormatDateTime(FAMPMFormat, EncodeTime(13, 0, 0, 0))
else
Result := FormatDateTime(FAMPMFormat, EncodeTime(1, 0, 0, 0))
end;
function TPickerAMPMColumn.IsCyclic: Boolean;
begin
Result := False;
end;
procedure TPickerAMPMColumn.SetAMPMFormat(const Value: string);
begin
FAMPMFormat := Value;
end;
procedure TPickerAMPMColumn.SetCurrentValue(Value: Integer);
begin
FAm := Value = 0;
end;
{ TCustomTimePicker }
constructor TCustomTimePicker.Create(AOwner: TComponent);
begin
inherited;
FTimeProvider := TTimeProvider.Create;
Time := Now;
MinuteIncrement := 1;
FTimeFormat := FormatSettings.ShortTimeFormat;
ParseFormat(FTimeFormat);
InitColumns;
end;
procedure TCustomTimePicker.AcceptDropDown;
begin
Time := GetTimeFromColumns;
end;
procedure TCustomTimePicker.DefineColumns(Columns: TList<TPickerColumn>);
var
LColumn: TPickerColumn;
begin
if not Assigned(FColumns) then
Exit;
for LColumn in FColumns do
Columns.Add(LColumn);
SetTimeToColumns(Time);
end;
function TCustomTimePicker.GetMinuteIncrement: TMinuteIncrement;
begin
Result := FTimeProvider.MinutesIncrement;
end;
function TCustomTimePicker.GetTimeFromColumns: TTime;
var
Column: TPickerColumn;
HourColumn: TPickerHourColumn absolute Column;
MinuteColumn: TPickerMinuteColumn absolute Column;
SecondColumn: TPickerSecondColumn absolute Column;
AMPMColumn: TPickerAMPMColumn absolute Column;
Hour, Minute, Second, MiliSecond: Word;
PM: Boolean;
begin
DecodeTime(FTime, Hour, Minute, Second, MiliSecond);
PM := False;
if FColumns <> nil then
for Column in FColumns do
begin
if Column is TPickerHourColumn then
Hour := HourColumn.CurrentValue
else if Column is TPickerMinuteColumn then
Minute := MinuteColumn.CurrentValue
else if Column is TPickerAMPMColumn then
PM := AMPMColumn.CurrentValue = 1
else if Column is TPickerSecondColumn then
Second := SecondColumn.CurrentValue;
end;
if FTimeProvider.UseAmPm and PM and (Hour < 12) then
Result := EncodeTime(Hour + 12, Minute, Second, MiliSecond)
else if FTimeProvider.UseAmPm and not PM and (Hour >= 12) then
Result := EncodeTime(Hour - 12, Minute, Second, MiliSecond)
else
Result := EncodeTime(Hour, Minute, Second, MiliSecond)
end;
procedure TCustomTimePicker.InitColumns;
begin
SetTimeToColumns(Time);
if HandleAllocated then
CalcSizes(ClientRect.Size);
end;
procedure TCustomTimePicker.ParseFormat(const Format: string);
const
TimeFormatRegExp = '(hh|h)|(nn|n)|(mm|m)|(ss|s)|(ampm)'; // do not localize
var
Match: TMatch;
Matches: TMatchCollection;
Value: string;
HourColumn: TPickerHourColumn;
MinuteColumn: TPickerMinuteColumn;
SecondColumn: TPickerSecondColumn;
AMPMColumn: TPickerAMPMColumn;
begin
FreeAndNil(FColumns);
FColumns := TObjectList<TPickerColumn>.Create(True);
Matches := TRegEx.Matches(Format, TimeFormatRegExp,
[roSingleLine, roIgnoreCase, roNotEmpty]);
FTimeProvider.UseAmPm := Pos('AM', UpperCase(Format)) > 0;
for Match in Matches do
begin
if not Match.Success then
Continue;
Value := Match.Value;
if Value.Length = 0 then
Continue;
case LowerCase(Value)[1] of
'h':
begin
HourColumn := TPickerHourColumn.Create(FTimeProvider);
HourColumn.HourFormat := Value;
FColumns.Add(HourColumn);
end;
'n', 'm':
begin
MinuteColumn := TPickerMinuteColumn.Create(FTimeProvider);
MinuteColumn.MinuteFormat := Value;
FColumns.Add(MinuteColumn);
end;
's':
begin
SecondColumn := TPickerSecondColumn.Create(FTimeProvider);
SecondColumn.SecondFormat := Value;
FColumns.Add(SecondColumn);
end;
'a':
begin
AMPMColumn := TPickerAMPMColumn.Create(FTimeProvider);
AMPMColumn.AMPMFormat := Value;
FColumns.Add(AMPMColumn);
end;
end;
end;
AdjustSize;
end;
procedure TCustomTimePicker.RejectDropDown;
begin
SetTimeToColumns(Time);
end;
procedure TCustomTimePicker.SetMinuteIncrement(Value: TMinuteIncrement);
begin
FTimeProvider.MinutesIncrement := Value;
end;
procedure TCustomTimePicker.SetTime(Value: TTime);
begin
if FTime = Value then
Exit;
FTime := Value;
DoOnChange;
SetTimeToColumns(FTime);
Invalidate;
end;
procedure TCustomTimePicker.SetTimeFormat(const Value: string);
begin
if FTimeFormat = Value then
Exit;
FTimeFormat := Value;
ParseFormat(FTimeFormat);
InitColumns;
Invalidate;
end;
procedure TCustomTimePicker.SetTimeToColumns(Value: TTime);
var
Column: TPickerColumn;
HourColumn: TPickerHourColumn absolute Column;
MinuteColumn: TPickerMinuteColumn absolute Column;
SecondColumn: TPickerSecondColumn absolute Column;
AMPMColumn: TPickerAMPMColumn absolute Column;
Hour, Minute, Second, MiliSecond: Word;
AM: Boolean;
begin
DecodeTime(Value, Hour, Minute, Second, MiliSecond);
AM := IsAM(Value);
if Assigned(FColumns) then
for Column in FColumns do
begin
if Column is TPickerHourColumn then
HourColumn.CurrentValue := Hour
else if Column is TPickerMinuteColumn then
MinuteColumn.CurrentValue := Minute
else if Column is TPickerAMPMColumn then
AMPMColumn.CurrentValue := Ord(not AM)
else if Column is TPickerSecondColumn then
SecondColumn.CurrentValue := Second;
end;
end;
{ TPickerViewInfo }
constructor TPickerViewInfo.Create;
begin
inherited;
FFont := TFont.Create;
end;
destructor TPickerViewInfo.Destroy;
begin
FreeAndNil(FFont);
inherited;
end;
procedure TPickerViewInfo.SetFont(Value: TFont);
begin
FFont.Assign(Value);
end;
{ TPickerOkCancelButtons }
constructor TPickerOkCancelButtons.Create;
begin
inherited;
FOkButton := TPickerButton.Create;
FOkButton.ButtonType := pbtOk;
FCancelButton := TPickerButton.Create;
FCancelButton.ButtonType := pbtCancel;
end;
destructor TPickerOkCancelButtons.Destroy;
begin
FreeAndNil(FOkButton);
FreeAndNil(FCancelButton);
inherited;
end;
procedure TPickerOkCancelButtons.Calculate(Rect: TRect; ItemHeight, BorderWidth: Integer);
var
BottomRect, CancelRect: TRect;
begin
BottomRect := Rect.SplitRect(srBottom, ItemHeight);
Bounds := BottomRect;
BottomRect.Inflate(-BorderWidth, -BorderWidth);
OkButton.BoundsRect := BottomRect.SplitRect(srLeft, 0.5);
CancelRect := BottomRect.SplitRect(srRight, 0.5);
CancelRect.Left := OkButton.BoundsRect.Right;
CancelButton.BoundsRect := CancelRect;
end;
{ TPickerButtonDrawInfo }
function TPickerButtonDrawInfo.GetButtonType: TPickerButtonType;
begin
Result := FButton.ButtonType;
end;
{ TPickerDrawerStyled }
function TPickerDrawerStyled.GetBorderColor(Hot, Pressed: Boolean): TColor;
begin
Result := inherited;
if not (seBorder in FPickerControl.StyleElements) then
Exit;
if Pressed or Hot then
Result := StyleServices.GetSystemColor(clHighlight)
else
Result := MiddleColor(StyleServices.GetSystemColor(clHighlight), StyleServices.GetSystemColor(clWindow));
end;
function TPickerDrawerStyled.GetButtonColor(Hot, Pressed: Boolean): TColor;
begin
Result := inherited;
if not(seClient in FPickerControl.StyleElements) then
Exit;
if Pressed then
Result := StyleServices.GetStyleColor(scButtonPressed)
else if Hot then
Result := StyleServices.GetStyleColor(scButtonHot)
else
Result := StyleServices.GetStyleColor(scButtonNormal)
end;
function TPickerDrawerStyled.GetButtonFontColor(Hot, Pressed: Boolean): TColor;
begin
Result := inherited;
if not(seClient in FPickerControl.StyleElements) then
Exit;
Result := StyleServices.GetSystemColor(clBtnText);
end;
function TPickerDrawerStyled.GetColor(Hot, Pressed, Enabled: Boolean): TColor;
begin
Result := inherited;
if not (seClient in FPickerControl.StyleElements) then
Exit;
Result := StyleServices.GetStyleColor(scEdit);
if not Enabled then
Result := MiddleColor(Result, StyleServices.GetSystemColor(clBtnFace));
end;
function TPickerDrawerStyled.GetFontColor: TColor;
begin
Result := inherited;
if seFont in FPickerControl.StyleElements then
Result := StyleServices.GetStyleFontColor(sfEditBoxTextNormal)
end;
function TPickerDrawerStyled.GetHighlightColor: TColor;
begin
Result := inherited;
if seClient in FPickerControl.StyleElements then
Result := StyleServices.GetSystemColor(clBtnHighlight);
end;
function TPickerDrawerStyled.GetPopupColor: TColor;
begin
Result := inherited;
if seClient in FPickerControl.StyleElements then
Result := StyleServices.GetStyleColor(scGrid);
end;
function TPickerDrawerStyled.GetSelectionColor: TColor;
begin
Result := inherited;
if not(seClient in FPickerControl.StyleElements) then
Exit;
Result := StyleServices.GetSystemColor(clHighlight);
end;
function TPickerDrawerStyled.GetSelectionFontColor: TColor;
begin
Result := inherited;
if not(seClient in FPickerControl.StyleElements) then
Exit;
Result := StyleServices.GetSystemColor(clHighlightText);
end;
function TPickerSecondColumn.GetCurrentValue: Integer;
begin
Result := SecondOf(ActualTime);
end;
function TPickerSecondColumn.GetMaxValue: Integer;
begin
Result := 59;
end;
function TPickerSecondColumn.GetMinValue: Integer;
begin
Result := 0;
end;
function TPickerSecondColumn.GetValueString(Value: Integer): string;
begin
Result := FormatDateTime(FSecondFormat, EncodeTime(HourOf(ActualTime), MinuteOf(ActualTime),
Value, MilliSecondOf(ActualTime)));
end;
procedure TPickerSecondColumn.SetCurrentValue(Value: Integer);
var
Hour, Minute, Second, MiliSecond: Word;
begin
DecodeTime(ActualTime, Hour, Minute, Second, MiliSecond);
if Value < GetMinValue then
Second := GetMinValue
else if Value > GetMaxValue then
Second := GetMaxValue
else
Second := Value;
ActualTime := EncodeTime(Hour, Minute, Second, MiliSecond);
end;
procedure TPickerSecondColumn.SetSecondFormat(const Value: string);
begin
FSecondFormat := Value;
end;
end.
|
unit ncgFormBase;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls;
type
TFormBaseGuard = class(TForm)
procedure FormCreate(Sender: TObject);
private
FDontForceForeground : Boolean;
{ Private declarations }
procedure OnMostrar(Sender: TObject);
procedure OnEsconder(Sender: TObject);
protected
public
{ Public declarations }
procedure OnTimerTop; virtual;
procedure Esconder; virtual;
procedure Mostrar;
property DontForceForeground: Boolean
read FDontForceForeground write FDontForceForeground;
end;
var
FormBaseGuard: TFormBaseGuard;
implementation
uses ncgFrmPri, ncDebug;
{$R *.dfm}
{ TFormBaseGuard }
function ForceForegroundWindow(hwnd: THandle; aFormName: String): boolean;
const
SPI_GETFOREGROUNDLOCKTIMEOUT = $2000;
SPI_SETFOREGROUNDLOCKTIMEOUT = $2001;
var
ForegroundThreadID: DWORD;
ThisThreadID : DWORD;
timeout : DWORD;
begin
DebugMsg('ForceForeGroundWindow - aFormName: '+aFormName);
if IsIconic(hwnd) then ShowWindow(hwnd, SW_RESTORE);
if GetForegroundWindow = hwnd then
Result := true
else begin
// Windows 98/2000 doesn't want to foreground a window when some other
// window has keyboard focus
if ((Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion > 4)) or
((Win32Platform = VER_PLATFORM_WIN32_WINDOWS) and
((Win32MajorVersion > 4) or ((Win32MajorVersion = 4) and
(Win32MinorVersion > 0)))) then
begin
// Code from Karl E. Peterson, www.mvps.org/vb/sample.htm
// Converted to Delphi by Ray Lischner
// Published in The Delphi Magazine 55, page 16
Result := false;
ForegroundThreadID := GetWindowThreadProcessID(GetForegroundWindow,nil);
ThisThreadID := GetWindowThreadPRocessId(hwnd,nil);
if AttachThreadInput(ThisThreadID, ForegroundThreadID, true) then
begin
BringWindowToTop(hwnd); // IE 5.5 related hack
SetForegroundWindow(hwnd);
AttachThreadInput(ThisThreadID, ForegroundThreadID, false);
Result := (GetForegroundWindow = hwnd);
end;
if not Result then begin
// Code by Daniel P. Stasinski
SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, @timeout, 0);
SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, TObject(0), SPIF_SENDCHANGE);
BringWindowToTop(hwnd); // IE 5.5 related hack
SetForegroundWindow(hWnd);
SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0,
TObject(timeout), SPIF_SENDCHANGE);
end;
end
else begin
BringWindowToTop(hwnd); // IE 5.5 related hack
SetForegroundWindow(hwnd);
end;
Result := (GetForegroundWindow = hwnd);
end;
end; { ForceForegroundWindow }
procedure TFormBaseGuard.Esconder;
begin
try
Hide;
except
on E: Exception do begin
DebugMsg('TFormBaseGuard.Esconder - Name: ' + Self.Name + ' - Exception: ' + E.Message);
with TTimer.Create(Self) do begin
Interval := 50;
OnTimer := OnEsconder;
Enabled := True;
end;
end;
end;
end;
procedure TFormBaseGuard.FormCreate(Sender: TObject);
begin
FDontForceForeground := False;
end;
procedure TFormBaseGuard.Mostrar;
var H: HWND;
begin
try
DebugMsg('TFormBaseGuard.Mostrar - Form ' + Name);
Show;
ForceForegroundWindow(Handle, 'TFormBaseGuard.Mostrar - ' + Name);
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, (SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE));
{ H := GetForeGroundWindow;
ShowWindow(Handle, SW_SHOW);
if (H <> Handle) and (H <> FindWindow('Shell_TrayWnd', nil)) then begin
keybd_event(VK_LWIN, Mapvirtualkey(VK_LWIN, 0), 0, 0);
keybd_event(VK_LWIN, Mapvirtualkey(VK_LWIN, 0), KEYEVENTF_KEYUP, 0);
keybd_event(VK_CONTROL, Mapvirtualkey(VK_CONTROL, 0), 0, 0);
keybd_event(VK_ESCAPE, Mapvirtualkey(VK_ESCAPE, 0), 0, 0);
keybd_event(VK_ESCAPE, Mapvirtualkey(VK_ESCAPE, 0), KEYEVENTF_KEYUP, 0);
keybd_event(VK_CONTROL, Mapvirtualkey(VK_CONTROL, 0), KEYEVENTF_KEYUP, 0);
SetForegroundWindow(Handle);
end; }
except
on E: Exception do begin
DebugMsg('TFormBaseGuard.Mostrar - Name: ' + Self.Name + ' - Exception: ' + E.Message);
with TTimer.Create(Self) do begin
Interval := 50;
OnTimer := OnMostrar;
Enabled := True;
end;
end;
end;
end;
procedure TFormBaseGuard.OnEsconder(Sender: TObject);
begin
try
Hide;
finally
Sender.Free;
end;
end;
procedure TFormBaseGuard.OnMostrar(Sender: TObject);
begin
try
Show;
finally
Sender.Free;
end;
end;
procedure TFormBaseGuard.OnTimerTop;
begin
end;
end.
procedure DoCreate;
begin
try
inherited
finally
Tradução;
end;
end;
if Assigned(FOnCreate) then
try
FOnCreate(Self);
except
if not HandleCreateException then
raise;
end;
if fsVisible in FFormState then Visible := True;
end;
|
unit fODMedIV;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fODBase, Grids, StdCtrls, ORCtrls, ComCtrls, ExtCtrls, Buttons, Menus, IdGlobal, strUtils,
VA508AccessibilityManager, VAUtils, fIVRoutes;
type
TfrmODMedIV = class(TfrmODBase)
VA508CompOrderSig: TVA508ComponentAccessibility;
VA508CompRoute: TVA508ComponentAccessibility;
VA508CompType: TVA508ComponentAccessibility;
VA508CompSchedule: TVA508ComponentAccessibility;
VA508CompGrdSelected: TVA508ComponentAccessibility;
pnlTop: TGridPanel;
pnlTopRightTop: TPanel;
pnlTopRightLbls: TPanel;
lblAmount: TLabel;
lblComponent: TLabel;
lblAddFreq: TLabel;
lblPrevAddFreq: TLabel;
grdSelected: TCaptionStringGrid;
txtSelected: TCaptionEdit;
cboSelected: TCaptionComboBox;
cboAddFreq: TCaptionComboBox;
pgctrlSolutionsAndAdditives: TPageControl;
tbshtSolutions: TTabSheet;
tbshtAdditives: TTabSheet;
cboAdditive: TORComboBox;
cboSolution: TORComboBox;
cmdRemove: TButton;
pnlComments: TPanel;
lblComments: TLabel;
memComments: TCaptionMemo;
lblRoute: TLabel;
txtAllIVRoutes: TLabel;
lblType: TLabel;
lblTypeHelp: TLabel;
lblSchedule: TLabel;
txtNSS: TLabel;
lblInfusionRate: TLabel;
cboRoute: TORComboBox;
cboType: TComboBox;
cboSchedule: TORComboBox;
chkPRN: TCheckBox;
txtRate: TCaptionEdit;
cboInfusionTime: TComboBox;
lblPriority: TLabel;
lblLimit: TLabel;
cboPriority: TORComboBox;
txtXDuration: TCaptionEdit;
cboDuration: TComboBox;
lblFirstDose: TVA508StaticText;
lblAdminTime: TVA508StaticText;
chkDoseNow: TCheckBox;
lbl508Required: TVA508StaticText;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure tabFluidChange(Sender: TObject);
procedure cboAdditiveNeedData(Sender: TObject; const StartFrom: string; Direction,
InsertAt: Integer);
procedure cboSolutionNeedData(Sender: TObject; const StartFrom: string; Direction,
InsertAt: Integer);
procedure cboAdditiveMouseClick(Sender: TObject);
procedure cboAdditiveExit(Sender: TObject);
procedure cboSolutionMouseClick(Sender: TObject);
procedure cboSolutionExit(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure cmdRemoveClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure txtSelectedExit(Sender: TObject);
procedure ControlChange(Sender: TObject);
procedure txtSelectedChange(Sender: TObject);
procedure grdSelectedDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect;
State: TGridDrawState);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure grdSelectedKeyPress(Sender: TObject; var Key: Char);
procedure grdSelectedMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure txtXDurationChange(Sender: TObject);
procedure pnlXDurationEnter(Sender: TObject);
procedure txtXDurationExit(Sender: TObject);
procedure cboScheduleChange(Sender: TObject);
procedure cboTypeChange(Sender: TObject);
procedure cboRouteChange(Sender: TObject);
procedure txtRateChange(Sender: TObject);
procedure cboPriorityChange(Sender: TObject);
procedure cboPriorityExit(Sender: TObject);
procedure cboRouteExit(Sender: TObject);
procedure txtNSSClick(Sender: TObject);
procedure cboScheduleClick(Sender: TObject);
procedure chkPRNClick(Sender: TObject);
procedure chkDoseNowClick(Sender: TObject);
procedure loadExpectFirstDose;
procedure SetSchedule(const x: string);
procedure cboScheduleExit(Sender: TObject);
procedure cboInfusionTimeChange(Sender: TObject);
procedure cboDurationChange(Sender: TObject);
procedure cboDurationEnter(Sender: TObject);
procedure cboInfusionTimeEnter(Sender: TObject);
procedure txtAllIVRoutesClick(Sender: TObject);
procedure cboRouteClick(Sender: TObject);
procedure lblTypeHelpClick(Sender: TObject);
procedure cboSelectedCloseUp(Sender: TObject);
procedure cboRouteKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure cboScheduleKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cboPriorityKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cboAddFreqKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cboAddFreqCloseUp(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure txtSelectedKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cboSelectedKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cboTypeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cboRouteKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cboScheduleKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure VA508CompOrderSigStateQuery(Sender: TObject; var Text: string);
procedure VA508CompRouteInstructionsQuery(Sender: TObject;
var Text: string);
procedure VA508CompTypeInstructionsQuery(Sender: TObject; var Text: string);
procedure VA508CompScheduleInstructionsQuery(Sender: TObject;
var Text: string);
procedure VA508CompGrdSelectedCaptionQuery(Sender: TObject;
var Text: string);
procedure ScrollBox1Resize(Sender: TObject);
private
FInpatient: Boolean;
FNSSAdminTime: string;
FNSSScheduleType: string;
OSolIEN: integer;
OAddIEN: integer;
OSchedule: string;
oAdmin: string;
OrderIEN: string;
FAdminTimeText: string;
JAWSON: boolean;
FOriginalDurationType: integer;
FOriginalInfusionType: integer;
FIVTypeDefined: boolean;
//FInitialOrderID: boolean;
procedure SetValuesFromResponses;
procedure DoSetFontSize( FontSize: integer);
procedure ClickOnGridCell(keypressed: Char);
procedure SetLimitationControl(aValue: string);
function CreateOtherSchedule: string;
function CreateOtherRoute: string;
procedure UpdateRoute;
procedure DisplayDoseNow(Status: boolean);
procedure UpdateDuration(SchType: string);
procedure ClearAllFields;
function UpdateAddFreq(OI: integer): string;
function IsAltCtrl_L_Pressed(Shift : TShiftState; Key : Word) : Boolean;
procedure SetCtrlAlt_L_LabelAccessText(var Text: string; theLabel : TLabel);
public
OrdAction: integer;
procedure InitDialog; override;
procedure SetupDialog(OrderAction: Integer; const ID: string); override;
procedure Validate(var AnErrMsg: string); override;
procedure SetFontSize( FontSize: integer); override;
function ValidateInfusionRate(Rate: string): string;
function IVTypeHelpText: string;
property NSSAdminTime: string read FNSSAdminTime write FNSSAdminTime;
property NSSScheduleType: string read FNSSScheduleType write FNSSScheduleType;
end;
var
frmODMedIV: TfrmODMedIV;
implementation
{$R *.DFM}
uses ORFn, uConst, rODMeds, rODBase, fFrame, uCore, fOtherSchedule, rCore;
const
TX_NO_DEA = 'Provider must have a DEA# or VA# to order this medication';
TC_NO_DEA = 'DEA# Required';
type
TIVComponent = class
private
IEN: Integer;
Name: string;
Fluid: Char;
Amount: Integer;
Units: string;
Volumes: string;
AddFreq: string;
end;
const
TC_RESTRICT = 'Ordering Restrictions';
TX_NO_BASE = 'A solution must be selected.';
TX_NO_AMOUNT = 'A valid strength or volume must be entered for ';
TX_NO_UNITS = 'Units must be entered for ';
TX_NO_RATE = 'An infusion rate must be entered.';
//TX_BAD_RATE = 'The infusion rate must be: # ml/hr or text@labels per day';
TX_BAD_RATE = 'Infusion rate can only be up to 4 digits long or' + CRLF + 'Infusion rate must be # ml/hr or text@labels per day';
TX_NO_INFUSION_TIME = 'An Infusion length must be entered or the Unit of Time for the Infuse Over Time field needs to be cleared out.';
TX_NO_SCHEDULE = 'A schedule is required for an intermittent order.';
TX_BAD_SCHEDULE = 'Unable to resolve non-standard schedule.';
TX_NO_INFUSION_UNIT = 'Invalid Unit of Time, select either "Minutes" or "Hours" for the Infusion Length';
TX_BAD_ROUTE = 'Route cannot be free-text';
TX_LEADING_NUMERIC = 'this additive must start with a leading numeric value';
TX_BAD_BAG = 'A valid additive frequency must be entered for ';
Tx_BAG_NO_COMMENTS ='"See Comments" entered for additive ';
TX_BAG_NO_COMMENTS1 = ' no comments defined for this order.';
(*
{ TIVComponent methods }
procedure TIVComponent.Clear;
begin
IEN := 0;
Name := '';
Fluid := #0;
Amount := 0;
Units := '';
Volumes := '';
end;
*)
{ Form methods }
procedure TfrmODMedIV.FormCreate(Sender: TObject);
//Reduce flicker
procedure ReplicatePreferences(c: TComponent);
var
X: Integer;
begin
if c is TListBox then
exit;
if (c is TWinControl) then
begin
TWinControl(c).DoubleBuffered := true;
end;
if (c is TPanel) then
begin
TPanel(c).FullRepaint := false;
end;
if c.ComponentCount > 0 then
begin
for X := (c.ComponentCount - 1) downto 0 do
ReplicatePreferences(c.Components[X]);
end;
end;
var
Restriction: string;
begin
frmFrame.pnlVisit.Enabled := false;
AutoSizeDisabled := true;
inherited;
AllowQuickOrder := True;
if dlgFormId = OD_CLINICINF then self.Caption := 'Clinic Infusion Orders';
CheckAuthForMeds(Restriction);
if Length(Restriction) > 0 then
begin
InfoBox(Restriction, TC_RESTRICT, MB_OK);
Close;
Exit;
end;
OrdAction := -1;
DoSetFontSize(MainFontSize);
FillerID := 'PSIV'; // does 'on Display' order check **KCM**
StatusText('Loading Dialog Definition');
if dlgFormId = OD_CLINICINF then Responses.Dialog := 'CLINIC OR PAT FLUID OE'
else Responses.Dialog := 'PSJI OR PAT FLUID OE'; // loads formatting info
StatusText('Loading Default Values');
CtrlInits.LoadDefaults(ODForIVFluids); // ODForIVFluids returns TStrings with defaults
InitDialog;
// Set special font colors and sizes
txtAllIVRoutes.Font.Color := clBlue;
txtAllIVRoutes.Font.Size := txtAllIVRoutes.Font.Size - 2;
lblTypeHelp.Font.Color := clBlue;
lblTypeHelp.Font.Size := lblTypeHelp.Font.Size - 2;
txtNSS.Font.Color := clBlue;
txtNSS.Font.Size := txtNSS.Font.Size - 2;
// Move inherited controls onto the TGridPanel
pnlTop.ControlCollection.BeginUpdate;
try
pnlTop.ControlCollection.AddControl(memOrder, 0, 14);
pnlTop.ControlCollection.ControlItems[0, 14].ColumnSpan := 8;
pnlTop.ControlCollection.ControlItems[0, 14].RowSpan := 3;
memOrder.Parent := pnlTop;
memOrder.Align := alClient;
pnlTop.ControlCollection.AddControl(cmdAccept, 8, 15);
cmdAccept.Parent := pnlTop;
cmdAccept.Align := alBottom;
pnlTop.ControlCollection.AddControl(cmdQuit, 8, 16);
cmdQuit.Parent := pnlTop;
cmdQuit.Align := alBottom;
finally
pnlTop.ControlCollection.EndUpdate;
end;
pnlTop.Align := alClient;
end;
procedure TfrmODMedIV.FormDestroy(Sender: TObject);
var
i: Integer;
begin
with grdSelected do for i := 0 to RowCount - 1 do TIVComponent(Objects[0, i]).Free;
inherited;
frmFrame.pnlVisit.Enabled := True;
end;
procedure TfrmODMedIV.FormResize(Sender: TObject);
var
isNewOrder: boolean;
addFreqLeft : integer;
begin
inherited;
if OrdAction in [ORDER_COPY, ORDER_EDIT] then isNewOrder := false
else isNewOrder := True;
with grdSelected do
begin
ColWidths[1] := Canvas.TextWidth(' 10000 ') + GetSystemMetrics(SM_CXVSCROLL);
ColWidths[2] := Canvas.TextWidth('meq.') + GetSystemMetrics(SM_CXVSCROLL);
//AGP ADDITIVE FREQUENCY CHANGES
ColWidths[3] := Canvas.TextWidth(lblAddFreq.Caption + ' ') + GetSystemMetrics(SM_CXVSCROLL);
if IsNewOrder = false then
begin
ColWidths[4] := Canvas.TextWidth(lblPrevAddFreq.Caption) + GetSystemMetrics(SM_CXVSCROLL);
ColWidths[0] := ClientWidth - ColWidths[1] - ColWidths[2] - ColWidths[3] - ColWidths[4] - 5;
end
else
begin
ColWidths[4] := 0;
ColWidths[0] := ClientWidth - ColWidths[1] - ColWidths[2] - ColWidths[3] - ColWidths[4] - 25;
end;
end;
lblAmount.Left := grdSelected.Left + grdSelected.ColWidths[0];
lblAddFreq.Left := grdSelected.Left + grdSelected.ColWidths[0] + grdSelected.ColWidths[1] + grdSelected.ColWidths[2];
addFreqLeft := lblAmount.Left + Canvas.TextWidth(lblAmount.Caption + ' ');
if addFreqLeft > lblAddFreq.Left then lblAddFreq.Left := addFreqLeft;
if isNewOrder = false then
begin
lblPrevAddFreq.Visible := True;
lblPrevAddFreq.Left := grdSelected.Left + grdSelected.ColWidths[0] + grdSelected.ColWidths[1] + grdSelected.ColWidths[2] + grdSelected.ColWidths[3];
end
else lblPrevAddFreq.Visible := False;
self.cboType.SelLength := 0;
self.cboInfusionTime.SelLength := 0;
self.cboDuration.SelLength := 0;
end;
{ TfrmODBase overrides }
procedure TfrmODMedIV.InitDialog;
const
NOSELECTION: TGridRect = (Left: -1; Top: -1; Right: -1; Bottom: -1);
var
i: Integer;
begin
inherited;
//grdSelected.Selection := NOSELECTION;
//FRouteConflict := False;
//lblTypeHelp.Hint := IVTypeHelpText;
ClearAllFields;
//FIVTypeDefined := false;
lblType.Hint := IVTypeHelpText;
cboType.Hint := IVTYpeHelpText;
with grdSelected do for i := 0 to RowCount - 1 do
begin
TIVComponent(Objects[0, i]).Free;
Rows[i].Clear;
end;
grdSelected.RowCount := 1;
//txtRate.Text := ' ml/hr'; {*kcm*}
with CtrlInits do
begin
SetControl(cboSolution, 'ShortList');
cboSolution.InsertSeparator;
SetControl(cboPriority, 'Priorities');
cboType.Items.Clear;
cboType.Items.Add('Continuous');
cboType.Items.Add('Intermittent');
cboType.ItemIndex := -1;
cboType.SelLength := 0;
//SetControl(cboRoute, 'Route');
if (cboRoute.ItemIndex = -1) and (cboRoute.Text <> '') then cboRoute.Text := '';
//SetControl(cboSchedule, 'Schedules');
LoadSchedules(cboSchedule.Items, patient.Inpatient);
//if (Patient.Inpatient) and (cboSchedule.Items.IndexOfName('Other')<0) then
if cboSchedule.Items.IndexOf('Other') = -1 then cboSchedule.Items.Add('OTHER');
cboSchedule.Enabled := False;
lblschedule.Enabled := False;
if cboInfusionTime.Items.Count = 0 then
begin
cboInfusionTime.Items.add('Minutes');
cboInfusionTime.Items.Add('Hours');
end;
cboInfusionTime.Enabled := false;
updateDuration('');
if cboDuration.Items.Count = 0 then
begin
cboDuration.Items.Add('L');
cboDuration.Items.Add('ml');
cboDuration.Items.Add('days');
cboDuration.Items.Add('hours');
end;
cboDuration.ItemIndex := -1;
cboDuration.Text := '';
if self.txtXDuration.Text <> '' then self.txtXDuration.Text := '';
txtNSS.Visible := false;
if (chkDoseNow.Visible = true) and (chkDoseNow.Checked = true) then chkDoseNow.Checked := false;
chkDoseNow.Visible := false;
chkPRN.Enabled := false;
//AGP ADDITIVE FREQUENCY CHANGES
if cboAddFreq.Items.Count = 0 then
begin
cboAddFreq.Items.Add('1 Bag/Day');
cboAddFreq.Items.Add('All Bags');
cboAddFreq.Items.Add('See Comments');
end;
end;
pgctrlSolutionsAndAdditives.ActivePage := tbshtSolutions;
// tabFluid.TabIndex := 0;
// tabFluidChange(Self); // this makes cboSolution visible
cboSolution.InitLongList('');
cboAdditive.InitLongList('');
JAWSON := true;
if ScreenReaderActive = false then
begin
lblAdminTime.TabStop := false;
lblFirstDose.TabStop := false;
memOrder.TabStop := false;
JAWSON := false;
end;
ActiveControl := cboSolution; //SetFocusedControl(cboSolution);
StatusText('');
OSolIEN := 0;
OAddIEN := 0;
OSchedule := '';
oAdmin := '';
self.txtAllIVRoutes.Visible := false;
memorder.text := '';
memOrder.Lines.Clear;
end;
function TfrmODMedIV.IVTypeHelpText: string;
begin
result := 'Continuous Type:' + CRLF + ' IV’s that run at a specified “Rate” ( __ml/hr, __mcg/kg/min, etc)' +
CRLF + CRLF + 'Intermittent Type:' + CRLF +
' IV’s administered at scheduled intervals (Q4H, QDay) or One-Time only, ' +
CRLF + ' “over a specified time period” (e.g. “Infuse over 30 min.”).' + CRLF + CRLF +
'Examples:' + CRLF + 'Continuous = Infusion/drip' + CRLF + 'Intermittent = IVP/IVPB';
end;
procedure TfrmODMedIV.ScrollBox1Resize(Sender: TObject);
begin
// inherited;
// ScrollBox1.OnResize := nil;
// //At least minimum
// if (pnlForm.Width < MinFormWidth) or (pnlForm.Height < MinFormHeight) then
// pnlForm.Align := alNone;
// pnlForm.AutoSize := false;
// if (pnlForm.Width < MinFormWidth) then pnlForm.Width := MinFormWidth;
// if pnlForm.Height < MinFormHeight then pnlForm.Height := MinFormHeight;
//
//
// if (ScrollBox1.Width >= MinFormWidth) then
// begin
// if (ScrollBox1.Height >= (MinFormHeight)) then
// begin
// pnlForm.Align := alClient;
// end else begin
// pnlForm.Align := alTop;
// pnlForm.AutoSize := true;
// end;
// end else begin
// if (ScrollBox1.Height >= (MinFormHeight)) then
// begin
// pnlForm.Align := alNone;
// pnlForm.Top := 0;
// pnlForm.Left := 0;
// pnlForm.AutoSize := false;
// pnlForm.Width := MinFormWidth;
// pnlForm.height := ScrollBox1.Height;
// end else begin
// pnlForm.Align := alNone;
// pnlForm.Top := 0;
// pnlForm.Left := 0;
// pnlForm.AutoSize := true;
// end;
// end;
//
// {
// if ScrollBox1.Height >= (MinFormHeight + 5) then
// begin
// pnlForm.Align := alClient;
// end else
// if (ScrollBox1.Width < MinFormWidth) then
// begin
//
// pnlForm.Align := alNone;
// pnlForm.Top := 0;
// pnlForm.Left := 0;
// pnlForm.autosize := false;
// if pnlForm.Width < MinFormWidth then
// pnlForm.Width := MinFormWidth;
//
// if pnlForm.height < MinFormHeight then
// pnlForm.height := MinFormHeight
// end else
// begin
// pnlForm.Align := alTop;
// pnlForm.AutoSize := true;
// end;
// Caption := IntToStr(ScrollBox1.Width); }
// ScrollBox1.OnResize := ScrollBox1Resize;
end;
procedure TfrmODMedIV.SetCtrlAlt_L_LabelAccessText(var Text: string; theLabel : TLabel);
begin
if theLabel.Visible then
Text := 'Press Ctrl + Alt + L to access ' + theLabel.Caption;
end;
procedure TfrmODMedIV.lblTypeHelpClick(Sender: TObject);
var
str: string;
begin
inherited;
str := IVTypeHelpText;
infoBox(str, 'Informational Help Text', MB_OK);
end;
procedure TfrmODMedIV.loadExpectFirstDose;
var
i: integer;
AnIVComponent: TIVComponent;
fAddIEN, fSolIEN, Interval, idx: integer;
AdminTime: TFMDateTime;
Admin, Duration, ShowText, SchTxt, SchType, IVType: string;
doseNow, calFirstDose: boolean;
begin
idx := self.cboSchedule.ItemIndex;
IVType := self.cboType.Items.Strings[self.cboType.itemindex];
if idx = -1 then
begin
if IVType = 'Continuous' then
begin
self.lblFirstDose.Caption := '';
self.lblFirstDose.Visible := false;
end;
exit;
end;
doseNow := true;
SchType := Piece(self.cboSchedule.Items.Strings[idx],U,3);
if self.EvtID > 0 then doseNow := false;
if (IVType = 'Continuous') or ((idx > -1) and ((SchType = 'P') or (SchType = 'O') or (SchType = 'OC')) or
(self.chkPRN.Checked = True)) then
begin
self.lblFirstDose.Caption := '';
self.lblAdminTime.Caption := '';
self.lblFirstDose.Visible := false;
self.lblAdminTime.Visible := false;
self.lblAdminTime.TabStop := false;
self.lblFirstDose.TabStop := false;
if (self.cboType.Text = 'Continuous') or (Piece(self.cboSchedule.Items.Strings[idx],U,3) = 'O') then doseNow := false;
if chkDoseNow.Checked = true then lblFirstDose.Visible := false;
if idx > -1 then oSchedule := Piece(self.cboSchedule.Items.Strings[idx],U,1);
if (self.chkPRN.Checked = True) and (idx > -1) and (LeftStr(Piece(self.cboSchedule.Items.Strings[idx],U,1),3)<> 'PRN') then
OSchedule := Piece(self.cboSchedule.Items.Strings[idx],U,1) + ' PRN';
DisplayDoseNow(doseNow);
exit;
// end;
end
else if SchType <> 'O' then
begin
self.lblAdminTime.Visible := true;
if FAdminTimeText <> '' then self.lblAdminTime.Caption := 'Admin. Time: ' + FAdminTimeText
else if Piece(self.cboSchedule.Items[idx],U,4) <> '' then
self.lblAdminTime.Caption := 'Admin. Time: ' + Piece(self.cboSchedule.Items[idx],U,4)
else self.lblAdminTime.Caption := 'Admin. Time: Not Defined';
end;
DisplayDoseNow(doseNow);
if chkDoseNow.Checked = true then
begin
lblFirstDose.Visible := false;
Exit;
end;
self.lblFirstDose.Visible := True;
fSolIEN := 0;
fAddIEN := 0;
for i := 0 to self.grdSelected.RowCount - 1 do
begin
AniVComponent := TIVComponent(self.grdSelected.Objects[0, i]);
if AnIVComponent = nil then Continue;
if (AnIVComponent.Fluid = 'B') and (fSolIEN = 0) then fSolIEN := AnIVComponent.IEN;
if (AnIVComponent.Fluid = 'A') and (fAddIEN = 0) then fAddIEN := AnIVComponent.IEN;
if (fSolIEN > 0) and (fAddIEN > 0) then break;
end;
SchTxt := self.cboSchedule.Text;
Admin := '';
if (self.lblAdminTime.visible = True) and (self.lblAdminTime.Caption <> '') then
begin
Admin := Copy(self.lblAdminTime.Caption, 14, (Length(self.lblAdminTime.Caption)-1));
if not CharInSet(Admin[1], ['0'..'9']) then Admin := '';
end;
if (fSolIEN = oSolIEN) and (fAddIEN = oAddIEN) and (OSchedule = SchTxt) and (oAdmin = Admin) then CalFirstDose := false
else
begin
CalFirstDose := True;
oSolIEN := fSolIEN;
oAddIEN := fAddIEN;
oSchedule := SchTxt;
oAdmin := Admin;
end;
if CalFirstDose = True then
begin
if fAddIEN > 0 then LoadAdminInfo(';' + schTxt, fAddIEN, ShowText, AdminTime, Duration, Admin)
else LoadAdminInfo(';' + schTxt, fSolIEN, ShowText, AdminTime, Duration, Admin);
if AdminTime > 0 then
begin
ShowText := 'Expected First Dose: ';
Interval := Trunc(FMDateTimeToDateTime(AdminTime) - FMDateTimeToDateTime(FMToday));
case Interval of
0: ShowText := ShowText + 'TODAY ' + FormatFMDateTime('(mmm dd, yy) at hh:nn', AdminTime);
1: ShowText := ShowText + 'TOMORROW ' + FormatFMDateTime('(mmm dd, yy) at hh:nn', AdminTime);
else ShowText := ShowText + FormatFMDateTime('mmm dd, yy at hh:nn', AdminTime);
end;
end;
self.lblFirstDose.Caption := ShowText;
end;
if (self.lblFirstDose.Visible = true) and (self.lblFirstDose.Caption <> '') and (JAWSON = true) then self.lblFirstDose.TabStop := true
else self.lblFirstDose.TabStop := false;
if (self.lblAdminTime.Visible = true) and (self.lblAdminTime.Caption <> '') and (JAWSON = true) then self.lblAdminTime.TabStop := true
else self.lblAdminTime.TabStop := false;
end;
procedure TfrmODMedIV.VA508CompRouteInstructionsQuery(
Sender: TObject; var Text: string);
begin
inherited;
SetCtrlAlt_L_LabelAccessText(Text, txtAllIVRoutes);
end;
procedure TfrmODMedIV.VA508CompScheduleInstructionsQuery(Sender: TObject;
var Text: string);
begin
inherited;
SetCtrlAlt_L_LabelAccessText(Text, txtNSS);
end;
procedure TfrmODMedIV.VA508CompTypeInstructionsQuery(Sender: TObject;
var Text: string);
begin
inherited;
SetCtrlAlt_L_LabelAccessText(Text, lblTypeHelp);
end;
procedure TfrmODMedIV.VA508CompGrdSelectedCaptionQuery(Sender: TObject;
var Text: string);
begin
inherited;
if grdSelected.Col = 0 then
Text := lblComponent.Caption
else if grdSelected.Col = 1 then
Text := lblAmount.Caption
else if grdSelected.Col = 2 then
Text := lblAmount.Caption + ', Unit'
else if grdSelected.Col = 3 then
Text := lblAddFreq.Caption
else if grdSelected.Col = 4 then
Text := lblPrevAddFreq.Caption;
end;
procedure TfrmODMedIV.VA508CompOrderSigStateQuery(Sender: TObject;
var Text: string);
begin
inherited;
Text := memOrder.Text;
end;
procedure TfrmODMedIV.Validate(var AnErrMsg: string);
var
DispWarning, ItemOK, Result: Boolean;
LDec,RDec,x, tempStr, iunit, infError, Bag: string;
digits, i, j, k, Len, temp, Value: Integer;
procedure SetError(const x: string);
begin
if Length(AnErrMsg) > 0 then AnErrMsg := AnErrMsg + CRLF;
AnErrMsg := AnErrMsg + x;
end;
begin
inherited;
with grdSelected do
begin
ItemOK := False;
for i := 0 to RowCount - 1 do
begin
for k := i to RowCount - 1 do
if not(k = i) and (TIVComponent(Objects[0, k]).IEN = TIVComponent(Objects[0, i]).IEN) then
begin
SetError('Duplicate Orderable Items included for '+TIVComponent(Objects[0, k]).Name+'.');
break;
end;
if (Objects[0,i] <> nil) and (TIVComponent(Objects[0, i]).Fluid = 'B') then ItemOK := True;
end;
if (not ItemOK) and ((self.cboType.ItemIndex = -1) or (MixedCase(self.cboType.Items.Strings[self.cboType.ItemIndex]) = 'Continuous')) then
SetError(TX_NO_BASE);
for i := 0 to RowCount - 1 do
begin
if (Objects[0, i] <> nil) and ((Length(Cells[1, i]) = 0) or (StrToFloat(Cells[1,i])=0))
then SetError(TX_NO_AMOUNT + Cells[0, i]);
if (Objects[0, i] <> nil) and (Length(Cells[2, i]) = 0)
then SetError(TX_NO_UNITS + Cells[0, i]);
if (Objects[0,i] <> nil) and (TIVComponent(Objects[0, i]).Fluid = 'A') then
begin
temp := Pos('.', Cells[1, i]);
if temp > 0 then
begin
tempStr := Cells[1, i];
if temp = 1 then
begin
SetError(cells[0, i] + TX_LEADING_NUMERIC);
Exit;
end;
for j := 1 to temp -1 do if not CharInSet(tempStr[j], ['0'..'9']) then
begin
SetError(cells[0, i] + TX_LEADING_NUMERIC);
Exit;
end;
end;
//AGP ADDITIVE FREQUENCY CHANGES
if MixedCase(self.cboType.Items.Strings[self.cboType.ItemIndex]) = 'Continuous' then
begin
Bag := (Cells[3, i]);
if Length(Bag) = 0 then
begin
SetError(TX_BAD_BAG + cells[0, i]);
end
else if cboAddFreq.Items.IndexOf(Bag) = -1 then
begin
SetError(TX_BAD_BAG + cells[0, i]);
end
else if (MixedCase(Bag) = 'See Comments') and ((self.memComments.Text = '') or (self.memComments.Text = CRLF)) then
begin
SetError(Tx_BAG_NO_COMMENTS + cells[0,i] + Tx_BAG_NO_COMMENTS1);
end;
end;
end;
end;
end;
if Pos(U, self.memComments.Text) > 0 then SetError('Comments cannot contain a "^".');
if cboSchedule.ItemIndex > -1 then updateDuration(Piece(cboSchedule.Items.Strings[cboSchedule.itemIndex], U, 3));
if self.cboPriority.Text = '' then SetError('Priority is required');
if (cboRoute.ItemIndex = -1) and (cboRoute.Text <> '') then SetError(TX_BAD_ROUTE);
if (cboRoute.ItemIndex > -1) and (cboRoute.ItemIndex = cboRoute.Items.IndexOf('OTHER')) then
SetError('A valid route must be selected');
if self.cboRoute.Text = '' then SetError('Route is required');
if (self.txtXDuration.Text <> '') and (self.cboduration.Items.IndexOf(SELF.cboDuration.Text) = -1) then
SetError('A valid duration type is required');
if (self.txtXDuration.Text = '') and (self.cboduration.Items.IndexOf(SELF.cboDuration.Text) > -1) then
SetError('Cannot have a duration type without a duration value');
if self.cboType.ItemIndex = -1 then
begin
SetError('IV Type is required');
Exit;
end;
if MixedCase(self.cboType.Items.Strings[self.cboType.ItemIndex]) = 'Continuous' then
begin
if Length(txtRate.Text) = 0 then SetError(TX_NO_RATE) else
begin
x := Trim(txtRate.Text);
if pos('@', X) > 0 then
begin
LDec := Piece(x, '@', 1);
RDec := Piece(x, '@', 2);
if (Length(RDec) = 0) or (Length(RDec) > 2) then x := '';
end
else if Pos('.',X)>0 then
begin
LDec := Piece(x, '.', 1);
RDec := Piece(x, '.', 2);
if Length(LDec) = 0 then SetError('Infusion Rate required a leading numeric value');
if Length(RDec) > 1 then SetError('Infusion Rate cannot exceed one decimal place');
end
else if LeftStr(txtRate.Text, 1) = '0' then
SetError('Infusion Rate cannot start with a zero.');
if ( Pos('@',x)=0) then
begin
if (Length(x) > 4) then
begin
seterror(TX_BAD_RATE);
exit;
end;
for i := 1 to Length(x) do
begin
if not CharInSet(x[i], ['0'..'9']) and (x[i] <> '.') then
begin
SetError(TX_BAD_RATE);
exit;
end;
end;
end;
if (pos('ml/hr', X) = 0) and (Length(x) > 0) and (pos('@', X) = 0) then X := X + ' ml/hr';
if Length(x) = 0 then SetError(TX_BAD_RATE) else Responses.Update('RATE', 1, x, x);
end;
if cboduration.text = 'doses' then SetError('Continuous Orders cannot have "doses" as a duration type');
end
else if MixedCase(self.cboType.Items.Strings[self.cboType.ItemIndex]) = 'Intermittent' then
begin
if (cboInfusionTime.ItemIndex = -1) and (txtRate.Text <> '') then SetError(TX_NO_INFUSION_UNIT);
if (txtRate.Text = '') and (cboInfusionTime.ItemIndex > -1) then SetError(TX_NO_INFUSION_TIME);
if (txtRate.Text <> '') then
begin
infError := '';
InfError := ValidateInfusionRate(txtRate.Text);
if infError <> '' then SetError(InfError);
Len := Length(txtRate.Text);
iunit := MixedCase(self.cboInfusionTime.Items.Strings[cboInfusionTime.ItemIndex]);
if (iunit = 'Minutes') and (Len > 4) then setError('Infuse Over Time cannot exceed 4 spaces for ' + iunit)
else if (iunit = 'Hours') and (Len > 2) then setError('Infuse Over Time cannot exceed 2 spaces for ' + iunit);
end;
if (cboSchedule.ItemIndex = -1) and (cboSchedule.Text = '') and (chkPRN.Checked = false) then SetError(TX_NO_SCHEDULE);
if (cboSchedule.ItemIndex > -1) and (cboSchedule.Text = '') then
begin
cboSchedule.ItemIndex := -1;
SetError(TX_NO_SCHEDULE)
end;
if (cboSchedule.ItemIndex = -1) and (cboSchedule.Text <> '') then SetError(TX_BAD_SCHEDULE);
end;
if txtXDuration.Text = '' then
begin
if AnErrMsg = '' then exit;
//if AnErrMsg = '' then self.FInitialOrderID := True;
//exit;
end;
Len := Length(txtXDuration.Text);
if LeftStr(txtXDuration.Text,1) <> '.' then
begin
DispWarning := false;
Digits := 2;
if cboDuration.text = 'ml' then digits := 4;
if ((cboDuration.text = 'days') or (cboDuration.text = 'hours')) and (Len > digits) then
DispWarning := true
else if (cboduration.text = 'ml') and (Len > digits) then DispWarning := true
else if (cboduration.text = 'L') and (Len > digits) and (Pos('.',txtXDuration.Text) = 0) then DispWarning := True;
if DispWarning = true then SetError('Duration for ' + cboduration.text + ' cannot be greater than ' + InttoStr(digits) + ' digits.');
end;
if (Pos('.', txtXDuration.Text)>0) then
begin
SetError('Invalid Duration, please enter a whole numbers for a duration.');
end
else if LeftStr(txtXDuration.text, 1) = '0' then
SetError('Duration cannot start with a zero.');
if (cboduration.text = 'doses') then
begin
if TryStrToInt(txtXDuration.Text, Value) = false then
SetError('Duration with a unit of "doses" must be a whole number between 0 and 2000000')
else if (Value < 0) or (Value > 2000000) then
SetError('Duration with a unit of "doses" must be greater then 0 and less then 2000000');
end;
//if AnErrMsg = '' then self.FInitialOrderID := True;
end;
function TFrmODMedIV.ValidateInfusionRate(Rate: string): string;
var
Temp: Boolean;
i: integer;
begin
Temp := False;
if Pos('.',Rate) >0 then
begin
Result := 'Infuse Over Time can only be a whole number';
exit;
end
else if LeftStr(Rate, 1) = '0' then Result := 'Infuse Over Time cannot start with a zero.';
for i := 1 to Length(Rate) do if not CharInSet(Rate[i], ['0'..'9']) then Temp := True;
if Temp = True then Result := 'The Infusion time can only be a whole number';
end;
procedure TfrmODMedIV.SetValuesFromResponses;
var
x, addRoute, tempSch, AdminTime, TempOrder, tmpSch, tempIRoute, tempRoute, PreAddFreq, DEAFailStr, TX_INFO: string;
AnInstance, i, idx, j: Integer;
AResponse, AddFreqResp: TResponse;
AnIVComponent: TIVComponent;
AllIVRoute: TStringList;
PQO: boolean;
begin
Changing := True;
//self.FInitialOrderID := false;
with Responses do
begin
SetControl(cboType, 'TYPE', 1);
if cboType.ItemIndex > -1 then FIVTypeDefined := True;
FInpatient := OrderForInpatient;
AnInstance := NextInstance('ORDERABLE', 0);
while AnInstance > 0 do
begin
AResponse := FindResponseByName('ORDERABLE', AnInstance);
if AResponse <> nil then
begin
x := AmountsForIVFluid(StrToIntDef(AResponse.IValue, 0), 'B');
AnIVComponent := TIVComponent.Create;
AnIVComponent.IEN := StrToIntDef(AResponse.IValue, 0);
DEAFailStr := '';
if not FInpatient then
begin
DEAFailStr := DEACheckFailedForIVOnOutPatient(AnIVComponent.IEN,'S');
while StrToIntDef(Piece(DEAFailStr,U,1),0) in [1..6] do
begin
case StrToIntDef(Piece(DEAFailStr,U,1),0) of
1: TX_INFO := TX_DEAFAIL; //prescriber has an invalid or no DEA#
2: TX_INFO := TX_SCHFAIL + Piece(DEAFailStr,U,2) + '.'; //prescriber has no schedule privileges in 2,2N,3,3N,4, or 5
3: TX_INFO := TX_NO_DETOX; //prescriber has an invalid or no Detox#
4: TX_INFO := TX_EXP_DEA1 + Piece(DEAFailStr,U,2) + TX_EXP_DEA2; //prescriber's DEA# expired and no VA# is assigned
5: TX_INFO := TX_EXP_DETOX1 + Piece(DEAFailStr,U,2) + TX_EXP_DETOX2; //valid detox#, but expired DEA#
6: TX_INFO := TX_SCH_ONE; //schedule 1's are prohibited from electronic prescription
end;
if StrToIntDef(Piece(DEAFailStr,U,1),0)=6 then
begin
InfoBox(TX_INFO, TC_DEAFAIL, MB_OK);
cboAdditive.Text := '';
AbortOrder := True;
Exit;
end;
if InfoBox(TX_INFO + TX_INSTRUCT, TC_DEAFAIL, MB_RETRYCANCEL) = IDRETRY then
begin
DEAContext := True;
fFrame.frmFrame.mnuFileEncounterClick(self);
DEAFailStr := '';
DEAFailStr := DEACheckFailedForIVOnOutPatient(AnIVComponent.IEN,'S');
end
else
begin
cboAdditive.Text := '';
AbortOrder := True;
Exit;
end;
end
end else
begin
DEAFailStr := DEACheckFailed(AnIVComponent.IEN, FInpatient);
while StrToIntDef(Piece(DEAFailStr,U,1),0) in [1..6] do
begin
case StrToIntDef(Piece(DEAFailStr,U,1),0) of
1: TX_INFO := TX_DEAFAIL; //prescriber has an invalid or no DEA#
2: TX_INFO := TX_SCHFAIL + Piece(DEAFailStr,U,2) + '.'; //prescriber has no schedule privileges in 2,2N,3,3N,4, or 5
3: TX_INFO := TX_NO_DETOX; //prescriber has an invalid or no Detox#
4: TX_INFO := TX_EXP_DEA1 + Piece(DEAFailStr,U,2) + TX_EXP_DEA2; //prescriber's DEA# expired and no VA# is assigned
5: TX_INFO := TX_EXP_DETOX1 + Piece(DEAFailStr,U,2) + TX_EXP_DETOX2; //valid detox#, but expired DEA#
6: TX_INFO := TX_SCH_ONE; //schedule 1's are prohibited from electronic prescription
end;
if StrToIntDef(Piece(DEAFailStr,U,1),0)=6 then
begin
InfoBox(TX_INFO, TC_DEAFAIL, MB_OK);
cboAdditive.Text := '';
AbortOrder := True;
Exit;
end;
if InfoBox(TX_INFO + TX_INSTRUCT, TC_DEAFAIL, MB_RETRYCANCEL) = IDRETRY then
begin
DEAContext := True;
fFrame.frmFrame.mnuFileEncounterClick(self);
DEAFailStr := '';
DEAFailStr := DEACheckFailed(AnIVComponent.IEN, FInpatient);
end
else
begin
cboAdditive.Text := '';
AbortOrder := True;
Exit;
end;
end
end;
AnIVComponent.Name := AResponse.EValue;
AnIVComponent.Fluid := 'B';
AnIVComponent.Amount := StrToIntDef(Piece(x, U, 2), 0);
AnIVComponent.Units := Piece(x, U, 1);
AnIVComponent.Volumes := Copy(x, Pos(U, x) + 1, Length(x));
with grdSelected do
begin
if Objects[0, RowCount - 1] <> nil then RowCount := RowCount + 1;
Objects[0, RowCount - 1] := AnIVComponent;
Cells[0, RowCount - 1] := AnIVComponent.Name;
if AnIVComponent.Amount <> 0 then
Cells[1, RowCount - 1] := IntToStr(AnIVComponent.Amount);
Cells[2, RowCount - 1] := AnIVComponent.Units;
Cells[3, RowCount - 1] := 'N/A';
end;
end;
AResponse := FindResponseByName('VOLUME', AnInstance);
if AResponse <> nil then with grdSelected do Cells[1, RowCount - 1] := AResponse.EValue;
AnInstance := NextInstance('ORDERABLE', AnInstance);
end; {while AnInstance - ORDERABLE}
AnInstance := NextInstance('ADDITIVE', 0);
while AnInstance > 0 do
begin
AResponse := FindResponseByName('ADDITIVE', AnInstance);
if AResponse <> nil then
begin
x := AmountsForIVFluid(StrToIntDef(AResponse.IValue, 0), 'A');
AnIVComponent := TIVComponent.Create;
AnIVComponent.IEN := StrToIntDef(AResponse.IValue, 0);
DEAFailStr := '';
if not FInpatient then
begin
DEAFailStr := DEACheckFailedForIVOnOutPatient(AnIVComponent.IEN,'A');
while StrToIntDef(Piece(DEAFailStr,U,1),0) in [1..6] do
begin
case StrToIntDef(Piece(DEAFailStr,U,1),0) of
1: TX_INFO := TX_DEAFAIL; //prescriber has an invalid or no DEA#
2: TX_INFO := TX_SCHFAIL + Piece(DEAFailStr,U,2) + '.'; //prescriber has no schedule privileges in 2,2N,3,3N,4, or 5
3: TX_INFO := TX_NO_DETOX; //prescriber has an invalid or no Detox#
4: TX_INFO := TX_EXP_DEA1 + Piece(DEAFailStr,U,2) + TX_EXP_DEA2; //prescriber's DEA# expired and no VA# is assigned
5: TX_INFO := TX_EXP_DETOX1 + Piece(DEAFailStr,U,2) + TX_EXP_DETOX2; //valid detox#, but expired DEA#
6: TX_INFO := TX_SCH_ONE; //schedule 1's are prohibited from electronic prescription
end;
if StrToIntDef(Piece(DEAFailStr,U,1),0)=6 then
begin
InfoBox(TX_INFO, TC_DEAFAIL, MB_OK);
cboAdditive.Text := '';
AbortOrder := True;
Exit;
end;
if InfoBox(TX_INFO + TX_INSTRUCT, TC_DEAFAIL, MB_RETRYCANCEL) = IDRETRY then
begin
DEAContext := True;
fFrame.frmFrame.mnuFileEncounterClick(self);
DEAFailStr := '';
DEAFailStr := DEACheckFailedForIVOnOutPatient(AnIVComponent.IEN,'A');
end
else
begin
cboAdditive.Text := '';
AbortOrder := True;
Exit;
end;
end
end else
begin
DEAFailStr := DEACheckFailed(AnIVComponent.IEN, FInpatient);
while StrToIntDef(Piece(DEAFailStr,U,1),0) in [1..6] do
begin
case StrToIntDef(Piece(DEAFailStr,U,1),0) of
1: TX_INFO := TX_DEAFAIL; //prescriber has an invalid or no DEA#
2: TX_INFO := TX_SCHFAIL + Piece(DEAFailStr,U,2) + '.'; //prescriber has no schedule privileges in 2,2N,3,3N,4, or 5
3: TX_INFO := TX_NO_DETOX; //prescriber has an invalid or no Detox#
4: TX_INFO := TX_EXP_DEA1 + Piece(DEAFailStr,U,2) + TX_EXP_DEA2; //prescriber's DEA# expired and no VA# is assigned
5: TX_INFO := TX_EXP_DETOX1 + Piece(DEAFailStr,U,2) + TX_EXP_DETOX2; //valid detox#, but expired DEA#
6: TX_INFO := TX_SCH_ONE; //schedule 1's are prohibited from electronic prescription
end;
if StrToIntDef(Piece(DEAFailStr,U,1),0)=6 then
begin
InfoBox(TX_INFO, TC_DEAFAIL, MB_OK);
cboAdditive.Text := '';
AbortOrder := True;
Exit;
end;
if InfoBox(TX_INFO + TX_INSTRUCT, TC_DEAFAIL, MB_RETRYCANCEL) = IDRETRY then
begin
DEAContext := True;
fFrame.frmFrame.mnuFileEncounterClick(self);
DEAFailStr := '';
DEAFailStr := DEACheckFailed(AnIVComponent.IEN, FInpatient);
end
else
begin
cboAdditive.Text := '';
AbortOrder := True;
Exit;
end;
end
end;
AnIVComponent.Name := AResponse.EValue;
AnIVComponent.Fluid := 'A';
AnIVComponent.Amount := StrToIntDef(Piece(x, U, 2), 0);
AnIVComponent.Units := Piece(x, U, 1);
AnIVComponent.Volumes := Copy(x, Pos(U, x) + 1, Length(x));
//AGP ADDITIVE FREQUENCY CHANGES
AnIVComponent.AddFreq := '';
PreAddFreq := '';
AddFreqResp := FindResponseByName('ADDFREQ', AnInstance);
if AddFreqResp <> nil then
begin
if cboAddFreq.Items.IndexOf(AddFreqResp.IValue) = -1 then
begin
AnIvComponent.AddFreq := '';
end
else AnIvComponent.AddFreq := AddFreqResp.IValue;
PreAddFreq := AddFreqResp.IValue;
end;
with grdSelected do
begin
if Objects[0, RowCount - 1] <> nil then RowCount := RowCount + 1;
Objects[0, RowCount - 1] := AnIVComponent;
Cells[0, RowCount - 1] := AnIVComponent.Name;
if AnIVComponent.Amount <> 0 then
Cells[1, RowCount - 1] := IntToStr(AnIVComponent.Amount);
Cells[2, RowCount - 1] := AnIVComponent.Units;
Cells[3, RowCount -1] := AnIVComponent.AddFreq;
if OrdAction in [ORDER_COPY, ORDER_EDIT] then Cells[4, RowCount -1] := PreAddFreq;
end;
end;
AResponse := FindResponseByName('STRENGTH', AnInstance);
if AResponse <> nil then with grdSelected do Cells[1, RowCount - 1] := AResponse.EValue;
AResponse := FindResponseByName('UNITS', AnInstance);
if AResponse <> nil then with grdSelected do Cells[2, RowCount - 1] := AResponse.EValue;
AnInstance := NextInstance('ADDITIVE', AnInstance);
end; {while AnInstance - ADDITIVE}
SetControl(cboType, 'TYPE', 1);
if self.grdSelected.RowCount > 0 then self.txtAllIVRoutes.Visible := True;
updateRoute;
AResponse := FindResponseByName('ROUTE', 1);
if AResponse <> nil then
begin
tempRoute := AResponse.EValue;
if tempRoute <> '' then
begin
idx := self.cboRoute.Items.IndexOf(tempRoute);
if idx > -1 then self.cboRoute.ItemIndex := idx
else begin
tempIRoute := AResponse.IValue;
if tempIRoute <> '' then
begin
AllIVRoute := TStringList.Create;
LoadAllIVRoutes(AllIVRoute);
idx := -1;
for i := 0 to AllIVRoute.Count - 1 do
begin
if Piece(AllIVRoute.Strings[i], U, 1) = tempIRoute then
begin
idx := i;
break;
end;
end;
if idx > -1 then
begin
self.cboRoute.Items.Add(AllIVRoute.Strings[idx]);
idx := self.cboRoute.Items.IndexOf(tempRoute);
if idx > -1 then self.cboRoute.ItemIndex := idx;
end;
AllIVRoute.Free;
//if Pos(U, tempIRoute) = 0 then tempIRoute := tempIRoute + U + tempRoute;
//self.cboRoute.Items.Add(tempIRoute);
//idx := self.cboRoute.Items.IndexOf(tempRoute);
//if idx > -1 then self.cboRoute.ItemIndex := idx;
end;
end;
end;
end;
//SetControl(cboRoute, 'ROUTE', 1);
if (cboRoute.ItemIndex = -1) and (cboRoute.Text <> '') then cboRoute.Text := '';
if self.cboType.Text = 'Intermittent' then
begin
lblInfusionRate.Caption := 'Infuse Over Time (Optional)';
lblSchedule.Enabled := True;
cboschedule.Enabled := True;
//if popDuration.Items.IndexOf(popDoses) = -1 then popDuration.Items.Add(popDoses);
if cboDuration.Items.IndexOf('doses') = -1 then cboDuration.Items.Add('doses');
txtNss.Visible := true;
chkDoseNow.Visible := true;
chkPRN.Enabled := True;
tempSch := '';
AdminTime := '';
AResponse := FindResponseByName('SCHEDULE', 1);
if AResponse <> nil then tempSch := AResponse.EValue;
lblAdminTime.Visible := True;
lblAdminTime.Hint := AdminTimeHelpText;
lblAdminTime.ShowHint := True;
//Add in Dose Now Checkbox
SetControl(chkDoseNow, 'NOW', 1);
//AResponse := Responses.FindResponseByName('ADMIN', 1);
//if AResponse <> nil then AdminTime := AResponse.EValue;
//if Action = Order_Copy then FOriginalAdminTime := AdminTime;
SetSchedule(tempSch);
//if (cboSchedule.ItemIndex > -1) then lblAdminTime.Caption := 'Admin. Time: ' + Piece(cboSchedule.Items.strings[cboSchedule.itemindex],U,5);
//if (cboSchedule.ItemIndex > -1) and (Piece(lblAdminTime.Caption, ':' ,2) = ' ') then lblAdminTime.Caption := 'Admin. Time: ' + AdminTime;
if (OrdAction in [ORDER_COPY, ORDER_EDIT]) then
begin
TempOrder := Piece(OrderIEN,';',1);
TempOrder := Copy(tempOrder, 2, Length(tempOrder));
if DifferentOrderLocations(tempOrder, Patient.Location) = false then
begin
AResponse := Responses.FindResponseByName('ADMIN', 1);
if AResponse <> nil then AdminTime := AResponse.EValue;
//lblAdminTime.Caption := 'Admin. Time: ' + AdminTime;
if (cboSchedule.ItemIndex > -1) and (AdminTime <> '') then
begin
tmpSch := cboSchedule.Items.Strings[cboSchedule.itemindex];
setPiece(tmpSch,U,4,AdminTime);
cboSchedule.Items.Strings[cboSchedule.ItemIndex] := tmpSch;
end;
end;
end;
//if Piece(lblAdminTime.Caption, ':' ,2) = ' ' then lblAdminTime.Caption := 'Admin. Time: Not Defined';
SetControl(txtRate, 'RATE', 1);
cboInfusionTime.Enabled := true;
PQO := false;
if Pos('INFUSE OVER',UpperCase(txtRate.Text)) > 0 then
begin
txtRate.Text := Copy(txtRate.Text,Length('Infuse over ')+1,Length(txtRate.text));
PQO := True;
end;
if Pos('MINUTE',UpperCase(txtRate.Text))>0 then
begin
cboInfusionTime.Text := 'Minutes';
cboInfusionTime.itemindex := 0;
//txtRate.Text := Copy(txtRate.Text,Length('Infuse over ')+1,Length(txtRate.text));
txtRate.Text := Copy(txtRate.Text, 1, Length(txtRate.Text) - 8);
end
else if Pos('HOUR',UpperCase(txtRate.Text))>0 then
begin
cboInfusionTime.Text := 'Hours';
cboInfusionTime.ItemIndex := 1;
//txtRate.Text := Copy(txtRate.Text,Length('Infuse over ')+1,Length(txtRate.text));
txtRate.Text := Copy(txtRate.Text, 1, Length(txtRate.Text) - 6);
end
else if (txtRate.Text <> '') and (PQO = false) and (ValidateInfusionRate(txtRate.Text) ='') then
begin
cboInfusionTime.Text := 'Minutes';
cboInfusionTime.itemindex := 0;
end;
For j := 0 to grdSelected.RowCount -1 do
grdSelected.Cells[3,j] := 'N/A';
end
else
begin
lblSchedule.Enabled := false;
cboSchedule.ItemIndex := -1;
cboSchedule.Enabled := false;
if chkDoseNow.Visible = true then chkDoseNow.Checked := false;
chkDoseNow.Visible := false;
txtNSS.Visible := false;
cboInfusionTime.ItemIndex := -1;
cboInfusionTime.Text := '';
cboInfusionTime.Enabled := false;
chkPRN.Checked := false;
chkPRN.Enabled := false;
txtRate.Text := '';
cboDuration.ItemIndex := -1;
cboDuration.Text := '';
txtXDuration.Text := '';
SetControl(txtRate, 'RATE', 1);
if LowerCase(Copy(ReverseStr(txtRate.Text), 1, 6)) = 'rh/lm ' {*kcm*}
then txtRate.Text := Copy(txtRate.Text, 1, Length(txtRate.Text) - 6);
end;
SetControl(cboPriority, 'URGENCY', 1);
SetControl(memComments, 'COMMENT', 1);
AnInstance := NextInstance('DAYS', 0);
if AnInstance > 0 then
begin
AResponse := FindResponseByName('DAYS', AnInstance);
if AResponse <> nil then
SetLimitationControl(AResponse.EValue);
end;
end; {if...with Responses}
Changing := False;
if self.cboSchedule.ItemIndex > -1 then updateDuration(Piece(cboSchedule.Items.Strings[cboSchedule.itemindex],U,3));
loadExpectFirstDose;
ControlChange(Self);
end;
procedure TfrmODMedIV.SetupDialog(OrderAction: Integer; const ID: string);
begin
inherited;
OrdAction := OrderAction;
OrderIEN := id;
//self.FInitialOrderID := True;
if self.EvtID > 0 then FAdminTimeText := 'To Be Determined';
// if isIMO = true then self.Caption := 'Clinic ' + self.Caption;
if (isIMO) or ((patient.Inpatient = true) and (encounter.Location <> patient.Location)) and (FAdminTimeText = '') then
FAdminTimeText := 'Not defined for Clinic Locations';
if OrderAction in [ORDER_COPY, ORDER_EDIT, ORDER_QUICK] then
begin
SetValuesFromResponses;
end;
end;
{ tabFluid events }
procedure TfrmODMedIV.tabFluidChange(Sender: TObject);
begin
// inherited;
// case TabFluid.TabIndex of
// 0: begin
// cboSolution.Visible := True;
// cboAdditive.Visible := False;
// end;
// 1: begin
// cboAdditive.Visible := True;
// cboSolution.Visible := False;
// end;
// end;
// if cboSolution.Visible then
// ActiveControl := cboSolution;
// if cboAdditive.Visible then
// ActiveControl := cboAdditive;
if pgctrlSolutionsAndAdditives.ActivePage = tbshtSolutions then
ActiveControl := cboSolution
else
ActiveControl := cboAdditive;
end;
{ cboSolution events }
procedure TfrmODMedIV.cboSolutionNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
begin
cboSolution.ForDataUse(SubSetOfOrderItems(StartFrom, Direction, 'S.IVB RX', Responses.QuickOrder));
end;
procedure TfrmODMedIV.cbotypeChange(Sender: TObject);
var
i: integer;
begin
inherited;
//if (self.cbotype.Text = 'Intermittent') or (self.cboType.itemIndex = 1) then
if (self.cboType.itemIndex = 1) then
begin
cboSchedule.ItemIndex := -1;
lblAdminTime.Caption := '';
lblAdminTime.Visible := false;
lblschedule.Enabled := True;
cboSchedule.Enabled := True;
txtNSS.Visible := true;
chkDoseNow.Checked := false;
chkDoseNow.Visible := true;
chkPRN.Checked := false;
chkPRN.Enabled := True;
lblInfusionRate.Caption := 'Infuse Over Time (Optional)';
cboInfusionTime.Enabled := true;
if cboDuration.items.IndexOf('doses') = -1 then cboDuration.Items.Add('doses');
//AGP ADDITIVE FREQUECNY CHANGES
lblAddFreq.Caption := 'Additive Frequency';
for i := 0 to grdselected.RowCount - 1 do
begin
if (TIVComponent(grdselected.Objects[0, i]) <> nil) and (TIVComponent(grdselected.Objects[0, i]).Fluid = 'A') then
begin
grdSelected.Cells[3, i] := 'N/A';
end;
end;
end
//else if (self.cbotype.Text = 'Continuous') or (self.cboType.itemIndex = 0) then
else
begin
lblschedule.Enabled := False;
cboSchedule.ItemIndex := -1;
cboSchedule.Enabled := False;
txtNSS.Visible := false;
chkPRN.Checked := false;
chkPRN.Enabled := false;
if chkDoseNow.Visible = true then chkDoseNow.Checked := false;
chkDoseNow.Visible := false;
lblInfusionRate.Caption := 'Infusion Rate (ml/hr)*';
cboInfusionTime.ItemIndex := -1;
cboInfusionTime.Text := '';
cboInfusionTime.Enabled := false;
lblAdminTime.Visible := false;
updateDuration('');
cboduration.Items.Delete(cboDuration.Items.IndexOf('doses'));
lblAddFreq.Caption := 'Additive Frequency*';
if FIVTypeDefined = True then
begin
for i := 0 to grdselected.RowCount - 1 do
begin
if (TIVComponent(grdselected.Objects[0, i]) <> nil) and (TIVComponent(grdselected.Objects[0, i]).Fluid = 'A') then
begin
grdSelected.Cells[3, i] := '';
end;
end;
end;
end;
FIVTypeDefined := True;
self.txtRate.Text := '';
ControlChange(Sender);
end;
procedure TfrmODMedIV.cboTypeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if IsAltCtrl_L_Pressed(Shift, Key) then
lblTypeHelpClick(lblTypeHelp);
end;
function TfrmODMedIV.IsAltCtrl_L_Pressed(Shift : TShiftState; Key : Word) : Boolean;
begin
Result := (ssCtrl in Shift) and (ssAlt in Shift) and (Key = Ord('L'));
end;
procedure TfrmODMedIV.chkDoseNowClick(Sender: TObject);
Const
T = '"';
T1 = 'By checking the "Give additional dose now" box, you have actually entered two orders for the same medication.';
T2 = #13#13'The first order''s administrative schedule is "';
T3 = #13'The second order''s administrative schedule is "';
T4 = #13#13'Do you want to continue?';
T5 = '" and a priority of "';
T1A = 'By checking the "Give additional dose now" box, you have actually entered a new order with the schedule "NOW"';
T2A = ' in addition to the one you are placing for the same medication.';
var
medNm: string;
theSch: string;
ordPriority: string;
//SchID: integer;
begin
inherited;
if (chkDoseNow.Checked) then
begin
medNm := 'Test';
//SchID := cboSchedule.ItemIndex;
theSch := cboSchedule.Text;
ordPriority := cboPriority.SelText;
if length(theSch)>0 then
begin
//if (InfoBox(T1+medNm+T+T2+theSch+T+T3+'NOW"'+T4, 'Warning', MB_OKCANCEL or MB_ICONWARNING) = IDCANCEL)then
//if (InfoBox(T1+T2+theSch+T+T3+'NOW"'+T4, 'Warning', MB_OKCANCEL or MB_ICONWARNING) = IDCANCEL)then
if (InfoBox(T1+T2+'NOW'+T5+ordPriority+T+T3+theSch+T5+ordPriority+T+T4, 'Warning', MB_OKCANCEL or MB_ICONWARNING) = IDCANCEL)then
begin
chkDoseNow.Checked := False;
Exit;
end;
end else
begin
//if InfoBox(T1A+T2A+medNm+T+T4, 'Warning', MB_OKCANCEL or MB_ICONWARNING) = IDCANCEL then
if InfoBox(T1A+T2A+T4, 'Warning', MB_OKCANCEL or MB_ICONWARNING) = IDCANCEL then
begin
chkDoseNow.Checked := False;
Exit;
end;
end;
end;
ControlChange(self);
end;
procedure TfrmODMedIV.chkPRNClick(Sender: TObject);
begin
inherited;
ControlChange(Self);
end;
procedure TfrmODMedIV.cboSolutionMouseClick(Sender: TObject);
var
AnIVComponent: TIVComponent;
x,routeIEN, DEAFailStr, TX_INFO: string;
i: integer;
begin
inherited;
if CharAt(cboSolution.ItemID, 1) = 'Q' then // setup quick order
begin
//Clear pre-existing values
for i := 0 to self.grdSelected.RowCount do
begin
if self.grdSelected.Objects[0,i] <> nil then
begin
TIVComponent(self.grdSelected.Objects[0,i]).Free;
self.grdSelected.Rows[i].Clear;
end
else self.grdSelected.Rows[i].clear;
end;
self.grdSelected.RowCount := 0;
ControlChange(Sender);
Responses.QuickOrder := ExtractInteger(cboSolution.ItemID);
SetValuesFromResponses;
cboSolution.ItemIndex := -1;
Exit;
end;
if cboSolution.ItemIEN <= 0 then Exit; // process selection of solution
FInpatient := OrderForInpatient;
DEAFailStr := '';
if not FInpatient then
begin
DEAFailStr := DEACheckFailedForIVOnOutPatient(cboSolution.ItemIEN,'S');
while StrToIntDef(Piece(DEAFailStr,U,1),0) in [1..6] do
begin
case StrToIntDef(Piece(DEAFailStr,U,1),0) of
1: TX_INFO := TX_DEAFAIL; //prescriber has an invalid or no DEA#
2: TX_INFO := TX_SCHFAIL + Piece(DEAFailStr,U,2) + '.'; //prescriber has no schedule privileges in 2,2N,3,3N,4, or 5
3: TX_INFO := TX_NO_DETOX; //prescriber has an invalid or no Detox#
4: TX_INFO := TX_EXP_DEA1 + Piece(DEAFailStr,U,2) + TX_EXP_DEA2; //prescriber's DEA# expired and no VA# is assigned
5: TX_INFO := TX_EXP_DETOX1 + Piece(DEAFailStr,U,2) + TX_EXP_DETOX2; //valid detox#, but expired DEA#
6: TX_INFO := TX_SCH_ONE; //schedule 1's are prohibited from electronic prescription
end;
if StrToIntDef(Piece(DEAFailStr,U,1),0)=6 then
begin
InfoBox(TX_INFO, TC_DEAFAIL, MB_OK);
cboSolution.Text := '';
Exit;
end;
if InfoBox(TX_INFO + TX_INSTRUCT, TC_DEAFAIL, MB_RETRYCANCEL) = IDRETRY then
begin
DEAContext := True;
fFrame.frmFrame.mnuFileEncounterClick(self);
DEAFailStr := '';
DEAFailStr := DEACheckFailedForIVOnOutPatient(cboSolution.ItemIEN,'S');
end
else
begin
cboSolution.Text := '';
Exit;
end;
end
end else
begin
DEAFailStr := DEACheckFailed(cboSolution.ItemIEN, FInpatient);
while StrToIntDef(Piece(DEAFailStr,U,1),0) in [1..6] do
begin
case StrToIntDef(Piece(DEAFailStr,U,1),0) of
1: TX_INFO := TX_DEAFAIL; //prescriber has an invalid or no DEA#
2: TX_INFO := TX_SCHFAIL + Piece(DEAFailStr,U,2) + '.'; //prescriber has no schedule privileges in 2,2N,3,3N,4, or 5
3: TX_INFO := TX_NO_DETOX; //prescriber has an invalid or no Detox#
4: TX_INFO := TX_EXP_DEA1 + Piece(DEAFailStr,U,2) + TX_EXP_DEA2; //prescriber's DEA# expired and no VA# is assigned
5: TX_INFO := TX_EXP_DETOX1 + Piece(DEAFailStr,U,2) + TX_EXP_DETOX2; //valid detox#, but expired DEA#
6: TX_INFO := TX_SCH_ONE; //schedule 1's are prohibited from electronic prescription
end;
if StrToIntDef(Piece(DEAFailStr,U,1),0)=6 then
begin
InfoBox(TX_INFO, TC_DEAFAIL, MB_OK);
cboSolution.Text := '';
Exit;
end;
if InfoBox(TX_INFO + TX_INSTRUCT, TC_DEAFAIL, MB_RETRYCANCEL) = IDRETRY then
begin
DEAContext := True;
fFrame.frmFrame.mnuFileEncounterClick(self);
DEAFailStr := '';
DEAFailStr := DEACheckFailed(cboSolution.ItemIEN, FInpatient);
end
else
begin
cboSolution.Text := '';
Exit;
end;
end
end;
RouteIEN := Piece(cboSolution.Items.Strings[cboSolution.itemindex],U,4);
x := AmountsForIVFluid(cboSolution.ItemIEN, 'B');
AnIVComponent := TIVComponent.Create;
AnIVComponent.IEN := cboSolution.ItemIEN;
AnIVComponent.Name := Piece(cboSolution.Items[cboSolution.ItemIndex], U, 3);
AnIVComponent.Fluid := 'B';
AnIVComponent.Amount := StrToIntDef(Piece(x, U, 2), 0);
AnIVComponent.Units := Piece(x, U, 1);
AnIVComponent.Volumes := Copy(x, Pos(U, x) + 1, Length(x));
cboSolution.ItemIndex := -1;
with grdSelected do
begin
if Objects[0, RowCount - 1] <> nil then RowCount := RowCount + 1;
Objects[0, RowCount - 1] := AnIVComponent;
Cells[0, RowCount - 1] := AnIVComponent.Name;
Cells[1, RowCount - 1] := IntToStr(AnIVComponent.Amount);
Cells[2, RowCount - 1] := AnIVComponent.Units;
Cells[3, RowCount - 1] := 'N/A';
Row := RowCount - 1;
if Length(Piece(AnIVComponent.Volumes, U, 2)) > 0 then Col := 1 else Col := 0;
(* if RowCount = 1 then // switch to additives after 1st IV
begin
tabFluid.TabIndex := 1;
tabFluidChange(Self);
end; *)
end;
Application.ProcessMessages; //CQ: 10157
updateRoute;
ClickOnGridCell(#0);
//updateRoute;
ControlChange(Sender);
//updateRoute(routeIEN);
end;
procedure TfrmODMedIV.cboSolutionExit(Sender: TObject);
begin
inherited;
if EnterIsPressed then //CQ: 15097
if (cboSolution.ItemIEN > 0) or
((cboSolution.ItemIEN = 0) and (CharAt(cboSolution.ItemID, 1) = 'Q')) then
cboSolutionMouseClick(Self);
end;
{ cboAdditive events }
procedure TfrmODMedIV.cboAdditiveNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
begin
cboAdditive.ForDataUse(SubSetOfOrderItems(StartFrom, Direction, 'S.IVA RX', Responses.QuickOrder));
end;
procedure TfrmODMedIV.cboAddFreqCloseUp(Sender: TObject);
begin
inherited;
with cboAddFreq do
begin
if tag < 0 then exit;
grdSelected.Cells[Tag div 256, Tag mod 256] := MixedCase(items.Strings[itemindex]);
Tag := -1;
Hide;
ControlChange(Sender);
TControl(self.grdSelected).Enabled := True;
ActiveControl := self.grdSelected;
end;
grdSelected.Refresh;
end;
procedure TfrmODMedIV.cboAddFreqKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (Key = VK_RETURN) or (Key = VK_Tab) then
begin
cboAddFreqCloseUp(cboAddFreq);
Key := 0;
end;
end;
procedure TfrmODMedIV.cboDurationChange(Sender: TObject);
Var
ItemCount, i : Integer;
begin
//Overwrite the auto complete to need characters up to the first unique character of the selection
//Loop through the items and see it we have multiple possibilites
ItemCount := 0;
For i := 0 to cboDuration.Items.Count - 1 do begin
If Pos(Uppercase(cboDuration.Text), Uppercase(Copy(cboDuration.Items[i], 1, Length(cboDuration.Text)))) > 0 then
Inc(ItemCount);
end;
//We have finally found the unique value so select it
If ItemCount = 1 then begin
For i := 0 to cboDuration.Items.Count - 1 do begin
If Pos(Uppercase(cboDuration.Text), Uppercase(Copy(cboDuration.Items[i], 1, Length(cboDuration.Text)))) > 0 then begin
cboDuration.ItemIndex := i;
break;
end;
end;
end;
inherited;
if (FOriginalDurationType > -1) and (FOriginalDurationType <> cboDuration.ItemIndex) then
begin
self.txtXDuration.Text := '';
FOriginalDurationType := cboDuration.ItemIndex;
end;
if (FOriginalDurationType = -1) and (cboDuration.ItemIndex > -1) then FOriginalDurationType := cboDuration.ItemIndex;
controlchange(sender);
end;
procedure TfrmODMedIV.cboDurationEnter(Sender: TObject);
begin
inherited;
FOriginalDurationType := cboDuration.ItemIndex;
end;
procedure TfrmODMedIV.cboInfusionTimeChange(Sender: TObject);
begin
inherited;
if (FOriginalInfusionType > -1) and (FOriginalInfusionType <> cboInfusionTime.ItemIndex) then
begin
self.txtRate.Text := '';
FOriginalInfusionType := cboInfusionTime.ItemIndex;
end;
if (FOriginalInfusionType = -1) and (cboInfusionTime.ItemIndex > -1) then FOriginalInfusionType := cboInfusionTime.ItemIndex;
ControlChange(Sender);
end;
procedure TfrmODMedIV.cboInfusionTimeEnter(Sender: TObject);
begin
inherited;
FOriginalInfusionType := self.cboInfusionTime.ItemIndex;
end;
procedure TfrmODMedIV.cboPriorityChange(Sender: TObject);
begin
inherited;
ControlChange(sender);
end;
procedure TfrmODMedIV.cboPriorityExit(Sender: TObject);
begin
inherited;
if cboPriority.Text = '' then
begin
infoBox('Priority must have a value assigned to it', 'Warning', MB_OK);
cboPriority.SetFocus;
end;
end;
procedure TfrmODMedIV.cboPriorityKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (Key = VK_BACK) and (cboPriority.Text = '') then cboPriority.ItemIndex := -1;
end;
procedure TfrmODMedIV.cboRouteChange(Sender: TObject);
begin
inherited;
if cboRoute.ItemIndex = cboRoute.Items.IndexOf('OTHER') then cboRouteClick(cboRoute);
ControlChange(sender);
end;
procedure TfrmODMedIV.cboRouteClick(Sender: TObject);
var
otherRoute, temp: string;
idx, oidx: integer;
begin
inherited;
oidx := cboRoute.Items.IndexOf('OTHER');
if oidx = -1 then exit;
if cboRoute.ItemIndex = oidx then
begin
otherRoute := CreateOtherRoute;
if length(otherRoute) > 1 then
begin
idx := cboRoute.Items.IndexOf(Piece(OtherRoute, U, 2));
if idx > -1 then
begin
temp := cboRoute.Items.Strings[idx];
//setPiece(temp,U,5,'1');
cboRoute.Items.Strings[idx] := temp;
end
else
begin
cboRoute.Items.Add(otherRoute);
idx := cboRoute.Items.IndexOf(Piece(OtherRoute, U, 2));
end;
cboRoute.ItemIndex := idx;
end
else
begin
cboRoute.ItemIndex := -1;
cboRoute.SetFocus;
end;
end;
end;
procedure TfrmODMedIV.cboRouteExit(Sender: TObject);
begin
inherited;
(* if (cboRoute.Text <> '') and (cboRoute.ItemIndex = -1) then
begin
infoBox(TX_BAD_ROUTE,'Warning',MB_OK);
cboRoute.SetFocus;
end; *)
end;
procedure TfrmODMedIV.cboRouteKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if IsAltCtrl_L_Pressed(Shift, Key) then
txtAllIVRoutesClick(txtAllIVRoutes);
end;
procedure TfrmODMedIV.cboRouteKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (Key = VK_BACK) and (cboRoute.Text = '') then cboRoute.ItemIndex := -1;
end;
procedure TfrmODMedIV.cboAdditiveMouseClick(Sender: TObject);
var
AnIVComponent: TIVComponent;
x, routeIEN, DEAFailStr, TX_INFO: string;
begin
inherited;
if cboAdditive.ItemIEN <= 0 then Exit;
FInpatient := OrderForInpatient;
DEAFailStr := '';
if not FInpatient then
begin
DEAFailStr := DEACheckFailedForIVOnOutPatient(cboAdditive.ItemIEN,'A');
while StrToIntDef(Piece(DEAFailStr,U,1),0) in [1..6] do
begin
case StrToIntDef(Piece(DEAFailStr,U,1),0) of
1: TX_INFO := TX_DEAFAIL; //prescriber has an invalid or no DEA#
2: TX_INFO := TX_SCHFAIL + Piece(DEAFailStr,U,2) + '.'; //prescriber has no schedule privileges in 2,2N,3,3N,4, or 5
3: TX_INFO := TX_NO_DETOX; //prescriber has an invalid or no Detox#
4: TX_INFO := TX_EXP_DEA1 + Piece(DEAFailStr,U,2) + TX_EXP_DEA2; //prescriber's DEA# expired and no VA# is assigned
5: TX_INFO := TX_EXP_DETOX1 + Piece(DEAFailStr,U,2) + TX_EXP_DETOX2; //valid detox#, but expired DEA#
6: TX_INFO := TX_SCH_ONE; //schedule 1's are prohibited from electronic prescription
end;
if StrToIntDef(Piece(DEAFailStr,U,1),0)=6 then
begin
InfoBox(TX_INFO, TC_DEAFAIL, MB_OK);
cboAdditive.Text := '';
Exit;
end;
if InfoBox(TX_INFO + TX_INSTRUCT, TC_DEAFAIL, MB_RETRYCANCEL) = IDRETRY then
begin
DEAContext := True;
fFrame.frmFrame.mnuFileEncounterClick(self);
DEAFailStr := '';
DEAFailStr := DEACheckFailedForIVOnOutPatient(cboAdditive.ItemIEN,'A');
end
else
begin
cboAdditive.Text := '';
Exit;
end;
end;
end else
begin
DEAFailStr := DEACheckFailed(cboAdditive.ItemIEN, FInpatient);
while StrToIntDef(Piece(DEAFailStr,U,1),0) in [1..6] do
begin
case StrToIntDef(Piece(DEAFailStr,U,1),0) of
1: TX_INFO := TX_DEAFAIL; //prescriber has an invalid or no DEA#
2: TX_INFO := TX_SCHFAIL + Piece(DEAFailStr,U,2) + '.'; //prescriber has no schedule privileges in 2,2N,3,3N,4, or 5
3: TX_INFO := TX_NO_DETOX; //prescriber has an invalid or no Detox#
4: TX_INFO := TX_EXP_DEA1 + Piece(DEAFailStr,U,2) + TX_EXP_DEA2; //prescriber's DEA# expired and no VA# is assigned
5: TX_INFO := TX_EXP_DETOX1 + Piece(DEAFailStr,U,2) + TX_EXP_DETOX2; //valid detox#, but expired DEA#
6: TX_INFO := TX_SCH_ONE; //schedule 1's are prohibited from electronic prescription
end;
if StrToIntDef(Piece(DEAFailStr,U,1),0)=6 then
begin
InfoBox(TX_INFO, TC_DEAFAIL, MB_OK);
cboAdditive.Text := '';
Exit;
end;
if InfoBox(TX_INFO + TX_INSTRUCT, TC_DEAFAIL, MB_RETRYCANCEL) = IDRETRY then
begin
DEAContext := True;
fFrame.frmFrame.mnuFileEncounterClick(self);
DEAFailStr := '';
DEAFailStr := DEACheckFailed(cboAdditive.ItemIEN, FInpatient);
end
else
begin
cboAdditive.Text := '';
Exit;
end;
end;
end;
routeIEN := Piece(cboAdditive.Items.Strings[cboAdditive.itemindex],U,4);
x := AmountsForIVFluid(cboAdditive.ItemIEN, 'A');
AnIVComponent := TIVComponent.Create;
AnIVComponent.IEN := cboAdditive.ItemIEN;
AnIVComponent.Name := Piece(cboAdditive.Items[cboAdditive.ItemIndex], U, 3);
AnIVComponent.Fluid := 'A';
AnIVComponent.Amount := 0;
AnIVComponent.Units := Piece(x, U, 1);
AnIVComponent.Volumes := '';
cboAdditive.ItemIndex := -1;
with grdSelected do
begin
if Objects[0, RowCount - 1] <> nil then RowCount := RowCount + 1;
Objects[0, RowCount - 1] := AnIVComponent;
Cells[0, RowCount - 1] := AnIVComponent.Name;
Cells[2, RowCount - 1] := AnIVComponent.Units;
Cells[3, RowCount -1] := UpdateAddFreq(AnIVComponent.IEN);
Row := RowCount - 1;
Col := 1;
end;
Application.ProcessMessages; //CQ: 10157
ClickOnGridCell(#0);
updateRoute;
ControlChange(Sender);
//UpdateRoute(RouteIEN);
end;
procedure TfrmODMedIV.cboAdditiveExit(Sender: TObject);
begin
inherited;
if (cboAdditive.ItemIEN > 0) and (EnterIsPressed) then
cboAdditiveMouseClick(Self);
end;
{ grdSelected events }
procedure TfrmODMedIV.ClearAllFields;
begin
self.cboType.ItemIndex := -1;
self.cboType.Text := '';
self.memComments.Text := '';
self.txtRate.Text := '';
self.txtXDuration.text := '';
self.cboDuration.ItemIndex := -1;
self.cboDuration.Text := '';
self.txtAllIVRoutes.Visible := false;
//self.FInitialOrderID := True;
cbotypeChange(self.cboType);
if self.cboroute.Items.Count > 0 then self.cboRoute.Clear;
FIVTypeDefined := false;
end;
procedure TfrmODMedIV.ClickOnGridCell(keypressed: Char);
var
AnIVComponent: TIVComponent;
procedure PlaceControl(AControl: TWinControl; keypressed: Char);
var
ARect: TRect;
begin
with AControl do
begin
ARect := grdSelected.CellRect(grdSelected.Col, grdSelected.Row);
SetBounds(ARect.Left + grdSelected.Left + 1, ARect.Top + grdSelected.Top + 1,
ARect.Right - ARect.Left + 1, ARect.Bottom - ARect.Top + 1);
BringToFront;
Show;
SetFocus;
if AControl is TComboBox then //CQ: 10157
begin
TComboBox(AControl).DroppedDown := True;
TControl(self.grdSelected).Enabled := false;
end
else if AControl is TCaptionEdit then
begin
if not(keypressed = #0) then
begin
TCaptionEdit(AControl).Text := keypressed;
TCaptionEdit(AControl).SelStart := 1;
end;
end;
end;
end;
begin
AnIVComponent := TIVComponent(grdSelected.Objects[0, grdSelected.Row]);
if (AnIVComponent = nil) or (grdSelected.Col = 0) then
begin
if (AnIVComponent <> nil) and (grdSelected.Col = 0) then grdSelected.Refresh;
Exit;
end;
// allow selection if more the 1 unit to choose from
if (grdSelected.Col = 2) and (Length(Piece(AnIVComponent.Units, U, 2)) > 0) then
begin
PiecesToList(AnIVComponent.Units, U, cboSelected.Items);
cboSelected.ItemIndex := cboSelected.Items.IndexOf(grdSelected.Cells[grdSelected.Col, grdSelected.Row]);
cboSelected.Tag := (grdSelected.Col * 256) + grdSelected.Row;
PlaceControl(cboSelected,keypressed);
end;
// allow selection if more than 1 volume to choose from
if (grdSelected.Col = 1) and (Length(Piece(AnIVComponent.Volumes, U, 2)) > 0) then
begin
PiecesToList(AnIVComponent.Volumes, U, cboSelected.Items);
cboSelected.ItemIndex := cboSelected.Items.IndexOf(grdSelected.Cells[grdSelected.Col, grdSelected.Row]);
cboSelected.Tag := (grdSelected.Col * 256) + grdSelected.Row;
PlaceControl(cboSelected,keypressed);
end;
// display text box to enter strength if the entry is an additive
if (grdSelected.Col = 1) and (AnIVComponent.Fluid = 'A') then
begin
txtSelected.Text := grdSelected.Cells[grdSelected.Col, grdSelected.Row];
txtSelected.Tag := (grdSelected.Col * 256) + grdSelected.Row;
PlaceControl(txtSelected,keypressed);
end;
// AGP ADDITIVE FREQUENCY CHANGES
if (Self.cboType.ItemIndex < 1) and (grdSelected.Col = 3) and (AnIVComponent.Fluid = 'A') then
begin
cboAddFreq.ItemIndex := cboAddFreq.Items.IndexOf(grdSelected.Cells[grdSelected.Col, grdSelected.Row]);
cboAddFreq.Tag := (grdSelected.Col * 256) + grdSelected.Row;
PlaceControl(cboAddFreq,keypressed);
end;
end;
procedure TfrmODMedIV.txtSelectedChange(Sender: TObject); // text editor for grid
begin
inherited;
with txtSelected do
begin
if Tag < 0 then Exit;
grdSelected.Cells[Tag div 256, Tag mod 256] := Text;
end;
ControlChange(Sender);
end;
procedure TfrmODMedIV.txtSelectedExit(Sender: TObject);
begin
inherited;
with txtSelected do
begin
grdSelected.Cells[Tag div 256, Tag mod 256] := Text;
Tag := -1;
Hide;
end;
grdSelected.Refresh;
end;
procedure TfrmODMedIV.txtSelectedKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (Key = VK_RETURN) or (Key = VK_Tab) then
begin
ActiveControl := grdSelected;
Key := 0;
end;
end;
procedure TfrmODMedIV.cboScheduleChange(Sender: TObject);
var
othSch: string;
idx: integer;
begin
inherited;
if self.txtXDuration.Enabled = true then
begin
self.txtXDuration.Text := '';
self.cboDuration.ItemIndex := -1;
end;
if self.cboSchedule.ItemIndex > -1 then
begin
if cboSchedule.ItemIndex = cboSchedule.Items.IndexOf('Other') then
begin
othSch := CreateOtherSchedule;
if length(trim(othSch)) > 1 then
begin
cboSchedule.Items.Add(othSch + U + U + NSSScheduleType + U + NSSAdminTime);
idx := cboSchedule.Items.IndexOf(Piece(OthSch, U, 1));
cboSchedule.ItemIndex := idx;
end
else cboSchedule.itemindex := -1;
end;
if cboSchedule.itemIndex > -1 then updateDuration(Piece(cboSchedule.Items.Strings[cboSchedule.itemindex],U,3));
end;
ControlChange(sender);
end;
procedure TfrmODMedIV.cboScheduleClick(Sender: TObject);
var
othSch: string;
idx: integer;
begin
inherited;
if cboSchedule.ItemIndex = cboSchedule.Items.IndexOf('Other') then
begin
othSch := CreateOtherSchedule;
if length(trim(othSch)) > 1 then
begin
cboSchedule.Items.Add(othSch + U + U + NSSScheduleType + U + NSSAdminTime);
idx := cboSchedule.Items.IndexOf(Piece(OthSch, U, 1));
cboSchedule.ItemIndex := idx;
end;
end
else
begin
NSSAdminTime := '';
NSSScheduleType := '';
end;
end;
procedure TfrmODMedIV.cboScheduleExit(Sender: TObject);
begin
inherited;
if (cboSchedule.ItemIndex = -1) and (cboSchedule.Text <> '') then
begin
infoBox('Please select a valid schedule from the list.'+ CRLF + CRLF +
'If you would like to create a Day-of-Week schedule please select ''OTHER'' from the list.',
'Incorrect Schedule.', MB_OK);
cboSchedule.Text := '';
cboSchedule.SetFocus;
end;
if (cboSchedule.ItemIndex > -1) and (cboSchedule.Text = '') then cboSchedule.ItemIndex := -1;
end;
procedure TfrmODMedIV.cboScheduleKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if IsAltCtrl_L_Pressed(Shift, Key) then
txtNSSClick(txtNSS);
end;
procedure TfrmODMedIV.cboScheduleKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (Key = VK_BACK) and (cboSchedule.Text = '') then cboSchedule.ItemIndex := -1;
end;
procedure TfrmODMedIV.cboSelectedCloseUp(Sender: TObject);
begin
inherited;
with cboSelected do
begin
if tag < 0 then exit;
grdSelected.Cells[Tag div 256, Tag mod 256] := MixedCase(items.Strings[itemindex]);
Tag := -1;
Hide;
ControlChange(Sender);
TControl(self.grdSelected).Enabled := True;
ActiveControl := self.grdSelected;
end;
grdSelected.Refresh;
end;
procedure TfrmODMedIV.cboSelectedKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if (Key = VK_RETURN) or (Key = VK_Tab) then
begin
cboSelectedCloseUp(cboSelected);
Key := 0;
end;
end;
procedure TfrmODMedIV.cmdRemoveClick(Sender: TObject); // remove button for grid
var
i, stRow, stRowCount: Integer;
begin
inherited;
with grdSelected do
begin
if Row < 0 then Exit;
stRow := Row;
stRowCount := RowCount;
if Objects[0, Row] <> nil then TIVComponent(Objects[0, Row]).Free;
for i := Row to RowCount - 2 do Rows[i] := Rows[i + 1];
Rows[RowCount - 1].Clear;
RowCount := RowCount - 1;
end;
updateRoute;
if (stRowCount = 1) and (stRow = 0) then
begin
//self.cboRoute.ItemIndex := -1;
ClearAllFields;
end;
ControlChange(Sender);
end;
{ update Responses & Create Order Text }
procedure TfrmODMedIV.ControlChange(Sender: TObject);
var
i, CurAdd, CurBase, idx: Integer;
adminTime,x,xlimIn,xLimEx,eSch,iSch,iType, tmpdur, tmpSch, tmpRate: string;
AnIVComponent: TIVComponent;
FQOSchedule: TResponse;
function IsNumericRate(const x: string): Boolean;
var
i: Integer;
begin
Result := True;
for i := 1 to Length(x) do if not CharInSet(x[i], ['0'..'9','.']) then Result := False;
end;
begin
inherited;
if Changing then Exit;
loadExpectFirstDose;
// FQOSchedule := TResponse.Create;
FQOSchedule := Responses.FindResponseByName('SCHEDULE',1);
if FQOSchedule <> nil then
begin
eSch := FQOSchedule.EValue;
iSch := FQOSchedule.IValue;
end;
//if Sender <> Self then Responses.Clear; // Sender=Self when called from SetupDialog
Responses.Clear; // want this to clear even after SetupDialog in case instances don't match
CurAdd := 1; CurBase := 1;
tmpRate := '';
with grdSelected do for i := 0 to RowCount - 1 do
begin
AnIVComponent := TIVComponent(Objects[0, i]);
if AnIVComponent = nil then Continue;
with AnIVComponent do
begin
if Fluid = 'B' then // Solutions
begin
if IEN > 0 then Responses.Update('ORDERABLE', CurBase, IntToStr(IEN), Name);
if Length(Cells[1,i]) > 0 then Responses.Update('VOLUME', CurBase, Cells[1,i], Cells[1,i]);
Inc(CurBase);
end; {if Fluid B}
if Fluid = 'A' then // Additives
begin
if IEN > 0 then Responses.Update('ADDITIVE', CurAdd, IntToStr(IEN), Name);
if Length(Cells[1,i]) > 0 then Responses.Update('STRENGTH', CurAdd, Cells[1,i], Cells[1,i]);
if Length(Cells[2,i]) > 0 then Responses.Update('UNITS', CurAdd, Cells[2,i], Cells[2,i]);
//AGP ADDITIVE FREQUECNY CHANGES
if (Length(Cells[3,i]) > 0) and (Cells[3,i] <> 'N/A') then Responses.Update('ADDFREQ', CurAdd, Cells[3,i], Cells[3,i]);
Inc(CurAdd);
end; {if Fluid A}
end; {with AnIVComponent}
end; {with grdSelected}
x := txtRate.Text;
xlimIn := '';
xlimEx := '';
if length(txtXDuration.Text) > 0 then
begin
tmpDur := LowerCase(cboDuration.Text);
if (tmpDur = 'l') or (tmpDur = 'ml') then
begin
xlimEx := 'with total volume ' + txtXDuration.Text + self.cboDuration.items.strings[self.cboDuration.itemindex];
xlimIn := 'with total volume ' + txtXDuration.Text + self.cboDuration.items.strings[self.cboDuration.itemindex];
end
else if (tmpDur = 'days') or (tmpDur = 'hours') then
begin
xlimEx := 'for ' + txtXDuration.Text + ' ' + self.cboDuration.items.strings[self.cboDuration.itemindex];
xlimIn := 'for ' + txtXDuration.Text + ' ' + self.cboDuration.items.strings[self.cboDuration.itemindex];
end
else if tmpDur = 'doses' then
begin
xlimEx := 'for a total of ' + txtXDuration.Text + ' ' + self.cboDuration.items.strings[self.cboDuration.itemindex];
xlimIn := 'for a total of ' + txtXDuration.Text + ' ' + self.cboDuration.items.strings[self.cboDuration.itemindex];
end
else begin
xlimIn := '';
xlimEx := '';
end;
end;
if (cboType.ItemIndex > -1) and (cboType.Items.Strings[cboType.ItemIndex] = 'Intermittent') then iType := 'I'
else if (cboType.ItemIndex > -1) and (cboType.Items.Strings[cboType.ItemIndex] = 'Continuous') then iType := 'C'
else iType := '';
Responses.Update('TYPE',1,iType,cboType.Text);
Responses.Update('ROUTE',1,cboRoute.ItemID,cboRoute.Text);
tmpSch := UpperCase(Trim(cboSchedule.Text));
if chkPRN.Checked then tmpSch := tmpSch + ' PRN';
if UpperCase(Copy(tmpSch, Length(tmpSch) - 6, Length(tmpSch))) = 'PRN PRN'
then tmpSch := Copy(tmpSch, 1, Length(tmpSch) - 4);
Responses.Update('SCHEDULE',1,tmpSch,tmpSch);
(*adminTime := Piece(lblAdminTime.Caption,':',2);
adminTime := Copy(adminTime,1,Length(adminTime));
if (Action in [ORDER_COPY, ORDER_EDIT]) and ((FAdminTimeDelay <> '') or (FAdminTimeClinic <> '')) and
(cboSchedule.ItemIndex = FOriginalScheduleIndex) then Responses.Update('ADMIN',1,FOriginalAdminTime,FOriginalAdminTime)
else Responses.Update('ADMIN',1,adminTime,adminTime);*)
idx := self.cboSchedule.ItemIndex;
if idx > -1 then
begin
adminTime := Piece(lblAdminTime.Caption,':',2);
adminTime := Copy(adminTime,2,Length(adminTime));
if FAdminTimeText <> '' then AdminTime := '';
if AdminTime = 'Not Defined' then AdminTime := '';
Responses.Update('ADMIN',1,adminTime,adminTime);
end;
if IsNumericRate(x) then
begin
if cboInfusionTime.Enabled = true then
begin
idx := cboInfusionTime.Items.IndexOf(cboInfusionTime.Text);
if idx > -1 then x := x + ' ' + cboInfusionTime.Items.Strings[idx];
tmpRate := 'Infuse Over ' + x;
end
else
if pos('ml/hr', x)= 0 then x := x + ' ml/hr';
end;
if (Pos('@',x)>0) and (Piece(x,'@',1) = IntToStr(StrToIntDef(Piece(x,'@',1), -1))) and (cboInfusionTime.Enabled = false) then
begin
if Pos('ml/hr', x) = 0 then
x := Piece(x,'@',1) + ' ml/hr@' + Copy(x, Pos('@',x) + 1, Length(x));
end;
with txtRate do if (Length(Text) > 0) then
begin
if tmpRate = '' then Responses.Update('RATE', 1, x, x)
else Responses.Update('RATE', 1, 'INFUSE OVER ' + x, tmpRate);
end;
with cboPriority do if ItemIndex > -1 then Responses.Update('URGENCY', 1, ItemID, Text);
if Length(xlimIn)>0 then Responses.Update('DAYS',1, xlimIn, xlimEx);
with memComments do if GetTextLen > 0 then Responses.Update('COMMENT', 1, TX_WPTYPE, Text);
if (chkDoseNow.Visible = True) and (chkDoseNow.Checked = True) then
Responses.Update('NOW', 1, '1', 'NOW')
else Responses.Update('NOW', 1, '', '');
memOrder.Text := Responses.OrderText;
(* (Length(eSch)>0) or (Length(iSch)>0) then
Responses.Update('SCHEDULE',1,iSch,eSch); *)
end;
function TfrmODMedIV.CreateOtherRoute: string;
var
aRoute: string;
begin
aRoute := '';
Result := '';
if not ShowOtherRoutes(aRoute) then
begin
cboRoute.ItemIndex := -1;
cboRoute.Text := '';
end
else
begin
Result := aRoute;
end;
end;
function TfrmODMedIV.CreateOtherSchedule: string;
var
aSchedule: string;
begin
aSchedule := '';
cboSchedule.ItemIndex := -1;
cboSchedule.Text := '';
cboSchedule.DroppedDown := false;
if ShowOtherSchedule(aSchedule) then
begin
Result := Piece(aSchedule,U,1);
NSSAdminTime := Piece(aschedule,u,2);
NSSScheduleType := Piece(ASchedule, U, 3);
end;
end;
procedure TfrmODMedIV.grdSelectedDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect;
State: TGridDrawState);
begin
inherited;
//if Sender = ActiveControl then Exit;
//if not (gdSelected in State) then Exit;
with Sender as TStringGrid do
begin
if State = [gdSelected..gdFocused] then
begin
Canvas.Font.Color := Get508CompliantColor(clWhite);
Canvas.Brush.Color := clHighlight;
//Canvas.Font.Color := clHighlightText;
Canvas.Font.Style := [fsBold];
Canvas.MoveTo(Rect.Left,Rect.top);
end
else
begin
if (ACol = 4) and (ColWidths[4] > 0) then
Canvas.Brush.Color := clInactiveBorder
else Canvas.Brush.Color := clWindow;
Canvas.Font := Font;
end;
Canvas.FillRect(Rect);
//Canvas.Brush.Color := Color;
Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, Cells[ACol, ARow]);
end;
end;
procedure TfrmODMedIV.SetFontSize( FontSize: integer);
begin
// inherited SetFontSize( FontSize );
DoSetFontSize( FontSize );
end;
procedure TfrmODMedIV.DisplayDoseNow(Status: boolean);
begin
if self.EvtID > 0 then Status := false;
if status = false then
begin
if (self.chkDoseNow.Visible = true) and (self.chkDoseNow.Checked = true) then self.chkDoseNow.Checked := false;
self.chkDoseNow.Visible := false;
end;
if status = true then self.chkDoseNow.Visible := true;
end;
procedure TfrmODMedIV.DoSetFontSize( FontSize: integer);
begin
// tabFluid.TabHeight := Abs(Font.Height) + 4;
// grdSelected.DefaultRowHeight := Abs(Font.Height) + 8;
//
// SetScrollBarHeight(FontSize);
Self.Font.Assign(Screen.IconFont);
end;
procedure TfrmODMedIV.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
inherited;
// if (Key = VK_Tab) and (ssCtrl in Shift) then
// begin
// // Back-tab works the same as forward-tab because there are only two tabs.
// tabFluid.TabIndex := (tabFluid.TabIndex + 1) mod tabFluid.Tabs.Count;
// Key := 0;
// tabFluidChange(tabFluid);
// end;
end;
procedure TfrmODMedIV.FormKeyPress(Sender: TObject; var Key: Char);
begin
if (Key = #13) and (ActiveControl = grdSelected) then
Key := #0; //Don't let the base class turn it into a forward tab!
inherited;
end;
procedure TfrmODMedIV.grdSelectedKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
ClickOnGridCell(Key);
end;
procedure TfrmODMedIV.grdSelectedMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
ClickOnGridCell(#0);
end;
procedure TfrmODMedIV.txtXDurationChange(Sender: TObject);
begin
inherited;
if Changing then Exit;
ControlChange(Sender);
end;
procedure TfrmODMedIV.pnlXDurationEnter(Sender: TObject);
begin
inherited;
txtXDuration.SetFocus;
end;
procedure TfrmODMedIV.SetLimitationControl(aValue: string);
var
limitUnit,limitValue,tempval: string;
begin
limitUnit := '';
limitValue := '';
tempVal := '';
if pos('dose',AValue)>0 then
begin
limitValue := Piece(aValue,' ',5);
limitUnit := 'doses';
end;
if (( CharAt(aValue,1)= 'f') or ( CharAt(aValue,1)= 'F')) and (pos('dose',aValue)=0) then //days, hours
begin
limitValue := Piece(aValue,' ',2);
limitUnit := Piece(aValue,' ',3);
end;
if (CharAt(aValue,1)= 'w') or (CharAt(aValue,1)= 'W') then //L, ml
begin
tempval := Piece(aValue,' ',4);
limitValue := FloatToStr(ExtractFloat(tempVal));
limitUnit := Copy(tempVal,length(limitValue)+1,Length(tempVal));
end;
if isNumeric(CharAt(aValue,1)) then
begin
if LeftStr(avalue,1) = '0' then AValue := Copy(aValue,2,Length(aValue));
limitValue := FloatToStr(ExtractFloat(aValue));
limitUnit := Copy(aValue,length(limitValue)+1,Length(aValue));
if limitUnit = 'D' then limitUnit := 'days'
else if limitUnit = 'H' then limitUnit := 'hours'
else if limitUnit = 'ML' then limitUnit := 'ml';
end;
if ( Length(limitUnit)> 0) and ( (Length(limitValue) > 0 ) ) then
begin
txtXDuration.Text := limitValue;
if Trim(UpperCase(limitUnit))='CC' then
limitUnit := 'ml';
cboduration.text := limitUnit;
if cboDuration.Text <> '' then cboDuration.ItemIndex := cboDuration.Items.IndexOf(cboDuration.Text)
end;
end;
procedure TfrmODMedIV.SetSchedule(const x: string);
var
NonPRNPart,tempSch: string;
idx: integer;
begin
cboSchedule.ItemIndex := -1;
chkPRN.Checked := False;
//Check to see if schedule is already define in the schedule list
idx := cboSchedule.Items.IndexOf(X);
if idx > -1 then
begin
cboSchedule.ItemIndex := idx;
exit;
end;
//if PRN schedule than set the checkbox than exit
if (X = ' PRN') or (X = 'PRN') then
begin
chkPRN.Checked := True;
Exit;
end;
//Check to see if schedule is a Day-of-Week Schedule (MO-WE-FR@BID)
if (Pos('@', x) > 0) then
begin
tempSch := Piece(x, '@', 2);
idx := cboSchedule.Items.IndexOf(tempSch);
if idx > -1 then
begin
//tempSch := U + Piece(x, '@', 1) + '@' + Pieces(cboSchedule.Items.Strings[idx], U, 2, 5);
tempSch := Piece(x, '@', 1) + '@' + cboSchedule.Items.Strings[idx];
cboSchedule.Items.Add(tempSch);
cboSchedule.Text := (Piece(tempSch,U,1));
cboSchedule.ItemIndex := cboSchedule.Items.IndexOf(Piece(tempSch,U,1));
EXIT;
end;
//Check to see if schedule is a Day-of-Week PRN Schedule (MO-WE-FR@BID PRN)
if Pos('PRN', tempSch) > 0 then
begin
NonPRNPart := Trim(Copy(tempSch, 1, Pos('PRN', tempSch) - 1));
idx := cboSchedule.Items.IndexOf(NonPRNPart);
if idx > -1 then
begin
//tempSch := U + Piece(x, '@', 1) + '@' + Pieces(cboSchedule.Items.Strings[idx], U, 2, 5);
tempSch := Piece(x, '@', 1) + '@' + cboSchedule.Items.Strings[idx];
cboSchedule.Text := (Piece(tempSch,U,1));
cboSchedule.ItemIndex := cboSchedule.Items.IndexOf(Piece(tempSch, U, 1));
chkPRN.Checked := True;
EXIT;
end
else
//Add Day-of-Week PRN schedule built off Time Prompt (MO-WE-FR@0800-1000 PRN)
begin
NonPRNPart := Trim(Copy(X, 1, Pos('PRN', X) - 1));
chkPRN.Checked := True;
//cboSchedule.Items.Add(U + NonPRNPart + U + U + U + AdminTime);
//cboSchedule.Items.Add(U + NonPRNPart + U + U + U + Piece(NonPRNPart, '@', 2));
cboSchedule.Items.Add(NonPRNPart + U + U + U + Piece(NonPRNPart, '@', 2));
cboSchedule.Text := NonPRNPart;
cboSchedule.ItemIndex := cboSchedule.Items.IndexOf(NonPRNPart);
EXIT;
end;
end;
//Add Non PRN Day-of-Week Schedule built off Time Prompt (MO-WE-FR@0800-1000)
//cboSchedule.Items.Add(U + x + U + U + U + AdminTime);
//cboSchedule.Items.Add(U + x + U + U + U + tempSch);
cboSchedule.Items.Add(x + U + U + U + tempSch);
cboSchedule.Text := x;
cboSchedule.ItemIndex := cboSchedule.Items.IndexOf(X);
end
else
begin
//Handle standard schedule mark as PRN (Q4H PRN)
if Pos('PRN', X) > 0 then
begin
NonPRNPart := Trim(Copy(X, 1, Pos('PRN', X) - 1));
idx := cboSchedule.Items.IndexOf(NonPRNPart);
if idx > -1 then
begin
cboSchedule.ItemIndex := idx;
tempSch := cboSchedule.Items.Strings[idx];
//setPiece(tempSch,U,5,AdminTime);
cboSchedule.Items.Strings[idx] := tempSch;
chkPRN.Checked := True;
exit;
end;
end;
end;
end;
procedure TfrmODMedIV.txtXDurationExit(Sender: TObject);
var
Code: double;
begin
inherited;
if (txtXDuration.Text <> '0') and (txtXDuration.Text <> '') then
begin
try
code := StrToFloat(txtXDuration.Text);
except
code := 0;
end;
if code < 0.0001 then
begin
ShowMsg('Can not save order.' + #13#10 + 'Reason: Invalid Duration or Total Volume!');
txtXDuration.Text := '';
txtXDuration.SetFocus;
Exit;
end;
end;
try
if (Length(txtXDuration.Text)>0) and (StrToFloat(txtXDuration.Text)<0) then
begin
ShowMsg('Can not save order.' + #13#10 + 'Reason: Invalid Duration or total volume!');
txtXDuration.Text := '';
txtXDuration.SetFocus;
Exit;
end;
except
txtXDuration.Text := '';
end;
ControlChange(Sender);
end;
function TfrmODMedIV.UpdateAddFreq(OI: integer): string;
begin
if (self.cboType.ItemIndex = -1) or (MixedCase(self.cboType.Items.Strings[self.cboType.ItemIndex]) = 'Continuous') then
Result := GetDefaultAddFreq(OI)
else Result := '';
end;
procedure TfrmODMedIV.UpdateDuration(SchType: string);
begin
if SchType = 'O' then
begin
self.cboDuration.ItemIndex := -1;
self.txtXDuration.Text := '';
self.cboDuration.Enabled := false;
self.txtXDuration.Enabled := false;
self.lblLimit.Enabled := false;
end
else
begin
self.cboDuration.Enabled := true;
self.txtXDuration.Enabled := true;
self.lblLimit.Enabled := true;
end;
end;
procedure TfrmODMedIV.UpdateRoute;
var
AnIVComponent: TIVComponent;
i: integer;
OrderIds, TempIVRoute: TStringList;
//Default: boolean;
begin
if self.grdSelected.RowCount > 0 then self.txtAllIVRoutes.Visible := True;
TempIVRoute := TStringList.Create;
for I := (self.cboRoute.Items.Count -1) downto 0 do
begin
if Piece(self.cboRoute.Items.Strings[i], U, 5) = '1' then
TempIVRoute.Add(self.cboRoute.Items.Strings[i]);
self.cboRoute.Items.Delete(i);
end;
if self.cboRoute.ItemIndex = -1 then self.cboRoute.Text := '';
OrderIds := TStringList.Create;
for i := 0 to self.grdSelected.RowCount -1 do
begin
AniVComponent := TIVComponent(self.grdSelected.Objects[0, i]);
if AnIVComponent <> nil then orderIds.Add(InttoStr(AniVComponent.IEN));
end;
if OrderIds.Count > 0 then
begin
//if (self.FInitialOrderID = True) and (self.grdSelected.RowCount = 1) then Default := True
//else Default := False;
LoadDosageFormIVRoutes(self.cboRoute.Items, OrderIds);
//if default = True then
// begin
for I := 0 to cboRoute.items.Count - 1 do
begin
if Piece(cboRoute.Items.Strings[i], U, 5) = 'D' then
begin
cboRoute.ItemIndex := i;
break;
end;
end;
// self.FInitialOrderID := false;
//end;
OrderIds.Free;
end;
if TempIVRoute.Count > 0 then
begin
for I := 0 to tempIVRoute.Count - 1 do cboRoute.Items.Add(tempIVRoute.Strings[i]);
TempIVRoute.Free;
end;
cboRoute.Items.Add(U + 'OTHER');
end;
procedure TfrmODMedIV.txtAllIVRoutesClick(Sender: TObject);
var
i: integer;
msg : String;
begin
inherited;
msg := 'You can also select "OTHER" from the Route list'
+ ' to select a Route from the Expanded Med Route List.'
+ #13#10 + 'Click OK to launch the Expanded Med Route List.';
if ShowMsg(msg, smiInfo, smbOKCancel) = smrOk then
begin
for I := 0 to cboRoute.Items.Count - 1 do if cboRoute.Items.Strings[i] = U + 'OTHER' then break;
cboRoute.ItemIndex := i;
cboRouteClick(self);
cboRouteChange(self.cboRoute);
end;
end;
procedure TfrmODMedIV.txtNSSClick(Sender: TObject);
var
i: integer;
msg : String;
begin
inherited;
msg := 'You can also select ' + '"' + 'Other' + '"' + ' from the schedule list'
+ ' to create a day-of-week schedule.'
+ #13#10 + 'Click OK to launch schedule builder';
if ShowMsg(msg, smiInfo, smbOKCancel) = smrOK then
begin
//cboSchedule.Items.Add(U + 'OTHER');
for I := 0 to cboSchedule.Items.Count - 1 do if cboSchedule.Items.Strings[i] = 'OTHER' then break;
cboSchedule.ItemIndex := i;
//cboSchedule.SelectByID(U+'OTHER');
cboScheduleClick(Self);
cboScheduleChange(self.cboSchedule);
end;
end;
procedure TfrmODMedIV.txtRateChange(Sender: TObject);
begin
inherited;
if Changing then Exit;
ControlChange(Sender);
end;
end.
|
(*****************************************************************************
* Pascal Solution to "The 15-Puzzle" from the *
* *
* Seventh Annual UCF ACM UPE High School Programming Tournament *
* May 15, 1993 *
* *
*****************************************************************************)
(************************************************************************
Problem: The 15-Puzzle
File Name: puzzle.pas
Solution By: Gregg Hamilton
************************************************************************)
Var
puzzle : array[1..4, 1..4] of integer ; (* Array to store puzzle *)
inFile : text ; (* Iput file handle *)
i, j, (* Used for indexing and counting *)
open_i, (* Column position of open space *)
open_j, (* Row position of open space *)
num : integer ; (* Number of moves *)
dir : char ; (* Direction character *)
Begin
(* Set up input file. *)
assign( inFile, 'puzzle.in' ) ;
reset( inFile ) ;
(* Loop through all input data. *)
while not eof( inFile ) do
Begin
(* There should not be any blank lines at the bottom of the input *)
(* file, but it's better to be safe than sorry! The following check *)
(* will take care of them. *)
if eoln( inFile ) then
readln( inFile )
else
Begin
(* Read in the puzzle. *)
for i := 1 to 4 do
Begin
for j := 1 to 4 do
Begin
read( inFile, puzzle[i][j] ) ;
if puzzle[i][j] = 0 then
Begin
open_i := i ;
open_j := j ;
End ;
End ;
readln( inFile ) ;
End ;
(* Read in the number of moves. *)
readln( inFile, num ) ;
(* Loop through the number of moves *)
for i := 1 to num do
Begin
(* Read in the move. *)
read( inFile, dir ) ;
readln( inFile ) ;
(* Based on the direction, copy the contents of the position *)
(* where the blank space is moving to the current position *)
(* of the space, then set the value at that position to zero *)
(* (marking it as empty, and update the open space indicies. *)
case dir of
'U' : Begin
puzzle[open_i][open_j] := puzzle[open_i - 1][open_j] ;
puzzle[open_i - 1][open_j] := 0 ;
open_i := open_i - 1 ;
End ;
'D' : Begin
puzzle[open_i][open_j] := puzzle[open_i + 1][open_j] ;
puzzle[open_i + 1][open_j] := 0 ;
open_i := open_i + 1 ;
End ;
'L' : Begin
puzzle[open_i][open_j] := puzzle[open_i][open_j - 1] ;
puzzle[open_i][open_j - 1] := 0 ;
open_j := open_j - 1 ;
End ;
'R' : Begin
puzzle[open_i][open_j] := puzzle[open_i][open_j + 1] ;
puzzle[open_i][open_j + 1] := 0 ;
open_j := open_j + 1 ;
End ;
End ;
End ;
(* Print out the resulting board. *)
for i := 1 to 4 do
Begin
for j := 1 to 4 do
Begin
if puzzle[i][j] = 0 then
write( ' ' )
else
write( puzzle[i][j]:2, ' ' ) ;
End ;
writeln ;
End ;
writeln ;
End ; (* End of else not eoln *)
End ; (* End of while not eof *)
End.
|
unit g_player;
interface
uses
OpenGL, Windows, u_winapi, u_math, g_class_gameobject, g_game_objects, g_rockets, g_hud, u_sound, g_sounds;
type
TPlayer = class (TGameObject)
FireTimer : Integer;
RocketTime : Integer;
FakeTimer : Integer;
TrailTime : Integer;
BlinkTime : Integer;
RespawnTime : Integer;
Blinking : Boolean;
SoundPlayed : Boolean;
LockOn : TGameObject;
Streif : Single;
procedure Move; override;
procedure Render; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
procedure Death; override;
procedure Stop;
end;
TFakePlayer = class (TGameObject)
procedure Move; override;
procedure Render; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
procedure Death; override;
end;
const
MAX_SPEED = 0.15;
var
Player : TPlayer = nil;
implementation
uses g_world, SysUtils;
{ TPlayer }
procedure TPlayer.Death;
begin
inherited;
if SoundPlayed then Sound_StopStream(EngineSound);
Sound_PlayStream(Lost_life);
Dec(World.Lifes);
World.ReCreatePlayer;
end;
procedure TPlayer.DoCollision(Vector: TGamePos; CoObject: TObject);
begin
inherited;
end;
procedure TPlayer.Move;
var
Bullet : TBullet;
Rock : TSimpleRocket;
Trail : TTrail;
StrVec : TGamePos;
begin
Angle := AngleTo(Pos.x, Pos.z, Pos.x + Hud.Cursor.Pos.x, Pos.z + Hud.Cursor.Pos.z);
StrVec := MakeVector(0, 0, 0);
if (Keys[Ord('W')] or Keys[VK_UP]) then
begin
if not SoundPlayed then
begin
Sound_PlayStream(EngineSound);
SoundPlayed := True;
end;
Speed := Speed + 0.002;
if Speed > MAX_SPEED then Speed := MAX_SPEED;
MVector := MakeVector(Cosinus(Angle), 0, Sinus(Angle))
end else if (Keys[Ord('S')] or Keys[VK_DOWN]) then
begin
if not SoundPlayed then
begin
Sound_PlayStream (EngineSound);
SoundPlayed := True;
end;
Speed := Speed - 0.002;
if Speed < -MaX_SPEED then Speed := - MAX_SPEED;
MVector := MakeVector(Cosinus(Angle), 0, Sinus(Angle))
end else if (Keys[Ord('A')] or Keys[VK_LEFT]) then
begin
if not SoundPlayed then
begin
Sound_PlayStream (EngineSound);
SoundPlayed := True;
end;
Streif := Streif - 0.002;
if Streif < -Max_SPEED then Streif := -Max_SPEED;
StrVec := MakeVector(Cosinus(Angle+90), 0, Sinus(Angle+90));
end else if (Keys[Ord('D')] or Keys[VK_RIGHT]) then
begin
if not SoundPlayed then
begin
Sound_PlayStream (EngineSound);
SoundPlayed := True;
end;
Streif := Streif + 0.002;
if Streif > Max_SPEED then Streif := Max_SPEED;
StrVec := MakeVector(Cosinus(Angle+90), 0, Sinus(Angle+90));
end else
begin
if SoundPlayed then
begin
Sound_StopStream(EngineSound);
SoundPlayed := False;
end;
if Speed > 0 then
Speed := Speed - 0.0001 else
Speed := Speed + 0.0001;
end;
if Keys[ord('W')] then
begin
if TrailTime = 0 then
begin
Trail := TTrail.Create;
Trail.Scale := 1+Random(30)/10;
Trail.Pos := MinusVctors(Pos, MultiplyVectorScalar(MakeVector(Cosinus(Angle), 0, Sinus(Angle)), 2));
ObjectsEngine.AddObject(Trail);
TrailTime := 5;
end;
Dec(TrailTime);
end;
if Keys[VK_SHIFT] or Mouse_lbutton then
begin
if FireTimer <= 0 then
begin
Bullet := TBullet.Create;
Bullet.Pos := AddVector(Pos, MultiplyVectorScalar(MakeNormalVector(Cosinus(Angle), 0, Sinus(Angle)), 0.2));
Bullet.MVector := MultiplyVectorScalar(MakeNormalVector(Cosinus(Angle), 0, Sinus(Angle)), 0.2);
Bullet.FiredBy := Self;
ObjectsEngine.AddObject(Bullet);
Sound_PlayStream(ShotSound);
FireTimer := 10;
end else
Dec(FireTimer);
end else
FireTimer := 0;
if Keys[VK_SPACE] or Mouse_rbutton then
begin
if RocketTime <= 0 then
begin
Rock := TStraightRocket.Create;
Rock.Pos := AddVector(Pos, MultiplyVectorScalar(MakeNormalVector(Cosinus(Angle), 0, Sinus(Angle)), 0.5));;
Rock.MVector := MakeNormalVector(Cosinus(Angle), 0, Sinus(Angle));
Rock.FiredBy := Self;
Rock.Angle := Angle;
ObjectsEngine.AddObject(Rock);
RocketTime := 100;
end;
end;
Dec(RocketTime);
if RocketTime < 0 then RocketTime := 0;
if Collision = False then
begin
dec(RespawnTime);
if RespawnTime <= 0 then
begin
Collision := True;
Hide := False;
end else
Hide := odd(RespawnTime div 10);
end;
Pos := AddVector(Pos, MultiplyVectorScalar(MVector, Speed));
//Pos := AddVector(Pos, MultiplyVectorScalar(StrVec, Streif));
end;
procedure TPlayer.Render;
begin
inherited;
glPushMatrix;
glTranslatef(Pos.x, Pos.y, Pos.z);
glRotatef(90-Angle, 0.0, 1.0, 0.0);
glColor3f(1 - (Health / 100), Health / 100, 0.0);
glBegin(GL_LINE_LOOP);
glVertex3f(0.0, 0.0, 1);
glVertex3f(0.5, 0.0, -1);
glVertex3f(-0.5, 0.0, -1);
glEnd;
if Keys[Ord('W')] or Keys[ord('S')] then
begin
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex3f(-0.5, 0.0, -1);
glVertex3f(0.0, 0.0, -1.3 - (Random(100) / 100));
glVertex3f(0.5, 0.0, -1);
glEnd;
end;
glPopMatrix;
end;
procedure TPlayer.Stop;
begin
Sound_StopStream(EngineSound);
Freeze := True;
end;
{ TFakePlayer }
procedure TFakePlayer.Death;
begin
inherited;
//
end;
procedure TFakePlayer.DoCollision(Vector: TGamePos; CoObject: TObject);
begin
inherited;
end;
procedure TFakePlayer.Move;
begin
inherited;
Health := Health - 0.5;
end;
procedure TFakePlayer.Render;
begin
inherited;
glPushMatrix;
glTranslatef(Pos.x, Pos.y, Pos.z);
glRotatef(90-Angle, 0.0, 1.0, 0.0);
glColor3f(0.5, 0.5, 0.5);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 1);
glVertex3f(0.5, 0.0, -1);
glVertex3f(-0.5, 0.0, -1);
glEnd;
glPopMatrix;
end;
end.
|
unit ParamsHelper;
interface
uses
Data.DB, System.Classes, System.SysUtils, UIRestore;
type
TParamsHelper = class helper for TParams
function AddParam(pParamName : string; pFieldType: TFieldType; pValue : Variant): TParam; overload;
function AddParam(pField: TField) : TParam; overload;
end;
function StrToParam(s : string) : string;
implementation
{ TParamsHelper }
function TParamsHelper.AddParam(pParamName: string; pFieldType: TFieldType;
pValue: Variant): TParam;
begin
Result := nil;
if pParamName <> '' then
Result := FindParam(pParamName);
if not assigned(Result) then
Result := AddParameter;
if pParamName <> '' then
Result.Name := pParamName;
if pFieldType = ftString then
Result.AsString := pValue
else if pFieldType = ftWideString then
Result.AsWideString := pValue
else if pFieldType = ftFloat then
Result.AsFloat := pValue
else if pFieldType = ftDateTime then
Result.AsDateTime := pValue
else if pFieldType = ftInteger then
Result.AsInteger := pValue
else
Result.Value := pValue;
end;
function TParamsHelper.AddParam(pField: TField): TParam;
var
st: TStringStream; ist: IObjcleaner;
begin
if pField.IsNull then
begin
if pField.DataType in [ftInteger, ftSmallInt] then
Result := AddParam(pField.FieldName, ftInteger, 0)
else if pField.DataType in [ftFloat, ftSingle] then
Result := AddParam(pField.FieldName, ftFloat, 0)
else if pField.DataType in [ftBoolean] then
Result := AddParam(pField.FieldName, ftBoolean, False)
else if pField.DataType in [ftDateTime] then
Result := AddParam(pField.FieldName, ftDateTime, 0)
else
Result := AddParam(pField.FieldName, pField.DataType, '');
end
else if pField.DataType = ftBlob then
begin
st := TStringStream.Create; ist := CreateObjCleaner(st);
TBlobField(pField).SaveToStream(st);
Result := AddParameter;
Result.Name := pField.FieldName;
Result.DataType := ftBlob;
Result.LoadFromStream(st, ftBlob);
end
else
Result := AddParam(pField.FieldName, pField.DataType, pField.Value);
end;
// Global functions and procedures
function StrToParam(s: string): string;
begin
Result := StringReplace(s, ' ', '', [rfReplaceAll]);
Result := StringReplace(Result, '/', '', [rfReplaceAll]);
Result := StringReplace(Result, '-', '', [rfReplaceAll]);
end;
end.
|
unit IdThreadMgrPool;
interface
uses
Classes,
IdThread, IdThreadMgr;
type
TIdThreadMgrPool = class(TIdThreadMgr)
protected
FPoolSize: Integer;
FThreadPool: TThreadList;
//
procedure ThreadStopped(AThread: TIdThread);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetThread: TIdThread; override;
procedure ReleaseThread(AThread: TIdThread); override;
procedure TerminateThreads; override;
published
property PoolSize: Integer read FPoolSize write FPoolSize default 0;
end;
implementation
uses
IdGlobal,
SysUtils;
{ TIdThreadMgrPool }
constructor TIdThreadMgrPool.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FThreadPool := TThreadList.Create;
end;
destructor TIdThreadMgrPool.Destroy;
var
i: integer;
LThreads: TList;
begin
PoolSize := 0;
LThreads := FThreadPool.LockList;
try
for i := 0 to LThreads.Count - 1 do
begin
TIdThread(LThreads[i]).Free;
end;
finally FThreadPool.UnlockList; end;
FreeAndNil(FThreadPool);
inherited Destroy;
end;
function TIdThreadMgrPool.GetThread: TIdThread;
var
i: integer;
LThreadPool: TList;
begin
LThreadPool := FThreadPool.LockList;
try
// Use this as a chance to clean up thread pool
i := LThreadPool.Count - 1;
{ while (i > 0) and not (TIdThread(FThreadPool[i]).Suspended and TIdThread(FThreadPool[i]).Stopped) do begin
if TIdThread(FThreadPool[i]).Terminated then begin // cleanup
TIdThread(FThreadPool[i]).Free;
FThreadPool.Delete(i);
end;
Dec(i);
end;}
if i >= 0 then
begin
Result := TIdThread(LThreadPool[0]);
LThreadPool.Delete(0);
end else begin
Result := CreateNewThread;
Result.StopMode := smSuspend;
end;
finally FThreadPool.UnlockList; end;
ActiveThreads.Add(Result);
end;
procedure TIdThreadMgrPool.ReleaseThread(AThread: TIdThread);
var
LThreadPool: TList;
begin
ActiveThreads.Remove(AThread);
LThreadPool := FThreadPool.LockList;
try
// PoolSize = 0 means that we will keep all active threads in the thread pool
if ((PoolSize > 0) and (LThreadPool.Count >= PoolSize)) or AThread.Terminated then begin
if IsCurrentThread(AThread) then begin
AThread.FreeOnTerminate := True;
AThread.Terminate;
end else begin
if not AThread.Stopped then
begin
AThread.TerminateAndWaitFor;
end;
AThread.Free;
end;
end else begin
if not AThread.Suspended then begin
AThread.OnStopped := ThreadStopped;
AThread.Stop;
end
else begin
AThread.Free;
end;
end;
finally FThreadPool.UnlockList; end;
end;
procedure TIdThreadMgrPool.TerminateThreads;
begin
inherited TerminateThreads;
with FThreadPool.LockList do
try
while Count > 0 do begin
TIdThread(Items[0]).FreeOnTerminate := true;
TIdThread(Items[0]).Terminate;
TIdThread(Items[0]).Start;
Delete(0);
end;
finally
FThreadPool.UnlockList;
end;
end;
procedure TIdThreadMgrPool.ThreadStopped(AThread: TIdThread);
begin
FThreadPool.Add(AThread);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXDynalinkNative;
interface
uses
Data.DBXCommon,
Data.DBXDynalink
;
type
TDBXDynalinkDriverLoader = class(TDBXDynalinkDriverCommonLoader)
strict protected
// procedure LoadDriverLibrary(DriverProperties: TDBXProperties; DBXContext: TDBXContext); override;
function CreateMethodTable: TDBXMethodTable; override;
function CreateDynalinkDriver: TDBXDynalinkDriver; override;
end;
TGetDriverFunc = function(SVendorLib, SResourceFile: PChar; out Obj): TDBXErrorCode; stdcall;
TDBXDynalinkDriverNative = class(TDBXDynalinkDriver)
protected
function CreateConnection(ConnectionBuilder: TDBXConnectionBuilder): TDBXConnection; override;
public
constructor Create(DriverClone: TDBXDriver; DriverHandle: TDBXDriverHandle;
MethodTable: TDBXMethodTable); overload;
constructor Create(DBXDriverDef: TDBXDriverDef;
DBXDriverLoader: TDBXDynalinkDriverCommonLoaderClass); overload;
constructor Create(DBXDriverDef: TDBXDriverDef;
DBXDriverLoader: TDBXDynalinkDriverCommonLoaderClass;
DriverProps: TDBXProperties); overload;
end;
TDBXNativeMethodTable = class(TDBXMethodTable)
private
FLibraryHandle: THandle;
public
constructor Create(LibraryHandle: THandle);
destructor Destroy; override;
procedure LoadMethods; override;
function LoadMethod(MethodName: string): TPointer; override;
end;
implementation
uses
{$IFNDEF POSIX}
Winapi.Windows,
{$ENDIF not POSIX}
System.SysUtils,
Data.DBXCommonResStrs
;
{ TDBXDynalinkDriverNative }
constructor TDBXDynalinkDriverNative.Create(DriverClone: TDBXDriver; DriverHandle: TDBXDriverHandle; MethodTable: TDBXMethodTable);
begin
inherited Create(DriverClone, DriverHandle, MethodTable);
end;
constructor TDBXDynalinkDriverNative.Create(DBXDriverDef: TDBXDriverDef; DBXDriverLoader: TDBXDynalinkDriverCommonLoaderClass);
begin
inherited Create(DBXDriverDef, DBXDriverLoader);
end;
constructor TDBXDynalinkDriverNative.Create(DBXDriverDef: TDBXDriverDef; DBXDriverLoader: TDBXDynalinkDriverCommonLoaderClass; DriverProps: TDBXProperties);
begin
inherited Create(DBXDriverDef, DBXDriverLoader, DriverProps);
end;
function TDBXDynalinkDriverNative.CreateConnection(ConnectionBuilder: TDBXConnectionBuilder): TDBXConnection;
var
ConnectionHandle: TDBXConnectionHandle;
ErrorResult: TDBXErrorCode;
begin
LoadDriver(ConnectionBuilder.DbxContext);
ErrorResult := FMethodTable.FDBXDriver_CreateConnection(FDriverHandle, ConnectionHandle);
CheckResult(ErrorResult);
Result := TDBXDynalinkConnection.Create(ConnectionBuilder, ConnectionHandle, FMethodTable);
end;
{ DBXDriverLoader }
function TDBXDynalinkDriverLoader.CreateDynalinkDriver: TDBXDynalinkDriver;
begin
Result := TDBXDynalinkDriverNative.Create(TDBXDriver(nil), FDriverHandle, FMethodTable);
end;
function TDBXDynalinkDriverLoader.CreateMethodTable: TDBXMethodTable;
begin
Result := TDBXNativeMethodTable.Create(FLibraryHandle);
end;
{ TDBXNativeMethodTable }
constructor TDBXNativeMethodTable.Create(LibraryHandle: THandle);
begin
FLibraryHandle := LibraryHandle;
inherited Create;
end;
destructor TDBXNativeMethodTable.Destroy;
begin
FreeLibrary(FLibraryHandle);
FLibraryHandle := 0;
inherited;
end;
procedure TDBXNativeMethodTable.LoadMethods;
begin
FDBXLoader_GetDriver := LoadMethod(SDBXLoader_GetDriver);
FDBXBase_GetErrorMessageLength := LoadMethod(SDBXBase_GetErrorMessageLength);
FDBXBase_GetErrorMessage := LoadMethod(SDBXBase_GetErrorMessage);
FDBXBase_Close := LoadMethod(SDBXBase_Close);
FDBXRow_GetString := LoadMethod(SDBXRow_GetString);
FDBXRow_GetWideString := LoadMethod(SDBXRow_GetWideString);
FDBXRow_GetBoolean := LoadMethod(SDBXRow_GetBoolean);
FDBXRow_GetUInt8 := LoadMethod(SDBXRow_GetUInt8);
FDBXRow_GetInt8 := LoadMethod(SDBXRow_GetInt8);
FDBXRow_GetInt16 := LoadMethod(SDBXRow_GetInt16);
FDBXRow_GetInt32 := LoadMethod(SDBXRow_GetInt32);
FDBXRow_GetInt64 := LoadMethod(SDBXRow_GetInt64);
FDBXRow_GetSingle := LoadMethod(SDBXRow_GetSingle);
FDBXRow_GetDouble := LoadMethod(SDBXRow_GetDouble);
FDBXRow_GetBcd := LoadMethod(SDBXRow_GetBcd);
FDBXRow_GetTimeStamp := LoadMethod(SDBXRow_GetTimeStamp);
FDBXRow_GetTimeStampOffset := LoadMethod(SDBXRow_GetTimeStampOffset);
FDBXRow_GetTime := LoadMethod(SDBXRow_GetTime);
FDBXRow_GetDate := LoadMethod(SDBXRow_GetDate);
FDBXRow_GetFixedBytes := LoadMethod(SDBXRow_GetFixedBytes);
FDBXRow_GetByteLength := LoadMethod(SDBXRow_GetByteLength);
FDBXRow_GetBytes := LoadMethod(SDBXRow_GetBytes);
// FDBXRow_GetBinary := LoadMethod(SDBXRow_GetBinary);
FDBXRow_GetObjectTypeName := LoadMethod(SDBXRow_GetObjectTypeName);
FDBXWritableRow_SetNull := LoadMethod(SDBXWritableRow_SetNull);
FDBXWritableRow_SetString := LoadMethod(SDBXWritableRow_SetString);
FDBXWritableRow_SetWideString := LoadMethod(SDBXWritableRow_SetWideString);
FDBXWritableRow_SetBoolean := LoadMethod(SDBXWritableRow_SetBoolean);
FDBXWritableRow_SetUInt8 := LoadMethod(SDBXWritableRow_SetUInt8);
FDBXWritableRow_SetInt8 := LoadMethod(SDBXWritableRow_SetInt8);
FDBXWritableRow_SetInt16 := LoadMethod(SDBXWritableRow_SetInt16);
FDBXWritableRow_SetInt32 := LoadMethod(SDBXWritableRow_SetInt32);
FDBXWritableRow_SetInt64 := LoadMethod(SDBXWritableRow_SetInt64);
FDBXWritableRow_SetSingle := LoadMethod(SDBXWritableRow_SetSingle);
FDBXWritableRow_SetDouble := LoadMethod(SDBXWritableRow_SetDouble);
FDBXWritableRow_SetBcd := LoadMethod(SDBXWritableRow_SetBcd);
FDBXWritableRow_SetTimeStamp := LoadMethod(SDBXWritableRow_SetTimeStamp);
FDBXWritableRow_SetTimeStampOffset := LoadMethod(SDBXWritableRow_SetTimeStampOffset);
FDBXWritableRow_SetTime := LoadMethod(SDBXWritableRow_SetTime);
FDBXWritableRow_SetDate := LoadMethod(SDBXWritableRow_SetDate);
FDBXWritableRow_SetBytes := LoadMethod(SDBXWritableRow_SetBytes);
// FDBXWritableRow_SetBinary := LoadMethod(SDBXWritableRow_SetBinary);
FDBXDriver_CreateConnection := LoadMethod(SDBXDriver_CreateConnection);
FDBXDriver_GetVersion := LoadMethod(SDBXDriver_GetVersion);
FDBXConnection_Connect := LoadMethod(SDBXConnection_Connect);
FDBXConnection_Disconnect := LoadMethod(SDBXConnection_Disconnect);
FDBXConnection_SetCallbackEvent := LoadMethod(SDBXConnection_SetCallbackEvent);
FDBXConnection_CreateCommand := LoadMethod(SDBXConnection_CreateCommand);
FDBXConnection_BeginTransaction := LoadMethod(SDBXConnection_BeginTransaction);
FDBXConnection_Commit := LoadMethod(SDBXConnection_Commit);
FDBXConnection_Rollback := LoadMethod(SDBXConnection_Rollback);
FDBXConnection_GetIsolation := LoadMethod(SDBXConnection_GetIsolation);
// Ok if not implemented.
//
FDBXConnection_GetVendorProperty := GetProcAddress(FLibraryHandle, SDBXConnection_GetVendorProperty);
// FDBXConnection_SetProperty := GetProcAddress(FLibraryHandle, PAnsiChar(AnsiString(SDBXConnection_SetProperty)));
FDBXCommand_CreateParameterRow := LoadMethod(SDBXCommand_CreateParameterRow);
FDBXCommand_Prepare := LoadMethod(SDBXCommand_Prepare);
FDBXCommand_Execute := LoadMethod(SDBXCommand_Execute);
FDBXCommand_ExecuteImmediate := LoadMethod(SDBXCommand_ExecuteImmediate);
FDBXCommand_GetNextReader := LoadMethod(SDBXCommand_GetNextReader);
FDBXCommand_GetRowsAffected := LoadMethod(SDBXCommand_GetRowsAffected);
FDBXCommand_SetMaxBlobSize := LoadMethod(SDBXCommand_SetMaxBlobSize);
FDBXCommand_SetRowSetSize := LoadMethod(SDBXCommand_SetRowSetSize);
FDBXCommand_GetParameterCount := GetProcAddress(FLibraryHandle, SDBXCommand_GetParameterCount);
FDBXCommand_GetParameterType := GetProcAddress(FLibraryHandle, SDBXCommand_GetParameterType);
FDBXParameterRow_SetParameterType := LoadMethod(SDBXParameterRow_SetParameterType);
FDBXReader_GetColumnCount := LoadMethod(SDBXReader_GetColumnCount);
FDBXReader_GetColumnMetadata := LoadMethod(SDBXReader_GetColumnMetaData);
FDBXReader_Next := LoadMethod(SDBXReader_Next);
end;
function TDBXNativeMethodTable.LoadMethod(MethodName: string): TPointer;
begin
Result := GetProcAddress(FLibraryHandle, PChar(MethodName));
if not Assigned(Result) then
begin
raise TDBXError.Create(TDBXErrorCodes.DriverInitFailed, Format(SDllProcLoadError, [MethodName]));
end;
end;
end.
|
{
Cut Edge
DFS Method O(N2)
Input:
G: Undirected Simple Graph
N: Number of vertices,
Output:
EdgeNum: Nunmber of CutEdges
EdgeList[i]: CutEdge I
Reference:
Creative, p224
By Ali
}
program
CutEdge;
const
MaxN = 100 + 2;
var
N: Integer;
G: array[1 .. MaxN, 1 .. MaxN] of Integer;
EdgeNum: Integer;
EdgeList: array[1 .. MaxN * MaxN, 1 .. 2] of Integer;
DfsNum: array[1 .. Maxn] of Integer;
DfsN: Integer;
function Dfs(V: Integer; Parent: Integer) : Integer;
var
I, J, Hi: Integer;
begin
DfsNum[V] := DfsN;
Dec(DfsN);
Hi := DfsNum[V];
for I := 1 to N do
if (G[V, I] <> 0) and (I <> Parent) then
if DfsNum[I] = 0 then
begin
J := Dfs(I, V);
if J <= DfsNum[I] then
begin
Inc(EdgeNum);
EdgeList[EdgeNum, 1] := V;
EdgeList[EdgeNum, 2] := I;
end;
if Hi < J then
Hi := J;
end
else
if Hi < DfsNum[I] then
Hi := DfsNum[I];
Dfs := Hi;
end;
procedure CutEdges;
var
I: Integer;
begin
FillChar(DfsNum, SizeOf(DfsNum), 0);
DfsN := N;
EdgeNum := 0;
for I := 1 to N do
if DfsNum[I] = 0 then
Dfs(I, 0); {I == Root of tree}
end;
begin
CutEdges;
end.
|
unit UFrmWorkerInfo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmGrid, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxStyles, dxSkinsCore, dxSkinsDefaultPainters,
dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, DB,
cxDBData, dxSkinsdxBarPainter, ImgList, ActnList, dxBar, DBClient, cxClasses,
ExtCtrls, cxGridLevel, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, cxDBLookupComboBox;
type
TFrmWorkerInfo = class(TFrmGrid)
ClmnWorkerID: TcxGridDBColumn;
ClmnWorkerName: TcxGridDBColumn;
ClmnWorkerClass: TcxGridDBColumn;
ClmnBeginTime: TcxGridDBColumn;
ClmnEndTime: TcxGridDBColumn;
CdsWorkerClass: TClientDataSet;
DsWorkerClass: TDataSource;
procedure FormShow(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actNewExecute(Sender: TObject);
procedure actRefreshExecute(Sender: TObject);
procedure grdbtblvwDataDblClick(Sender: TObject);
procedure grdbtblvwDataKeyPress(Sender: TObject; var Key: Char);
private
function QueryWorkerInfo: Boolean;
function IsAdmin: Boolean;
public
end;
var
FrmWorkerInfo: TFrmWorkerInfo;
implementation
uses UDBAccess, UMsgBox, dxForms, UFrmWorkerInfoEdit;
{$R *.dfm}
function TFrmWorkerInfo.IsAdmin: Boolean;
var
lClassID: string;
begin
lClassID := CdsData.FindField('WorkerID').AsString;
Result := lClassID = 'admin';
end;
function TFrmWorkerInfo.QueryWorkerInfo: Boolean;
var
lSqlList: TStrings;
begin
lSqlList := TStringList.Create;
try
lSqlList.Add('select * from WorkerInfo');
lSqlList.Add('select * from WorkerClass');
Result := DBAccess.ReadMultipleDataSets(lSqlList, [CdsData, CdsWorkerClass]);
finally
lSqlList.Free;
end;
end;
procedure TFrmWorkerInfo.actDeleteExecute(Sender: TObject);
begin
if CdsData.Active and not CdsData.IsEmpty then
begin
if IsAdmin then
begin
ShowMsg('“系统管理员”不允许删除!');
Exit;
end;
if not ShowConfirm('您确定要删除当前选择的角色信息吗?') then Exit;
CdsData.Delete;
if DBAccess.ApplyUpdates('WorkerInfo', CdsData.Delta) then
CdsData.MergeChangeLog
else
begin
CdsData.CancelUpdates;
ShowMsg('角色信息删除失败,请重新操作!');
end;
end;
end;
procedure TFrmWorkerInfo.actEditExecute(Sender: TObject);
begin
if CdsData.Active and not CdsData.IsEmpty then
begin
if IsAdmin then
begin
ShowMsg('“系统管理员”不允许修改!');
Exit;
end;
TFrmWorkerInfoEdit.ShowWorkerInfoEdit(CdsData, CdsWorkerClass, 'Edit');
end;
end;
procedure TFrmWorkerInfo.actNewExecute(Sender: TObject);
begin
if not CdsData.Active then Exit;
TFrmWorkerInfoEdit.ShowWorkerInfoEdit(CdsData, CdsWorkerClass, 'Append');
end;
procedure TFrmWorkerInfo.actRefreshExecute(Sender: TObject);
begin
if not QueryWorkerInfo then
ShowMsg('用户信息刷新失败!');
end;
procedure TFrmWorkerInfo.FormShow(Sender: TObject);
begin
inherited;
QueryWorkerInfo;
end;
procedure TFrmWorkerInfo.grdbtblvwDataDblClick(Sender: TObject);
begin
inherited;
actEditExecute(nil);
end;
procedure TFrmWorkerInfo.grdbtblvwDataKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
if Key = #13 then
actEditExecute(nil);
end;
initialization
dxFormManager.RegisterForm(TFrmWorkerInfo);
end.
|
unit UnFabricaDeModelos;
interface
uses
SysUtils, Classes, DB, SqlExpr, DBClient,
{ helsonsant }
Util, DataUtil, Configuracoes, UnModelo, Dominio;
type
TFabricaDeModelos = class
private
FConexao: TSQLConnection;
FConfiguracoes: TConfiguracoes;
FDataUtil: TDataUtil;
FModelos: TStringList;
FUtil: TUtil;
public
function Configuracoes(
const Configuracoes: TConfiguracoes): TFabricaDeModelos;
constructor Create(const Conexao: TSQLConnection); reintroduce;
function DataUtil(const DataUtil: TDataUtil): TFabricaDeModelos;
function Descarregar: TFabricaDeModelos;
function DescarregarModelo(const Modelo: TModelo): TFabricaDeModelos;
function ObterModelo(const NomeModelo: string): TModelo;
function Preparar: TFabricaDeModelos;
function Util(const Util: TUtil): TFabricaDeModelos;
end;
implementation
{ TFabricaDeModelos }
function TFabricaDeModelos.Descarregar: TFabricaDeModelos;
begin
while Self.FModelos.Count > 0 do
Self.DescarregarModelo(Self.FModelos.Objects[0] as TModelo);
FreeAndNil(Self.FModelos);
Result := Self;
end;
function TFabricaDeModelos.Configuracoes(
const Configuracoes: TConfiguracoes): TFabricaDeModelos;
begin
Self.FConfiguracoes := Configuracoes;
Result := Self;
end;
constructor TFabricaDeModelos.Create(const Conexao: TSQLConnection);
begin
inherited Create;
Self.FConexao := Conexao;
Self.FModelos := TStringList.Create();
end;
function TFabricaDeModelos.DataUtil(
const DataUtil: TDataUtil): TFabricaDeModelos;
begin
Self.FDataUtil := DataUtil;
Result := Self;
end;
function TFabricaDeModelos.ObterModelo(const NomeModelo: string): TModelo;
var
_modelo: Modelo;
begin
_modelo := Modelo(GetClass('T' + NomeModelo));
Result := TComponentClass(_modelo).Create(nil) as TModelo;
Result
.Util(Self.FUtil)
.DataUtil(Self.FDataUtil)
.Configuracoes(Self.FConfiguracoes)
.Preparar(Self.FConexao);
Self.FModelos.AddObject(NomeModelo, Result);
end;
function TFabricaDeModelos.Util(const Util: TUtil): TFabricaDeModelos;
begin
Self.FUtil := Util;
Result := Self;
end;
function TFabricaDeModelos.DescarregarModelo(
const Modelo: TModelo): TFabricaDeModelos;
var
_indice: Integer;
begin
_indice := Self.FModelos.IndexOfObject(Modelo);
if _indice <> -1 then
begin
(Self.FModelos.Objects[_indice] as TModelo).Descarregar;
(Self.FModelos.Objects[_indice] as TModelo).Free;
Self.FModelos.Delete(_indice);
end;
Result := Self;
end;
function TFabricaDeModelos.Preparar: TFabricaDeModelos;
begin
Result := Self;
end;
end.
|
program ExampleEnumerate;
{$ifdef MSWINDOWS}{$apptype CONSOLE}{$endif}
{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}
uses
SysUtils, IPConnection, Device;
type
TExample = class
private
ipcon: TIPConnection;
public
procedure EnumerateCB(sender: TIPConnection;
const uid: string; const connectedUid: string; const position: char;
const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
const deviceIdentifier: word; const enumerationType: byte);
procedure Execute;
end;
const
HOST = 'localhost';
PORT = 4223;
var
e: TExample;
{ Print incoming enumeration }
procedure TExample.EnumerateCB(sender: TIPConnection;
const uid: string; const connectedUid: string; const position: char;
const hardwareVersion: TVersionNumber; const firmwareVersion: TVersionNumber;
const deviceIdentifier: word; const enumerationType: byte);
begin
WriteLn('UID: ' + uid);
WriteLn('Enumerate Type: ' + IntToStr(enumerationType));
if (enumerationType <> IPCON_ENUMERATION_TYPE_DISCONNECTED) then begin
WriteLn('Connected UID: ' + connectedUid);
WriteLn('Position: ' + position);
WriteLn('Hardware Version: ' + IntToStr(hardwareVersion[0]) + '.' +
IntToStr(hardwareVersion[1]) + '.' +
IntToStr(hardwareVersion[2]));
WriteLn('Firmware Version: ' + IntToStr(firmwareVersion[0]) + '.' +
IntToStr(firmwareVersion[1]) + '.' +
IntToStr(firmwareVersion[2]));
WriteLn('Device Identifier: ' + IntToStr(deviceIdentifier));
end;
WriteLn('');
end;
procedure TExample.Execute;
begin
{ Create connection and connect to brickd }
ipcon := TIPConnection.Create;
ipcon.Connect(HOST, PORT);
{ Register enumerate callback to "EnumerateCB" }
ipcon.OnEnumerate := {$ifdef FPC}@{$endif}EnumerateCB;
{ Trigger enumerate }
ipcon.Enumerate;
WriteLn('Press key to exit');
ReadLn;
ipcon.Destroy; { Calls ipcon.Disconnect internally }
end;
begin
e := TExample.Create;
e.Execute;
e.Destroy;
end.
|
{**********************************************}
{ TeeChart JPEG related functions }
{ Copyright (c) 1996-2004 by David Berneda }
{**********************************************}
unit TeeJPEG;
{$I TeeDefs.inc}
{$IFDEF TEEOCX}
{$I TeeAXDefs.inc}
{$ENDIF}
interface
uses
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
{$IFNDEF CLX}
{$IFNDEF CLR}
JPEG,
{$ENDIF}
{$ENDIF}
TeeProcs, TeeExport, TeCanvas;
type
{$IFDEF CLX}
TJPEGPerformance=(jpBestQuality, jpSpeed);
TJPEGDefaults=packed record
GrayScale : Boolean;
ProgressiveEncoding : Boolean;
CompressionQuality : Integer;
PixelFormat : TPixelFormat;
ProgressiveDisplay : Boolean;
Performance : TJPEGPerformance;
Scale : Integer;
Smoothing : Boolean;
end;
TJPEGImage=class(TBitmap)
public
GrayScale : Boolean;
ProgressiveEncoding : Boolean;
CompressionQuality : Integer;
PixelFormat : TPixelFormat;
ProgressiveDisplay : Boolean;
Performance : TJPEGPerformance;
Scale : Integer;
Smoothing : Boolean;
end;
const
JPEGDefaults:TJPEGDefaults=(
GrayScale : False;
ProgressiveEncoding : False;
CompressionQuality : 95;
PixelFormat : TeePixelFormat;
ProgressiveDisplay : False;
Performance : jpBestQuality;
Scale : 1;
Smoothing : True;
);
type
{$ENDIF}
TTeeJPEGOptions = class(TForm)
CBGray: TCheckBox;
RGPerf: TRadioGroup;
Label1: TLabel;
EQuality: TEdit;
UpDown1: TUpDown;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
{$IFDEF CLR}
TJPEGPerformance=(jpBestQuality, jpSpeed);
TJPEGDefaults=packed record
GrayScale : Boolean;
ProgressiveEncoding : Boolean;
CompressionQuality : Integer;
PixelFormat : TPixelFormat;
ProgressiveDisplay : Boolean;
Performance : TJPEGPerformance;
Scale : Integer;
Smoothing : Boolean;
end;
const
JPEGDefaults:TJPEGDefaults=(
GrayScale : False;
ProgressiveEncoding : False;
CompressionQuality : 95;
PixelFormat : TeePixelFormat;
ProgressiveDisplay : False;
Performance : jpBestQuality;
Scale : 1;
Smoothing : True;
);
type
TJPEGImage=class(TBitmap)
public
GrayScale : Boolean;
ProgressiveEncoding : Boolean;
CompressionQuality : Integer;
PixelFormat : TPixelFormat;
ProgressiveDisplay : Boolean;
Performance : TJPEGPerformance;
Scale : Integer;
Smoothing : Boolean;
end;
{$ENDIF}
TJPEGExportFormat=class(TTeeExportFormat)
private
Procedure CheckProperties;
function GetQuality: Integer;
procedure SetQuality(const Value: Integer);
protected
FProperties : TTeeJPEGOptions;
Procedure DoCopyToClipboard; override;
public
Destructor Destroy; override; // 6.02
function Description:String; override;
function FileExtension:String; override;
function FileFilter:String; override;
Function Jpeg:TJPEGImage;
Function Options(Check:Boolean=True):TForm; override;
Procedure SaveToStream(Stream:TStream); override;
property Quality:Integer read GetQuality write SetQuality default 95;
end;
{ Returns a JPEG image from "APanel" Chart, DBChart or Draw3D }
Function TeeGetJPEGImageParams( APanel:TCustomTeePanel;
Const Params:TJPEGDefaults;
Left,Top,
Width,Height:Integer):TJPEGImage;
{ saves a Panel (Chart, Tree, etc) into a JPEG file }
procedure TeeSaveToJPEGFile( APanel:TCustomTeePanel;
Const FileName: WideString;
Gray: WordBool;
Performance: TJPEGPerformance;
Quality, AWidth, AHeight: Integer);
{ same as above, with 100% quality }
procedure TeeSaveToJPEG( APanel:TCustomTeePanel;
Const FileName: WideString;
AWidth, AHeight: Integer);
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses {$IFDEF CLX}
QClipbrd,
{$ELSE}
Clipbrd,
{$ENDIF}
TeeConst;
Function TeeGetJPEGImageParams( APanel:TCustomTeePanel;
Const Params:TJPEGDefaults;
Left,Top,
Width,Height:Integer):TJPEGImage;
var tmpBitmap : TBitmap;
begin
{ converts a Chart to JPEG }
{ create the resulting JPEG image }
result:=TJPEGImage.Create;
{ create a temporary bitmap }
tmpBitmap:=APanel.TeeCreateBitmap(APanel.Color,
TeeRect(Left,Top,Left+Width,Top+Height),
TeePixelFormat);
try
{ set the desired JPEG options... }
With result do
begin
GrayScale :=Params.GrayScale;
ProgressiveEncoding :=Params.ProgressiveEncoding;
CompressionQuality :=Params.CompressionQuality;
PixelFormat :=Params.PixelFormat;
ProgressiveDisplay :=Params.ProgressiveDisplay;
Performance :=Params.Performance;
Scale :=Params.Scale;
Smoothing :=Params.Smoothing;
{ Copy the temporary Bitmap onto the JPEG image... }
Assign(tmpBitmap);
end;
finally
tmpBitmap.Free; { <-- free the temporary Bitmap }
end;
end;
{ This function creates a JPEG Image, sets the desired JPEG
parameters, draws a Chart (or TeeTree) on it, Saves the JPEG on disk and
Loads the JPEG from disk to show it on this Form. }
procedure TeeSaveToJPEGFile( APanel:TCustomTeePanel;
Const FileName: WideString;
Gray: WordBool;
Performance: TJPEGPerformance;
Quality, AWidth, AHeight: Integer);
var tmp : String;
tmpWidth,
tmpHeight : Integer;
Params : TJPEGDefaults;
begin
{ verify filename extension }
tmp:=FileName;
if ExtractFileExt(tmp)='' then tmp:=tmp+'.jpg';
{ Set the JPEG params }
Params:=JPEGDefaults;
Params.GrayScale:=Gray;
Params.CompressionQuality:=Quality;
Params.Performance:=Performance;
if AWidth<=0 then tmpWidth:=APanel.Width
else tmpWidth:=AWidth;
if AHeight<=0 then tmpHeight:=APanel.Height
else tmpHeight:=AHeight;
{ Create the JPEG with the Chart image }
With TeeGetJPEGImageParams(APanel,Params,0,0,tmpWidth,tmpHeight) do
try
SaveToFile(tmp); { <-- save the JPEG to disk }
finally
Free; { <-- free the temporary JPEG object }
end;
end;
procedure TeeSaveToJPEG( APanel:TCustomTeePanel;
Const FileName: WideString;
AWidth, AHeight: Integer);
begin
TeeSaveToJPEGFile(APanel,FileName,False,jpBestQuality,100,AWidth,AHeight);
end;
function TJPEGExportFormat.Description:String;
begin
result:=TeeMsg_AsJPEG;
end;
function TJPEGExportFormat.FileExtension: String;
begin
result:='jpg';
end;
function TJPEGExportFormat.FileFilter:String;
begin
result:=TeeMsg_JPEGFilter;
end;
Function TJPEGExportFormat.Jpeg:TJPEGImage;
var Params : TJPEGDefaults;
begin
{ returns a JPEG image using the "Panel" (Chart) property }
if not Assigned(Panel) then
Raise Exception.Create(TeeMsg_ExportPanelNotSet);
CheckProperties;
{ set JPEG options }
Params:=JPEGDefaults;
Params.GrayScale:=FProperties.CBGray.Checked;
Params.CompressionQuality:=FProperties.UpDown1.Position;
Params.Performance:=TJPEGPerformance(FProperties.RGPerf.ItemIndex);
CheckSize;
{ obtain a JPEG image using parameters }
result:=TeeGetJPEGImageParams(Panel,Params,0,0,Width,Height);
end;
Procedure TJPEGExportFormat.CheckProperties;
begin
if not Assigned(FProperties) then
FProperties:=TTeeJPEGOptions.Create(nil);
end;
Function TJPEGExportFormat.Options(Check:Boolean=True):TForm;
begin
if Check then CheckProperties;
result:=FProperties;
end;
procedure TJPEGExportFormat.DoCopyToClipboard;
var tmp : TJPEGImage;
begin
tmp:=Jpeg;
try
Clipboard.Assign(tmp);
finally
tmp.Free;
end;
end;
procedure TJPEGExportFormat.SaveToStream(Stream:TStream);
begin
With Jpeg do
try
SaveToStream(Stream);
finally
Free;
end;
end;
procedure TTeeJPEGOptions.FormCreate(Sender: TObject);
begin
Align:=alClient;
end;
function TJPEGExportFormat.GetQuality: Integer;
begin
Options;
result:=FProperties.UpDown1.Position;
end;
procedure TJPEGExportFormat.SetQuality(const Value: Integer);
begin
Options;
FProperties.UpDown1.Position:=Value;
end;
destructor TJPEGExportFormat.Destroy;
begin
// FreeAndNil(FProperties); ?? 6.02
inherited;
end;
initialization
RegisterTeeExportFormat(TJPEGExportFormat);
finalization
UnRegisterTeeExportFormat(TJPEGExportFormat);
end.
|
unit LocalUser;
interface
uses
Role;
type
TLocalUser = class
private
FUserId: string;
FPasskey: string;
FRoles: array of TRole;
FName: string;
function GetHasName: boolean;
function GetHasPasskey: boolean;
function GetRole(const i: integer): TRole;
procedure SetRole(const i: integer; const Value: TRole);
function GetRolesCount: integer;
public
property Name: string read FName write FName;
property UserId: string read FUserId write FUserId;
property Passkey: string read FPasskey write FPasskey;
property HasName: boolean read GetHasName;
property HasPasskey: boolean read GetHasPasskey;
property Roles[const i: integer]: TRole read GetRole write SetRole;
property RolesCount: integer read GetRolesCount;
constructor Create;
end;
implementation
{ TLocalUser }
constructor TLocalUser.Create;
begin
inherited Create;
SetLength(FRoles,0);
end;
function TLocalUser.GetHasName: boolean;
begin
Result := FUserId <> '';
end;
function TLocalUser.GetHasPasskey: boolean;
begin
Result := FPasskey <> '';
end;
function TLocalUser.GetRole(const i: integer): TRole;
begin
Result := FRoles[i];
end;
function TLocalUser.GetRolesCount: integer;
begin
Result := Length(FRoles);
end;
procedure TLocalUser.SetRole(const i: integer; const Value: TRole);
begin
if i >= Length(FRoles) then SetLength(FRoles,Length(FRoles)+1);
FRoles[i] := Value;
end;
end.
|
unit uRenderer;
{$MODE Delphi}
interface
uses ExtCtrls,Windows,Forms;
Type ProcRenderer=Procedure;
procedure RendererInit(p:TPanel);
procedure RendererDestroy(p:TPanel);
procedure RendererAktivieren;
procedure RendererDeaktivieren;
procedure RendererAktualisieren;
procedure RendererStart(animation:ProcRenderer);
implementation
uses dglOpenGL;
type THilfsKruecke=class
anim:ProcRenderer;
null:ProcRenderer;
procedure AnimationsKruecke(Sender:TObject;var Done:BOOLEAN);
procedure AnimationsNull(Sender:TObject;var Done:BOOLEAN);
END;
var dc:HDC;RC:HGLRC;
VAR t:THilfsKruecke;
procedure RendererDestroy(p:TPanel);
begin
DeactivateRenderingContext;
DestroyRenderingContext(RC);
ReleaseDC(p.Handle, DC);
end;
procedure RendererAktivieren;
begin
Application.OnIdle:=t.AnimationsKruecke;
end;
procedure RendererDeaktivieren;
begin
Application.OnIdle:=t.AnimationsNull;
end;
procedure RendererInit(p:TPanel);
begin
DC:= GetDC(p.Handle);
RC:= CreateRenderingContext( DC,
[opDoubleBuffered],
32,
24,
0,0,0,
0);
ActivateRenderingContext(DC, RC);
end;
procedure RendererAktualisieren;
begin
SwapBuffers(DC);
glEnable(gl_depth_test);
glDepthFunc(GL_LEqual);
//glDepthFunc(GL_Less);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
end;
procedure RendererStart(animation:ProcRenderer);
begin
t.anim:=animation;
application.OnIdle := t.AnimationsKruecke;
end;
procedure THilfsKruecke.AnimationsKruecke(Sender:TObject;var Done:BOOLEAN);
begin
done:=false;
anim; //Aufruf der eigentlichen Animation; kann geändert werden.
RendererAktualisieren;
end;
procedure THilfsKruecke.AnimationsNull(Sender:TObject;var Done:BOOLEAN);
begin
done:=true;
end;
begin
t:=THilfskruecke.Create;
end.
|
unit PTA30402;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, DB, DBTables, Grids, DBGrids, Messages,Dialogs,SysUtils,
Mask, ExtCtrls,datelib, Tmax_DataSetText, OnPopupEdit, OnGrDBGrid,
OnFocusButton, MemDS, DBAccess, Ora, OnEditBaseCtrl, OnEditStdCtrl,
OnEditBtnCtrl;
type
TCForm = class(TForm)
DataSource1: TDataSource;
codeGrid: TOnGrDbGrid;
Panel1: TPanel;
BT_Select: TOnFocusButton;
BT_Close: TOnFocusButton;
OraQuery1: TOraQuery;
Panel2: TPanel;
E_Search: TOnButtonEdit;
procedure BT_CloseClick(Sender: TObject);
procedure codeGridDblClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure E_SearchButtonClick(Sender: TObject; ButtonIndex: Integer);
procedure E_SearchKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
Edit : TOnWinPopupEdit;
Code : String; {코드}
CodeName : String; {코드명}
Procedure Open_Grid;
end;
var
CForm: TCForm;
implementation
uses PTA30401;
{$R *.DFM}
Procedure TCForm.Open_Grid;
begin
with OraQuery1 do
begin
Close;
Sql.Clear;
if copy(MainForm.GSsysdate,1,8) < MainForm.payrachdate then
Sql.Add('SELECT ''0C'' CODENO, ')
else
Sql.Add('SELECT ''C00'' CODENO, ');
Sql.Add(' ''팀장'' CODENAME ');
Sql.Add(' FROM DUAL ');
Sql.Add('UNION ');
Sql.Add('SELECT CODENO, CODENAME ');
Sql.Add(' FROM PYCCODE ');
Sql.Add(' WHERE CODEID =''I112'' ');
Sql.Add(' and useyn = ''Y'' ');
Sql.Add(Format('AND CODENAME like ''%s''',['%'+E_Search.Text+'%']) );
Sql.Add('ORDER BY CODENO ');
Open;
end;
end;
procedure TCForm.BT_CloseClick(Sender: TObject);
begin
Code := '';
CodeName := '';
Edit.PopupForm.ClosePopup(False);
end;
procedure TCForm.codeGridDblClick(Sender: TObject);
begin
Code := OraQuery1.FieldByName('CODENO').AsString ;
CodeName := OraQuery1.FieldByName('CODENAME').AsString ;
Edit.PopupForm.ClosePopup(False);
end;
procedure TCForm.FormShow(Sender: TObject);
begin
E_Search.Text := '';
Open_Grid;
end;
procedure TCForm.E_SearchButtonClick(Sender: TObject;
ButtonIndex: Integer);
begin
Open_Grid;
end;
procedure TCForm.E_SearchKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then Open_Grid;
end;
end.
|
//1.6 se cambiaron los procedimientos de levantarbloque
unit Unidad;
interface
Uses
sysUtils;
const
LongBloque = 1024;
type
tArchivoLibres = file of word;
tNroBloque = word; //tipo de numero de bloque
tBloque = array [1 .. LongBloque] of byte; //buffer bloque
archivo = File;
tEstado = (C, E, LE);
{ C = Cerrado; E = Escritura (append) no busca espacios libres;
LE = lectura y escritura, con posicionamiento en bloques. }
tPersona = record
nombre: string[20]; // Nombre y Apellido
apellido: string[20];
dni: longword; //longword(4bytes) o string, elijan alguno.
end;
ctlPersonas = record
estado: tEstado;
arch: archivo;
b: tBloque;
ib: word;
libres: tArchivoLibres; //Archivo auxiliar con la cantidad de bytes libres por bloque
libre: word;
p: tPersona;
pe: array[1..60] of byte; //Si no es 52, cual sería más conveniente'
lpe: byte;
end;
procedure cargar (var ctrl: ctlPersonas);
procedure crear (var ctrl: ctlPersonas; nombre:string);
procedure abrir (var ctrl: ctlPersonas; modo: tEstado; nombre: String);
procedure cerrar (var ctrl: ctlPersonas);
procedure primero (var ctrl: ctlPersonas; var estado: boolean);
procedure siguiente (var ctrl: ctlPersonas; var estado: boolean);
procedure recuperar (var ctrl: ctlPersonas; dni: longword; var estado: boolean);
procedure exportar (var ctrl: ctlPersonas; nomLogTXT : string);
procedure insertar (var ctrl: ctlPersonas; var estado: boolean);
procedure eliminar (var ctrl: ctlPersonas; var estado: boolean);
procedure modificar (var ctrl: ctlPersonas; var estado: boolean);
procedure respaldar (var ctrl: ctlPersonas; var estado: boolean);
Implementation
function libre (var ctrl: ctlPersonas): integer; //En lpe se envía el tamaño del registro empaquetado persona que se guardará en el archivo. La función retorna la posición del bloque con tamaño buscado.
var
encontrado : boolean;
begin
seek (ctrl.libres, 0);
encontrado := false;
while ((not encontrado) and (FilePos (ctrl.libres) < FileSize (ctrl.libres))) do begin
read (ctrl.libres, ctrl.libre);
encontrado := (ctrl.libre >= ctrl.lpe);
end;
if encontrado then
libre := FilePos ((ctrl.libres)) -1 //Le retorno el número de bloque que contiene el espacio libre. Por eso retorno la posición, ya que son relacionales.
else
libre:= -1; //Si no hallo libre retorno un valor absurdo.
end;
{
* PRE: el índice pasado como argumento es una posición de lectura
* válida.
}
procedure LeerPersona(var b: tBloque; var i: word; var p: tPersona);
var
longNombre: byte;
begin
//levanto el dni
move(b[i+1], p.dni, sizeof(p.dni));
inc(i, sizeof(p.dni) +1);
//levanto el length del nombre
move(b[i], longNombre, 1);
//levanto el nombre (con el byte de longitud al comienzo)
move(b[i], p.nombre, longNombre+1);
inc(i, longNombre+1);
end;
procedure LeerPersona1(var ctrl: ctlPersonas; var res: boolean);
var
aux : word;
begin
aux:= 1024 - (ctrl.libre) - (ctrl.ib+1);
if ( aux > 0 ) then
begin
Move(ctrl.b[ctrl.ib+1], ctrl.p.nombre, SizeOf(ctrl.p.nombre)); //desde donde apunta IB, +1 para no incluir la longitud del string
Inc(ctrl.ib, SizeOf(ctrl.p.nombre)+1); //me queda la duda si el SizeOf al string, tambien cuenta el bye de longitud
Move(ctrl.b[ctrl.ib+1], ctrl.p.apellido, SizeOf(ctrl.p.apellido)); //pero por las dudas, lo escribo así.
Inc(ctrl.ib, SizeOf(ctrl.p.nombre)+1);
Move(ctrl.b[ctrl.ib], ctrl.p.dni, SizeOf(longword));
Inc(ctrl.ib, SizeOf(longword));
res := true;
end
else
res := false;
end;
procedure cargar (var ctrl: ctlPersonas); //Carga en los bloques y cuando está lleno lo vuelco en el archivo???
var
i: byte;
begin
if ((ctrl.estado = E) or (ctrl.estado = LE)) then begin
i:= 2; //Inicializo el índice para recorrer el registro de empaquetamiento.
move (ctrl.p.dni, ctrl.pe[i], SizeOf(ctrl.p.dni)); //Copio el dni en pe.
i:= i + SizeOf(ctrl.p.dni);
move (ctrl.p.nombre, ctrl.pe[i], (Length(ctrl.p.nombre)+1)); //Copio el nombre en pe e incluyo el prefijo del tamaño.
i:= i + Length (ctrl.p.nombre)+1; //Queda guardado la longitud del registro empaquetado.
ctrl.lpe:= i -2;
ctrl.pe[1] := ctrl.lpe; //Guardo el prefijo de longitud del registro empaquetado. Resto dos porque lo inicialicé con ese valor (para manipular arreglo).
//Guardo en el bloque buffer y actualizo su índice y la cantidad de espacio libre:
if (ctrl.libre >= ctrl.lpe) then begin
move (ctrl.pe[1], ctrl.b[ctrl.ib], ctrl.lpe +1 );
ctrl.ib := ctrl.ib + i;
ctrl.libre := ctrl.libre - (i - 1);
end
else begin //En el caso de que no me alcance el tamaño libre debo crear otro bloque y volcar este.
blockWrite (ctrl.arch, ctrl.b, 1); //Guardo el bloque buffer y creo uno nuevo.
write (ctrl.libres, ctrl.libre);
ctrl.ib:=1;
ctrl.libre:=LongBloque;
move (ctrl.pe[1], ctrl.b[1], ctrl.lpe + 1);
ctrl.ib := ctrl.ib + ctrl.lpe -1;
ctrl.libre := ctrl.libre - (ctrl.lpe + 1);
end;
end;
end;
procedure crear (var ctrl: ctlPersonas; nombre:string);
var
b: tBloque;
i: integer;
begin
assign(ctrl.arch, nombre);
assign(ctrl.libres, nombre + 'Libres');
rewrite (ctrl.arch, LongBloque);
rewrite (ctrl.libres);
for i := 1 to LongBloque do
b[i]:= 0;
blockwrite (ctrl.arch, b,1);
write (ctrl.libres, LongBloque);
ctrl.estado := C; //Ver después que decide hacer con estado. Al crearlo ya queda abierto para escrituras. (O conviene cerrarlo y abrirlo luego?)
ctrl.ib := 1;
close(ctrl.arch);
close(ctrl.libres); //Inicializo el índice del bloque buffer b para recorrerlo.
end;
procedure abrir (var ctrl: ctlPersonas; modo: tEstado; nombre: String);
begin
if(modo <> C) then
begin
assign(ctrl.arch, nombre);
assign(ctrl.libres, nombre + 'Libres');
reset (ctrl.arch, LongBloque); //Abro el archivo para lectura y le envío tamano de bloque.
reset (ctrl.libres);
ctrl.estado := modo;
if (modo = E) then begin
seek (ctrl.arch, FileSize (ctrl.arch)-1); //Me posiciono en el último bloque del archivo y lo levanto a continuación.
BlockRead (ctrl.arch, ctrl.b,1); //Guardo el bloque del archivo en el bloque buffer.
seek (ctrl.libres, FileSize (ctrl.libres)-1); //Lo mismo para el archivo de libres.
read (ctrl.libres, ctrl.libre);
ctrl.ib := LongBloque - (ctrl.libre - 1); //inicializo el puntero de b para escritura.
end;
end;
end;
procedure cerrar (var ctrl: ctlPersonas);
begin
if (ctrl.estado = E) or (ctrl.estado = LE) then begin //Verifico el estado del archivo antes de cerrar del todo.
seek (ctrl.libres,filepos(ctrl.libres)-1);
seek (ctrl.arch,filepos (ctrl.arch)-1);
blockwrite (ctrl.arch, ctrl.b, 1); //Escribo el último bloque en el archivo.
write (ctrl.libres, ctrl.libre); //Escribo la cantidad de espacio libre en el archivo de espacios libres.
end;
ctrl.estado := C;
close (ctrl.arch);
close (ctrl.libres);
end;
{
* Busca secuencialmente en el archivo de espacios libres (a partir
* de donde esté parado) un bloque que no se encuentre vacío
* (espacios libre != longBloque)
}
function getPosSiguienteBloqueNoVacio (var a: tArchivoLibres): integer;
var
libresTemp: integer;
result: integer;
begin
result:= -1;
while ((not EOF(a)) and (result = -1)) do begin
read(a, libresTemp);
if (libresTemp <> longBloque) then
result:= filePos(a) - 1;
end;
getPosSiguienteBloqueNoVacio:= result;
end;
{
* Levanta el bloque y setea todos los datos adyacentes correspondientes.
* Recibe el puntero del archivo posicionado en el bloque que se quiere
* levantar.
}
procedure levantarBloque(var ctrl: ctlPersonas);
begin
//levanto el bloque
blockRead(ctrl.arch, ctrl.b, 1);
//leo espacios libres del bloque actual
seek(ctrl.libres, filePos(ctrl.arch) - 1);
read(ctrl.libres, ctrl.libre);
end;
procedure levantarBloqueEscritura(var ctrl: ctlPersonas);
begin
levantarBloque(ctrl);
//posiciono el índice acorde al estado del archivo
ctrl.ib:= longBloque - ctrl.libre + 1;
end;
procedure levantarBloqueLectura(var ctrl: ctlPersonas);
begin
levantarBloque(ctrl);
//posiciono el índice acorde al estado del archivo
ctrl.ib:= 1;
end;
{
* PRE: archivo creado y abierto
*
* POST:
* · Deja en el bloque buffer el primer bloque en el que haya al menos un registro
* de persona (alberga la posibilidad de que haya bloques vacíos).
* · Deja el índice del bloque buffer posicionado en el primer byte del siguiente
* registro de persona.
* · Devuelve en el registro de persona del handler la persona leída.
* · result es 1 si la operación se concretó correctamente
* 0 si la operación no se concretó porque el archivo no contenía personas
}
procedure primero(var ctrl: ctlPersonas; var estado: boolean);
var
iBloqueValido: integer;
begin
if (ctrl.estado = LE) then begin
iBloqueValido:= getPosSiguienteBloqueNoVacio(ctrl.libres);
if (iBloqueValido <> -1) then begin
seek(ctrl.arch, iBloqueValido);
levantarBloqueLectura(ctrl);
leerPersona(ctrl.b, ctrl.ib, ctrl.p);
estado:= true;
end
else
estado:= false; //todos los bloques están vacíos
end;
end;
procedure siguiente (var ctrl: ctlPersonas; var estado: boolean);
var
iBloqueValido : integer;
Begin
if (longBloque - ctrl.libre + 1 > ctrl.ib) then begin
leerPersona(ctrl.b, ctrl.ib, ctrl.p);
end
else begin
iBloqueValido:= getPosSiguienteBloqueNoVacio(ctrl.libres);
if (iBloqueValido <> -1) then begin
seek(ctrl.arch, iBloqueValido);
levantarBloqueLectura(ctrl);
leerPersona(ctrl.b, ctrl.ib, ctrl.p);
estado := true;
end
else
estado := false; //Sino, ya no habia más registro. No hay siguiente porque estaba al final.
end;
End;
procedure empaquetar (var ctrl: ctlPersonas);
begin
ctrl.lpe:= 2;
move(ctrl.p.dni, ctrl.pe[ctrl.lpe], sizeof(ctrl.p.dni));
inc(ctrl.lpe, sizeof(ctrl.p.dni));
move(ctrl.p.nombre, ctrl.pe[ctrl.lpe], length(ctrl.p.nombre) + 1);
inc(ctrl.lpe, length(ctrl.p.nombre) + 1);
ctrl.pe[1]:= ctrl.lpe - 2;
dec(ctrl.lpe, 1);
end;
{
* Params
* @arch ctlPersonas
* @dni longword
* @p TPersona
* @estado integer
*
* Recibe el registro de control con el archivo abierto
* Devuelve un registro de la persona con el dni que busca
* Devuelve el resultado de la operación.
* Queda apuntando IB al siguiente reg. del bloque }
procedure recuperar (var ctrl: ctlPersonas; dni: longword; var estado: boolean);
var
encontrado : boolean;
est:boolean;
Begin
encontrado := false;
primero(ctrl, est);
if ( est ) then
begin
while ((est) and (not encontrado)) do //mientras no encuentro la persona con el dni o no se termine el archivo
begin
if ( ctrl.p.dni <> dni) then begin //busco dni
siguiente(ctrl, est) //si no lo encuentro, sigo con el proximo registro
end else
begin
encontrado := true;
empaquetar(ctrl);
end;
end;
estado := encontrado; //en el caso de haber recorrido todos los registros y no
end // encontrarlo, devuelvo 0. No se encontraba el registro
else
estado := false;
end;
procedure exportar (var ctrl: ctlPersonas; nomLogTXT : string);
var
F: text;
estado: boolean;
Begin
if (ctrl.estado = LE) then begin
assign(F, nomLogTXT+'.txt');
rewrite(F);
primero(ctrl, estado);
while ( estado ) do begin
writeln(F, ctrl.p.nombre:20 ,' ', ctrl.p.dni );
siguiente(ctrl, estado);
end;
close(F);
end;
End;
procedure insertar (var ctrl: ctlPersonas; var estado: boolean);
var
encontrado: boolean;
nBloqueAInsertar: integer;
p: tPersona;
Begin
if ( ctrl.estado = LE) then begin
p := ctrl.p;
// verificacion unicidad
recuperar(ctrl, ctrl.p.dni, encontrado); // Busco si existe en el archivo
if ( not encontrado ) then begin
ctrl.p := p;
empaquetar(ctrl);
nBloqueAInsertar := libre(ctrl);
ctrl.ib:= longBloque - ctrl.libre + 1;
if ( nBloqueAInsertar <> -1 ) then begin // inserto en el bloque
seek(ctrl.arch, nBloqueAInsertar); // me posiciono en el bloque del archivo a escribir
levantarBloqueEscritura(ctrl);
move(ctrl.pe[1], ctrl.b[ctrl.ib], ctrl.lpe);
inc(ctrl.ib, ctrl.lpe);
dec(ctrl.libre, ctrl.lpe);
seek(ctrl.libres, nBloqueAInsertar);
write(ctrl.libres, ctrl.libre);
end else begin // inserto al final
cargar(ctrl);
end;
end;
end;
End;
procedure eliminar (var ctrl: ctlPersonas; var estado: boolean);
var
est: boolean;
cant: longword;
Begin
recuperar(ctrl,ctrl.p.dni,est); // llamo a recup para buscar el registro, si no lo encuentro sale directamente
if ( est ) then begin // encontro la persona
//No cambien estas dos líneas, sé que es ilegible, pero funciona; cuando nos veamos les explicaré
//cómo funciona (pero funciona).
cant := LongBLoque - ctrl.libre - (ctrl.ib - 1);
move(ctrl.b[ctrl.ib], ctrl.b[ctrl.ib-ctrl.lpe], cant); // Mueve los registros que estaban despues del eliminado
ctrl.libre := ctrl.libre + ctrl.lpe;
seek(ctrl.arch,filepos(ctrl.arch)-1); // se posiciona y vuelve a escribir en el bloque del archivo
Blockwrite(ctrl.arch,ctrl.b,1); // el registro sin la persona para modificar
seek(ctrl.libres,filepos(ctrl.libres)-1); // se posiciona y vuelve a escribir
write(ctrl.libres,ctrl.libre); // en el archivo de espacios libres
estado:=true; //retorna 1 si es verdadero
end
else
estado:=false; // retorna 0 si es falso
End;
procedure modificar (var ctrl: ctlPersonas; var estado: boolean);
var
est: boolean;
per: tPersona;
Begin
per.dni:=ctrl.p.dni; // hacemos un
per.nombre:=ctrl.p.nombre; // backup de los datos
eliminar(ctrl, est);
if ( est ) then begin
ctrl.ib := LongBloque - (ctrl.libre - 1);
ctrl.p.dni := per.dni;
ctrl.p.nombre := per.nombre;
cargar(ctrl); // Lo ponemos al final para tener una mejor eficiencia en la escritura
estado := true;
end else
estado := false;
End;
procedure respaldar (var ctrl: ctlPersonas; var estado: boolean);
//var
Begin
End;
End.
|
unit NtUtils.Environment;
interface
uses
NtUtils.Exceptions, Ntapi.ntdef;
type
TEnvVariable = record
Name, Value: String;
end;
IEnvironment = interface
function Environment: Pointer;
function Size: NativeUInt;
function IsCurrent: Boolean;
function SetAsCurrent: TNtxStatus;
function SetAsCurrentExchange(out Old: IEnvironment): TNtxStatus;
function Enumerate: TArray<TEnvVariable>;
function SetVariable(Name, Value: String): TNtxStatus;
function DeleteVariable(Name: String): TNtxStatus;
function SetVariableEx(const Name: UNICODE_STRING;
Value: PUNICODE_STRING): TNtxStatus;
function QueryVariable(Name: String): String;
function QueryVariableWithStatus(Name: String; out Value: String):
TNtxStatus;
function Expand(Source: String): String;
function ExpandWithStatus(Source: String; out Expanded: String): TNtxStatus;
end;
TEnvironment = class (TInterfacedObject, IEnvironment)
private
FBlock: Pointer;
constructor CreateOwned(Buffer: Pointer);
public
constructor OpenCurrent;
constructor CreateNew(CloneCurrent: Boolean);
destructor Destroy; override;
function Environment: Pointer;
function Size: NativeUInt;
function IsCurrent: Boolean;
function SetAsCurrent: TNtxStatus;
function SetAsCurrentExchange(out Old: IEnvironment): TNtxStatus;
function Enumerate: TArray<TEnvVariable>;
function SetVariable(Name, Value: String): TNtxStatus;
function DeleteVariable(Name: String): TNtxStatus;
function SetVariableEx(const Name: UNICODE_STRING;
Value: PUNICODE_STRING): TNtxStatus;
function QueryVariable(Name: String): String;
function QueryVariableWithStatus(Name: String; out Value: String):
TNtxStatus;
function Expand(Source: String): String;
function ExpandWithStatus(Source: String; out Expanded: String): TNtxStatus;
end;
// Environmental block parsing routine
function RtlxEnumerateEnvironment(Environment: PWideChar;
EnvironmentLength: Cardinal; var CurrentIndex: Cardinal;
out Name: String; out Value: String): Boolean;
// Prepare an environment for a user. If token is zero the function returns only
// system environmental variables. Supports pseudo-handles.
function UnvxCreateUserEnvironment(out Environment: IEnvironment;
hToken: THandle; InheritCurrent: Boolean): TNtxStatus;
// Expand a string using the current environment
function RtlxExpandStringVar(var Str: String): TNtxStatus;
function RtlxExpandString(Str: String): String;
implementation
uses
Ntapi.ntrtl, Ntapi.ntstatus, Ntapi.ntpebteb, Ntapi.ntmmapi, Ntapi.ntseapi,
Ntapi.ntpsapi, NtUtils.Ldr, Winapi.UserEnv, NtUtils.Objects, NtUtils.Tokens;
function RtlxEnumerateEnvironment(Environment: PWideChar;
EnvironmentLength: Cardinal; var CurrentIndex: Cardinal;
out Name: String; out Value: String): Boolean;
var
pCurrentChar, pName, pValue: PWideChar;
StartIndex: Cardinal;
begin
pCurrentChar := Environment + CurrentIndex;
// Start parsing the name
StartIndex := CurrentIndex;
pName := pCurrentChar;
// Find the end of the name
repeat
if CurrentIndex >= EnvironmentLength then
Exit(False);
// The equality sign is considered as a delimiter between the name and the
// value unless it is the first character
if (pCurrentChar^ = '=') and (StartIndex <> CurrentIndex) then
Break;
if pCurrentChar^ = #0 then
Exit(False); // no more variables
Inc(CurrentIndex);
Inc(pCurrentChar);
until False;
SetString(Name, pName, CurrentIndex - StartIndex);
// Skip the equality sign
Inc(CurrentIndex);
Inc(pCurrentChar);
// Start parsing the value
StartIndex := CurrentIndex;
pValue := pCurrentChar;
// Find the end of the value
repeat
if CurrentIndex >= EnvironmentLength then
Exit(False);
// The value is zero-terminated
if pCurrentChar^ = #0 then
Break;
Inc(CurrentIndex);
Inc(pCurrentChar);
until False;
SetString(Value, pValue, CurrentIndex - StartIndex);
// Skip the #0 character
Inc(CurrentIndex);
Result := True;
end;
{ TEnvironment }
function TEnvironment.Enumerate: TArray<TEnvVariable>;
var
Ind: Cardinal;
BlockLength: Cardinal;
Name, Value: String;
begin
SetLength(Result, 0);
Ind := 0;
BlockLength := Self.Size div SizeOf(WideChar);
while RtlxEnumerateEnvironment(Environment, BlockLength, Ind, Name, Value) do
begin
SetLength(Result, Length(Result) + 1);
Result[High(Result)].Name := Name;
Result[High(Result)].Value := Value;
end;
end;
function TEnvironment.Environment: Pointer;
begin
// Always return a non-null pointer
if Assigned(FBlock) then
Result := FBlock
else
Result := RtlGetCurrentPeb.ProcessParameters.Environment;
end;
function TEnvironment.Expand(Source: String): String;
begin
if not ExpandWithStatus(Source, Result).IsSuccess then
Result := Source;
end;
function TEnvironment.ExpandWithStatus(Source: String;
out Expanded: String): TNtxStatus;
var
SrcStr, DestStr: UNICODE_STRING;
Required: Cardinal;
begin
SrcStr.FromString(Source);
Result.Location := 'RtlExpandEnvironmentStrings_U';
DestStr.MaximumLength := 0;
repeat
Required := 0;
DestStr.Length := 0;
DestStr.Buffer := AllocMem(DestStr.MaximumLength);
Result.Status := RtlExpandEnvironmentStrings_U(FBlock, SrcStr, DestStr,
@Required);
if not Result.IsSuccess then
FreeMem(DestStr.Buffer);
until not NtxExpandStringBuffer(Result, DestStr, Required);
if not Result.IsSuccess then
Exit;
Expanded := DestStr.ToString;
FreeMem(DestStr.Buffer);
end;
function TEnvironment.IsCurrent: Boolean;
begin
// Referencing null means referencing current environment
Result := not Assigned(FBlock);
end;
constructor TEnvironment.CreateNew(CloneCurrent: Boolean);
begin
NtxAssert(RtlCreateEnvironment(CloneCurrent, FBlock), 'RtlCreateEnvironment');
end;
constructor TEnvironment.CreateOwned(Buffer: Pointer);
begin
FBlock := Buffer;
end;
function TEnvironment.DeleteVariable(Name: String): TNtxStatus;
var
NameStr: UNICODE_STRING;
begin
NameStr.FromString(Name);
Result := SetVariableEx(NameStr, nil);
end;
destructor TEnvironment.Destroy;
begin
if Assigned(FBlock) then
RtlDestroyEnvironment(FBlock);
inherited;
end;
constructor TEnvironment.OpenCurrent;
begin
FBlock := nil;
end;
function TEnvironment.QueryVariable(Name: String): String;
begin
if not QueryVariableWithStatus(Name, Result).IsSuccess then
Result := '';
end;
function TEnvironment.QueryVariableWithStatus(Name: String; out Value: String):
TNtxStatus;
var
NameStr, ValueStr: UNICODE_STRING;
begin
NameStr.FromString(Name);
Result.Location := 'RtlQueryEnvironmentVariable_U';
ValueStr.MaximumLength := 0;
repeat
ValueStr.Length := 0;
ValueStr.Buffer := AllocMem(ValueStr.MaximumLength);
Result.Status := RtlQueryEnvironmentVariable_U(FBlock, NameStr, ValueStr);
if not Result.IsSuccess then
FreeMem(ValueStr.Buffer);
until not NtxExpandStringBuffer(Result, ValueStr);
if not Result.IsSuccess then
Exit;
Value := ValueStr.ToString;
FreeMem(ValueStr.Buffer);
end;
function TEnvironment.SetAsCurrent: TNtxStatus;
begin
if Assigned(FBlock) then
begin
Result.Location := 'RtlSetCurrentEnvironment';
Result.Status := RtlSetCurrentEnvironment(FBlock, nil);
// Make the object point to the current environment
if Result.IsSuccess then
FBlock := nil;
end
else
begin
// We are already pointing to the current environment, nothing to do
Result.Status := STATUS_SUCCESS;
end;
end;
function TEnvironment.SetAsCurrentExchange(out Old: IEnvironment): TNtxStatus;
var
OldEnv: Pointer;
begin
if Assigned(FBlock) then
begin
Result.Location := 'RtlSetCurrentEnvironment';
Result.Status := RtlSetCurrentEnvironment(FBlock, @OldEnv);
if Result.IsSuccess then
begin
// Store the returned pointer into a new IEnvironmnent
Old := TEnvironment.CreateOwned(OldEnv);
// Make this object point to the current environment
FBlock := nil;
end;
end
else
begin
// The caller tries to exchange the current environment with itself
Result.Status := STATUS_SUCCESS;
Old := Self;
end;
end;
function TEnvironment.SetVariable(Name, Value: String): TNtxStatus;
var
NameStr, ValueStr: UNICODE_STRING;
begin
NameStr.FromString(Name);
ValueStr.FromString(Value);
Result := SetVariableEx(NameStr, @ValueStr);
end;
function TEnvironment.SetVariableEx(const Name: UNICODE_STRING;
Value: PUNICODE_STRING): TNtxStatus;
var
EnvCopy: TEnvironment;
begin
if Assigned(FBlock) then
begin
Result.Location := 'RtlSetEnvironmentVariable';
Result.Status := RtlSetEnvironmentVariable(FBlock, Name, Value);
end
else
begin
// RtlSetEnvironmentVariable can't change variables in the current block,
// it simply allocates a new one with a new variable only
// Make a full copy, make changes to it, and set it is as current
EnvCopy := TEnvironment.CreateNew(True);
Result := EnvCopy.SetVariableEx(Name, Value);
if Result.IsSuccess then
Result := EnvCopy.SetAsCurrent;
EnvCopy.Free;
end;
end;
function TEnvironment.Size: NativeUInt;
begin
// This is the same way as RtlSetEnvironmentVariable determines the size.
// Make sure to pass a valid pointer for the call.
Result := RtlSizeHeap(NtCurrentTeb.ProcessEnvironmentBlock.ProcessHeap, 0,
Environment);
end;
function UnvxCreateUserEnvironment(out Environment: IEnvironment;
hToken: THandle; InheritCurrent: Boolean): TNtxStatus;
var
hxToken: IHandle;
EnvBlock: Pointer;
begin
Result := LdrxCheckModuleDelayedImport(userenv, 'CreateEnvironmentBlock');
if not Result.IsSuccess then
Exit;
// Handle pseudo-tokens
Result := NtxExpandPseudoToken(hxToken, hToken, TOKEN_QUERY or TOKEN_DUPLICATE
or TOKEN_IMPERSONATE);
if not Result.IsSuccess then
Exit;
Result.Location := 'CreateEnvironmentBlock';
Result.LastCall.Expects(TOKEN_QUERY or TOKEN_DUPLICATE or TOKEN_IMPERSONATE,
@TokenAccessType);
Result.Win32Result := CreateEnvironmentBlock(EnvBlock, hxToken.Handle,
InheritCurrent);
if Result.IsSuccess then
Environment := TEnvironment.CreateOwned(EnvBlock);
end;
function RtlxExpandStringVar(var Str: String): TNtxStatus;
var
Environment: IEnvironment;
ExpandedStr: String;
begin
Environment := TEnvironment.OpenCurrent;
Result := Environment.ExpandWithStatus(Str, ExpandedStr);
if Result.IsSuccess then
Str := ExpandedStr;
end;
function RtlxExpandString(Str: String): String;
var
Environment: IEnvironment;
begin
Environment := TEnvironment.OpenCurrent;
Result := Environment.Expand(Str);
end;
end.
|
Unit WlanAPIClient;
Interface
Uses
Windows, WlanAPI, Classes;
Type
TWlanAPIClient = Class
Private
FAPIVersion : DWORD;
FError : LONG;
FHandle : THandle;
Constructor Create; Reintroduce;
Public
Class Function NewInstance:TWlanAPIClient;
Destructor Destroy; Override;
Function _WlanEnumInterfaces(Var AList:PWLAN_INTERFACE_INFO_LIST):Boolean;
Function _WlanGetAvailableNetworkList(InterfaceGuid:PGUID; Flags:DWORD; Var List:PWLAN_AVAILABLE_NETWORK_LIST):Boolean;
Function _WlanConnect(pInterfaceGuid:PGUID; pConnectionParameters:PWLAN_CONNECTION_PARAMETERS):Boolean;
Function _WlanDisconnect(pInterfaceGuid:PGUID):Boolean;
Function _WlanGetNetworkBssList(pInterfaceGuid:PGUID; pDot11Ssid:PDOT11_SSID; dot11BssType:DWORD; bSecurityEnabled:BOOL; Var pWlanBssList:PWLAN_BSS_LIST):Boolean;
Function EnumInterfaces(AList:TList):Boolean;
Property Error : LONG Read FError;
Property APIVersion : DWORD Read FAPIVersion;
end;
Implementation
Uses
WlanInterface;
Constructor TWlanAPIClient.Create;
begin
Inherited Create;
FHandle := 0;
end;
Destructor TWlanAPIClient.Destroy;
begin
If FHandle <> 0 Then
WlanCloseHandle(FHandle, Nil);
Inherited Destroy;
end;
Class Function TWlanAPIClient.NewInstance:TWlanAPIClient;
begin
Try
Result := TWlanAPIClient.Create;
Except
Result := Nil;
end;
If Assigned(Result) Then
begin
Result.FError := WlanOpenHandle(WLANAPI_CLIENT_VISTA, Nil, Result.FAPIVersion, Result.FHandle);
If Result.FError <> ERROR_SUCCESS Then
begin
Result.Free;
Result := Nil
end;
end;
end;
Function TWlanAPIClient._WlanEnumInterfaces(Var AList:PWLAN_INTERFACE_INFO_LIST):Boolean;
begin
FError := WlanAPI.WlanEnumInterfaces(FHandle, Nil, AList);
Result := FError = ERROR_SUCCESS;
end;
Function TWlanAPIClient._WlanGetAvailableNetworkList(InterfaceGuid:PGUID; Flags:DWORD; Var List:PWLAN_AVAILABLE_NETWORK_LIST):Boolean;
begin
FError := WlanAPI.WlanGetAvailableNetworkList(FHandle, InterfaceGuid, Flags, Nil, List);
Result := FError = ERROR_SUCCESS;
end;
Function TWlanAPICLient.EnumInterfaces(AList:TList):Boolean;
Var
I, J : Integer;
List : PWLAN_INTERFACE_INFO_LIST;
Tmp : TWlanInterface;
begin
Result := _WlanEnumInterfaces(List);
If Result Then
begin
For I := 0 To List.dwNumberOfItems - 1 Do
begin
List.dwIndex := I;
Tmp := TWlanInterface.NewInstance(Self, List);
Result := Assigned(Tmp);
If Result Then
begin
AList.Add(Tmp);
end
Else begin
For J := I - 1 DownTo 0 Do
TWlanInterface(AList[J]).Free;
AList.Clear;
FError := ERROR_NOT_ENOUGH_MEMORY;
Break;
end;
end;
WlanFreeMemory(List);
end;
end;
Function TWlanAPIClient._WlanConnect(pInterfaceGuid:PGUID; pConnectionParameters:PWLAN_CONNECTION_PARAMETERS):Boolean;
begin
FError := WlanConnect(FHandle, pInterfaceGuid, pConnectionParameters, Nil);
Result := FError = ERROR_SUCCESS;
end;
Function TWlanAPIClient._WlanDisconnect(pInterfaceGuid:PGUID):Boolean;
begin
FError := WlanDisconnect(FHandle, pInterfaceGuid, Nil);
Result := FError = ERROR_SUCCESS;
end;
Function TWlanAPIClient._WlanGetNetworkBssList(pInterfaceGuid:PGUID; pDot11Ssid:PDOT11_SSID; dot11BssType:DWORD; bSecurityEnabled:BOOL; Var pWlanBssList:PWLAN_BSS_LIST):Boolean;
begin
FError := WlanGetNetworkBssList(FHandle, pInterfaceGuid, pDot11Ssid, dot11BssType, bSecurityEnabled, Nil, pWlanBssList);
Result := FError = ERROR_SUCCESS;
end;
End.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Datasnap.DSProxy;
interface
uses System.JSON, Data.DBXCommon, Data.DBXJSONReflect, Data.DbxCompressionFilter;
type
/// <summary>Base class for generated proxies which implements the most
/// important DSAdmin functions.</summary>
TDSAdminClient = class
protected
FDBXConnection: TDBXConnection;
FInstanceOwner: Boolean;
FMarshal: TJSONMarshal;
FUnMarshal: TJSONUnMarshal;
private
FGetPlatformNameCommand: TDBXCommand;
FClearResourcesCommand: TDBXCommand;
FFindPackagesCommand: TDBXCommand;
FFindClassesCommand: TDBXCommand;
FFindMethodsCommand: TDBXCommand;
FGetServerMethodsCommand: TDBXCommand;
FGetServerMethodParametersCommand: TDBXCommand;
FGetDatabaseConnectionPropertiesCommand: TDBXCommand;
FBroadcastToChannelCommand: TDBXCommand;
FBroadcastObjectToChannelCommand: TDBXCommand;
FNotifyCallbackCommand: TDBXCommand;
FNotifyObjectCommand: TDBXCommand;
FListClassesCommand: TDBXCommand;
FDescribeClassCommand: TDBXCommand;
FListMethodsCommand: TDBXCommand;
FDescribeMethodCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function GetPlatformName: string;
function ClearResources: Boolean;
function FindPackages: TDBXReader;
function FindClasses(PackageName: string; ClassPattern: string): TDBXReader;
function FindMethods(PackageName: string; ClassPattern: string; MethodPattern: string): TDBXReader;
function GetServerMethods: TDBXReader;
function GetServerMethodParameters: TDBXReader;
function GetDatabaseConnectionProperties: TDBXReader;
function BroadcastToChannel(ChannelName: string; Msg: TJSONValue): Boolean;
function BroadcastObjectToChannel(ChannelName: string; Msg: TObject): Boolean;
function NotifyCallback(ClientId: string; CallbackId: string; Msg: TJSONValue; out Response: TJSONValue): Boolean; overload;
function NotifyObject(ClientId: string; CallbackId: string; Msg: TObject; out Response: TObject): Boolean; overload;
function ListClasses: TJSONArray;
function DescribeClass(ClassName: string): TJSONObject;
function ListMethods(ClassName: string): TJSONArray;
function DescribeMethod(ServerMethodName: string): TJSONObject;
{$IFNDEF NEXTGEN}
/// <summary> Deprecated: Use NotifyCallback which takes no ChannelName, instead.</summary>
function NotifyCallback(ChannelName: string; ClientId: string; CallbackId: string; Msg: TJSONValue; out Response: TJSONValue): Boolean; overload; deprecated 'ChannelName is no longer required';
/// <summary> Deprecated: Use NotifyObject which takes no ChannelName, instead.</summary>
function NotifyObject(ChannelName: string; ClientId: string; CallbackId: string; Msg: TObject; out Response: TObject): Boolean; overload; deprecated 'ChannelName is no longer required';
{$ENDIF !NEXTGEN}
property InstanceOwner: Boolean read FInstanceOwner;
end;
implementation
uses System.Classes, Data.DBXClient, System.SysUtils;
{ TDSAdminClient }
function TDSAdminClient.GetPlatformName: string;
begin
if FGetPlatformNameCommand = nil then
begin
FGetPlatformNameCommand := FDBXConnection.CreateCommand;
FGetPlatformNameCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGetPlatformNameCommand.Text := 'DSAdmin.GetPlatformName';
FGetPlatformNameCommand.Prepare;
end;
FGetPlatformNameCommand.ExecuteUpdate;
Result := FGetPlatformNameCommand.Parameters[0].Value.GetWideString;
end;
function TDSAdminClient.ClearResources: Boolean;
begin
if FClearResourcesCommand = nil then
begin
FClearResourcesCommand := FDBXConnection.CreateCommand;
FClearResourcesCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FClearResourcesCommand.Text := 'DSAdmin.ClearResources';
FClearResourcesCommand.Prepare;
end;
FClearResourcesCommand.ExecuteUpdate;
Result := FClearResourcesCommand.Parameters[0].Value.GetBoolean;
end;
function TDSAdminClient.FindPackages: TDBXReader;
begin
if FFindPackagesCommand = nil then
begin
FFindPackagesCommand := FDBXConnection.CreateCommand;
FFindPackagesCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FFindPackagesCommand.Text := 'DSAdmin.FindPackages';
FFindPackagesCommand.Prepare;
end;
FFindPackagesCommand.ExecuteUpdate;
Result := FFindPackagesCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner);
end;
function TDSAdminClient.FindClasses(PackageName: string; ClassPattern: string): TDBXReader;
begin
if FFindClassesCommand = nil then
begin
FFindClassesCommand := FDBXConnection.CreateCommand;
FFindClassesCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FFindClassesCommand.Text := 'DSAdmin.FindClasses';
FFindClassesCommand.Prepare;
end;
FFindClassesCommand.Parameters[0].Value.SetWideString(PackageName);
FFindClassesCommand.Parameters[1].Value.SetWideString(ClassPattern);
FFindClassesCommand.ExecuteUpdate;
Result := FFindClassesCommand.Parameters[2].Value.GetDBXReader(FInstanceOwner);
end;
function TDSAdminClient.FindMethods(PackageName: string; ClassPattern: string; MethodPattern: string): TDBXReader;
begin
if FFindMethodsCommand = nil then
begin
FFindMethodsCommand := FDBXConnection.CreateCommand;
FFindMethodsCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FFindMethodsCommand.Text := 'DSAdmin.FindMethods';
FFindMethodsCommand.Prepare;
end;
FFindMethodsCommand.Parameters[0].Value.SetWideString(PackageName);
FFindMethodsCommand.Parameters[1].Value.SetWideString(ClassPattern);
FFindMethodsCommand.Parameters[2].Value.SetWideString(MethodPattern);
FFindMethodsCommand.ExecuteUpdate;
Result := FFindMethodsCommand.Parameters[3].Value.GetDBXReader(FInstanceOwner);
end;
function TDSAdminClient.GetServerMethods: TDBXReader;
begin
if FGetServerMethodsCommand = nil then
begin
FGetServerMethodsCommand := FDBXConnection.CreateCommand;
FGetServerMethodsCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGetServerMethodsCommand.Text := 'DSAdmin.GetServerMethods';
FGetServerMethodsCommand.Prepare;
end;
FGetServerMethodsCommand.ExecuteUpdate;
Result := FGetServerMethodsCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner);
end;
function TDSAdminClient.GetServerMethodParameters: TDBXReader;
begin
if FGetServerMethodParametersCommand = nil then
begin
FGetServerMethodParametersCommand := FDBXConnection.CreateCommand;
FGetServerMethodParametersCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGetServerMethodParametersCommand.Text := 'DSAdmin.GetServerMethodParameters';
FGetServerMethodParametersCommand.Prepare;
end;
FGetServerMethodParametersCommand.ExecuteUpdate;
Result := FGetServerMethodParametersCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner);
end;
function TDSAdminClient.GetDatabaseConnectionProperties: TDBXReader;
begin
if FGetDatabaseConnectionPropertiesCommand = nil then
begin
FGetDatabaseConnectionPropertiesCommand := FDBXConnection.CreateCommand;
FGetDatabaseConnectionPropertiesCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FGetDatabaseConnectionPropertiesCommand.Text := 'DSAdmin.GetDatabaseConnectionProperties';
FGetDatabaseConnectionPropertiesCommand.Prepare;
end;
FGetDatabaseConnectionPropertiesCommand.ExecuteUpdate;
Result := FGetDatabaseConnectionPropertiesCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner);
end;
function TDSAdminClient.BroadcastToChannel(ChannelName: string; Msg: TJSONValue): Boolean;
begin
if FBroadcastToChannelCommand = nil then
begin
FBroadcastToChannelCommand := FDBXConnection.CreateCommand;
FBroadcastToChannelCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FBroadcastToChannelCommand.Text := 'DSAdmin.BroadcastToChannel';
FBroadcastToChannelCommand.Prepare;
end;
FBroadcastToChannelCommand.Parameters[0].Value.SetWideString(ChannelName);
FBroadcastToChannelCommand.Parameters[1].Value.SetJSONValue(Msg, FInstanceOwner);
FBroadcastToChannelCommand.ExecuteUpdate;
Result := FBroadcastToChannelCommand.Parameters[2].Value.GetBoolean;
end;
function TDSAdminClient.BroadcastObjectToChannel(ChannelName: string; Msg: TObject): Boolean;
begin
if FBroadcastObjectToChannelCommand = nil then
begin
FBroadcastObjectToChannelCommand := FDBXConnection.CreateCommand;
FBroadcastObjectToChannelCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FBroadcastObjectToChannelCommand.Text := 'DSAdmin.BroadcastObjectToChannel';
FBroadcastObjectToChannelCommand.Prepare;
end;
FBroadcastObjectToChannelCommand.Parameters[0].Value.SetWideString(ChannelName);
if not Assigned(Msg) then
FBroadcastObjectToChannelCommand.Parameters[1].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FBroadcastObjectToChannelCommand.Parameters[1].ConnectionHandler).GetJSONMarshaler;
try
FBroadcastObjectToChannelCommand.Parameters[1].Value.SetJSONValue(FMarshal.Marshal(Msg), True);
if FInstanceOwner then
Msg.Free
finally
FreeAndNil(FMarshal)
end
end;
FBroadcastObjectToChannelCommand.ExecuteUpdate;
Result := FBroadcastObjectToChannelCommand.Parameters[2].Value.GetBoolean;
end;
function TDSAdminClient.NotifyCallback(ClientId: string; CallbackId: string; Msg: TJSONValue; out Response: TJSONValue): Boolean;
begin
if FNotifyCallbackCommand = nil then
begin
FNotifyCallbackCommand := FDBXConnection.CreateCommand;
FNotifyCallbackCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FNotifyCallbackCommand.Text := 'DSAdmin.NotifyCallback';
FNotifyCallbackCommand.Prepare;
end;
FNotifyCallbackCommand.Parameters[0].Value.SetWideString(ClientId);
FNotifyCallbackCommand.Parameters[1].Value.SetWideString(CallbackId);
FNotifyCallbackCommand.Parameters[2].Value.SetJSONValue(Msg, FInstanceOwner);
FNotifyCallbackCommand.ExecuteUpdate;
Response := TJSONValue(FNotifyCallbackCommand.Parameters[3].Value.GetJSONValue(FInstanceOwner));
Result := FNotifyCallbackCommand.Parameters[4].Value.GetBoolean;
end;
function TDSAdminClient.NotifyObject(ClientId: string; CallbackId: string; Msg: TObject; out Response: TObject): Boolean;
begin
if FNotifyObjectCommand = nil then
begin
FNotifyObjectCommand := FDBXConnection.CreateCommand;
FNotifyObjectCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FNotifyObjectCommand.Text := 'DSAdmin.NotifyObject';
FNotifyObjectCommand.Prepare;
end;
FNotifyObjectCommand.Parameters[0].Value.SetWideString(ClientId);
FNotifyObjectCommand.Parameters[1].Value.SetWideString(CallbackId);
if not Assigned(Msg) then
FNotifyObjectCommand.Parameters[2].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FNotifyObjectCommand.Parameters[2].ConnectionHandler).GetJSONMarshaler;
try
FNotifyObjectCommand.Parameters[2].Value.SetJSONValue(FMarshal.Marshal(Msg), True);
if FInstanceOwner then
Msg.Free
finally
FreeAndNil(FMarshal)
end
end;
FNotifyObjectCommand.ExecuteUpdate;
if not FNotifyObjectCommand.Parameters[3].Value.IsNull then
begin
FUnMarshal := TDBXClientCommand(FNotifyObjectCommand.Parameters[3].ConnectionHandler).GetJSONUnMarshaler;
try
Response := TObject(FUnMarshal.UnMarshal(FNotifyObjectCommand.Parameters[3].Value.GetJSONValue(True)));
finally
FreeAndNil(FUnMarshal)
end;
end
else
Response := nil;
Result := FNotifyObjectCommand.Parameters[4].Value.GetBoolean;
end;
function TDSAdminClient.ListClasses: TJSONArray;
begin
if FListClassesCommand = nil then
begin
FListClassesCommand := FDBXConnection.CreateCommand;
FListClassesCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FListClassesCommand.Text := 'DSAdmin.ListClasses';
FListClassesCommand.Prepare;
end;
FListClassesCommand.ExecuteUpdate;
Result := TJSONArray(FListClassesCommand.Parameters[0].Value.GetJSONValue(FInstanceOwner));
end;
function TDSAdminClient.DescribeClass(ClassName: string): TJSONObject;
begin
if FDescribeClassCommand = nil then
begin
FDescribeClassCommand := FDBXConnection.CreateCommand;
FDescribeClassCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FDescribeClassCommand.Text := 'DSAdmin.DescribeClass';
FDescribeClassCommand.Prepare;
end;
FDescribeClassCommand.Parameters[0].Value.SetWideString(ClassName);
FDescribeClassCommand.ExecuteUpdate;
Result := TJSONObject(FDescribeClassCommand.Parameters[1].Value.GetJSONValue(FInstanceOwner));
end;
function TDSAdminClient.ListMethods(ClassName: string): TJSONArray;
begin
if FListMethodsCommand = nil then
begin
FListMethodsCommand := FDBXConnection.CreateCommand;
FListMethodsCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FListMethodsCommand.Text := 'DSAdmin.ListMethods';
FListMethodsCommand.Prepare;
end;
FListMethodsCommand.Parameters[0].Value.SetWideString(ClassName);
FListMethodsCommand.ExecuteUpdate;
Result := TJSONArray(FListMethodsCommand.Parameters[1].Value.GetJSONValue(FInstanceOwner));
end;
function TDSAdminClient.DescribeMethod(ServerMethodName: string): TJSONObject;
begin
if FDescribeMethodCommand = nil then
begin
FDescribeMethodCommand := FDBXConnection.CreateCommand;
FDescribeMethodCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FDescribeMethodCommand.Text := 'DSAdmin.DescribeMethod';
FDescribeMethodCommand.Prepare;
end;
FDescribeMethodCommand.Parameters[0].Value.SetWideString(ServerMethodName);
FDescribeMethodCommand.ExecuteUpdate;
Result := TJSONObject(FDescribeMethodCommand.Parameters[1].Value.GetJSONValue(FInstanceOwner));
end;
constructor TDSAdminClient.Create(ADBXConnection: TDBXConnection);
begin
Create(ADBXConnection, True);
end;
constructor TDSAdminClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create;
if ADBXConnection = nil then
raise EInvalidOperation.Create('Connection cannot be nil. Make sure the connection has been opened.');
FDBXConnection := ADBXConnection;
FInstanceOwner := AInstanceOwner;
end;
destructor TDSAdminClient.Destroy;
begin
FreeAndNil(FGetPlatformNameCommand);
FreeAndNil(FClearResourcesCommand);
FreeAndNil(FFindPackagesCommand);
FreeAndNil(FFindClassesCommand);
FreeAndNil(FFindMethodsCommand);
FreeAndNil(FGetServerMethodsCommand);
FreeAndNil(FGetServerMethodParametersCommand);
FreeAndNil(FGetDatabaseConnectionPropertiesCommand);
FreeAndNil(FBroadcastToChannelCommand);
FreeAndNil(FBroadcastObjectToChannelCommand);
FreeAndNil(FNotifyCallbackCommand);
FreeAndNil(FNotifyObjectCommand);
FreeAndNil(FListClassesCommand);
FreeAndNil(FDescribeClassCommand);
FreeAndNil(FListMethodsCommand);
FreeAndNil(FDescribeMethodCommand);
inherited;
end;
{$IFNDEF NEXTGEN}
function TDSAdminClient.NotifyCallback(ChannelName, ClientId, CallbackId: string; Msg: TJSONValue;
out Response: TJSONValue): Boolean;
begin
Result := NotifyCallback(ClientId, CallbackId, Msg, Response);
end;
function TDSAdminClient.NotifyObject(ChannelName, ClientId, CallbackId: string; Msg: TObject;
out Response: TObject): Boolean;
begin
Result := NotifyObject(ClientId, CallbackId, Msg, Response);
end;
{$ENDIF !NEXTGEN}
end.
|
{ Access functions for I/O ports for GPC on an IA32 platform. This
unit is *not* portable. It works only on IA32 platforms (tested
under Linux and DJGPP). It is provided here only to serve as a
replacement for BP's Port and PortW pseudo arrays.
Copyright (C) 1998-2005 Free Software Foundation, Inc.
Author: Frank Heckenbach <frank@pascal.gnu.de>
This file is part of GNU Pascal.
GNU Pascal 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, or (at your
option) any later version.
GNU Pascal 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 GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030303}
{$error This unit requires GPC release 20030303 or newer.}
{$endif}
{$ifndef __i386__}
{$error The Ports unit is only for the IA32 platform}
{$endif}
unit Ports;
interface
{ Port access functions }
function InPortB (PortNumber: ShortWord): Byte;
function InPortW (PortNumber: ShortWord): ShortWord;
procedure OutPortB (PortNumber: ShortWord; aValue: Byte);
procedure OutPortW (PortNumber, aValue: ShortWord);
{ libc functions for getting access to the ports -- only for root
processes, of course -- and to give up root privileges after
getting access to the ports for setuid root programs. Dummies
under DJGPP. }
{$ifdef MSDOS}
function IOPerm (From, Num: MedCard; On: Integer): Integer; attribute (name = 'ioperm');
function IOPL (Level: Integer): Integer; attribute (name = 'iopl');
function SetEUID (EUID: Integer): Integer; attribute (name = 'seteuid');
{$else}
function IOPerm (From, Num: MedCard; On: Integer): Integer; external name 'ioperm';
function IOPL (Level: Integer): Integer; external name 'iopl';
function SetEUID (EUID: Integer): Integer; external name 'seteuid';
{$endif}
implementation
function InPortB (PortNumber: ShortWord): Byte;
var aValue: Byte;
begin
asm volatile ('inb %%dx, %%al' : '=a' (aValue) : 'd' (PortNumber));
InPortB := aValue
end;
function InPortW (PortNumber: ShortWord): ShortWord;
var aValue: ShortWord;
begin
asm volatile ('inw %%dx, %%ax' : '=a' (aValue) : 'd' (PortNumber));
InPortW := aValue
end;
procedure OutPortB (PortNumber: ShortWord; aValue: Byte);
begin
asm volatile ('outb %%al, %%dx' : : 'd' (PortNumber), 'a' (aValue))
end;
procedure OutPortW (PortNumber, aValue: ShortWord);
begin
asm volatile ('outw %%ax, %%dx' : : 'd' (PortNumber), 'a' (aValue))
end;
{$ifdef MSDOS}
function IOPerm (From, Num: MedCard; On: Integer): Integer;
begin
Discard (From);
Discard (Num);
Discard (On);
IOPerm := 0
end;
function IOPL (Level: Integer): Integer;
begin
Discard (Level);
IOPL := 0
end;
function SetEUID (EUID: Integer): Integer;
begin
Discard (EUID);
SetEUID := 0
end;
{$endif}
end.
|
unit Restaurantes.Utils;
interface
uses
System.JSON.Writers,
System.SysUtils,
System.StrUtils,
System.NetEncoding,
System.Classes,
FireDAC.Comp.Client,
Data.Db,
Data.DBXPlatform,
Restaurantes.Constantes;
type
TUtils = class
private
public
class procedure AddJSONValue(const AWriter: TJSONTextWriter; const AQuery: TFDQuery; const AContador: Integer);
class procedure FormatarJSON(const AIDCode: Integer; const AContent: string);
end;
implementation
uses
REST.JSON;
{ TUtils }
class procedure TUtils.AddJSONValue(const AWriter: TJSONTextWriter;
const AQuery: TFDQuery; const AContador: Integer);
var
ftTipoCampo : TFieldType;
StreamIn : TStream;
StreamOut : TStringStream;
begin
//Pegar o nome do campo
AWriter.WritePropertyName(AQuery.Fields[AContador].FieldName);
ftTipoCampo := AQuery.Fields.Fields[AContador].DataType;
case ftTipoCampo of
ftString, ftFmtMemo, ftMemo, ftWideString, ftWideMemo, ftUnknown:
AWriter.WriteValue(AQuery.Fields[AContador].AsString);
//Devolvendo a imagem em Base64
ftBlob :
begin
StreamIn := AQuery.CreateBlobStream(AQuery.Fields.Fields[AContador], bmRead);
StreamOut := TStringStream.Create;
TNetEncoding.Base64.Encode(StreamIn, StreamOut);
StreamOut.Position := 0;
AWriter.WriteValue(StreamOut.DataString);
end;
ftSmallint, ftInteger, ftWord, ftLongWord, ftShortint, ftLargeint, ftByte:
AWriter.WriteValue(AQuery.Fields[AContador].AsInteger);
ftBoolean:
AWriter.WriteValue(AQuery.Fields[AContador].AsBoolean);
ftFloat, ftCurrency, ftExtended, ftFMTBcd, ftBCD:
AWriter.WriteValue(AQuery.Fields[AContador].AsFloat);
ftDate:
if not AQuery.Fields[AContador].IsNull then
AWriter.WriteValue(FormatDatetime('DD/MM/YYYY', AQuery.Fields[AContador].AsDateTime))
else
AWriter.WriteValue('');
ftDateTime:
if not AQuery.Fields[AContador].IsNull then
AWriter.WriteValue(FormatDatetime('DD/MM/YYYY hh:nn:ss', AQuery.Fields[AContador].AsDateTime))
else
AWriter.WriteValue('');
ftTime, ftTimeStamp:
if not AQuery.Fields[AContador].IsNull then
AWriter.WriteValue(FormatDatetime('HH:NN:SS', AQuery.Fields[AContador].AsDateTime))
else
AWriter.WriteValue('');
ftBytes:
AWriter.WriteValue(AQuery.Fields[AContador].AsBytes);
end;
end;
class procedure TUtils.FormatarJSON(const AIDCode: Integer;
const AContent: string);
begin
GetInvocationMetadata().ResponseCode := AIDCode;
GetInvocationMetadata().ResponseContent := AContent;
end;
end.
|
unit SDIMAIN;
interface
uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls,
Vcl.Menus, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls,
Vcl.ImgList, Vcl.StdActns, Vcl.ActnList, Vcl.ToolWin, System.ImageList,
System.Actions, uParserQuery, FireDAC.VCLUI.Memo;
type
TSDIAppForm = class(TForm)
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
ToolBar1: TToolBar;
ToolButton9: TToolButton;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
ActionList1: TActionList;
FileNew1: TAction;
FileOpen1: TAction;
FileSave1: TAction;
FileSaveAs1: TAction;
FileExit1: TAction;
EditCut1: TEditCut;
EditCopy1: TEditCopy;
EditPaste1: TEditPaste;
HelpAbout1: TAction;
StatusBar: TStatusBar;
ImageList1: TImageList;
MainMenu1: TMainMenu;
File1: TMenuItem;
FileNewItem: TMenuItem;
FileOpenItem: TMenuItem;
FileSaveItem: TMenuItem;
FileSaveAsItem: TMenuItem;
N1: TMenuItem;
FileExitItem: TMenuItem;
Edit1: TMenuItem;
CutItem: TMenuItem;
CopyItem: TMenuItem;
PasteItem: TMenuItem;
Help1: TMenuItem;
HelpAboutItem: TMenuItem;
actSetting: TAction;
ToolButton7: TToolButton;
ToolButton8: TToolButton;
actQuery: TAction;
Panel2: TPanel;
GroupBox2: TGroupBox;
FDGUIxFormsMemo2: TFDGUIxFormsMemo;
GroupBox3: TGroupBox;
FDGUIxFormsMemo3: TFDGUIxFormsMemo;
Panel1: TPanel;
GroupBox1: TGroupBox;
FDGUIxFormsMemo1: TFDGUIxFormsMemo;
Splitter2: TSplitter;
Splitter3: TSplitter;
GroupBox4: TGroupBox;
FDGUIxFormsMemo4: TFDGUIxFormsMemo;
Splitter4: TSplitter;
ToolButton10: TToolButton;
actInsert: TAction;
actUpdate: TAction;
actDelete: TAction;
ToolButton11: TToolButton;
ToolButton12: TToolButton;
ToolButton13: TToolButton;
procedure FileNew1Execute(Sender: TObject);
procedure FileOpen1Execute(Sender: TObject);
procedure FileSave1Execute(Sender: TObject);
procedure FileExit1Execute(Sender: TObject);
procedure HelpAbout1Execute(Sender: TObject);
procedure actSettingExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure actQueryExecute(Sender: TObject);
private
{ Private declarations }
FParserQuery: TParserQuery;
//
procedure showLog(const S: string);
procedure doOnLine(const S: string);
procedure doResultLine(const S: string);
procedure showStatus(const S: string);
procedure showResult(const S: string);
public
{ Public declarations }
end;
var
SDIAppForm: TSDIAppForm;
implementation
uses About, uFrmSetting;
{$R *.dfm}
procedure TSDIAppForm.FileNew1Execute(Sender: TObject);
begin
{ Do nothing }
end;
procedure TSDIAppForm.FileOpen1Execute(Sender: TObject);
begin
OpenDialog.Execute;
end;
procedure TSDIAppForm.FileSave1Execute(Sender: TObject);
begin
SaveDialog.Execute;
end;
procedure TSDIAppForm.FormCreate(Sender: TObject);
begin
FParserQuery := TParserQuery.Create;
FParserQuery.initial('');
FParserQuery.OnLine := doOnLine;
FParserQuery.OnResultLine := doResultLine;
// self.WindowState := wsMaximized;
end;
procedure TSDIAppForm.FormDestroy(Sender: TObject);
begin
FParserQuery.Free;
end;
procedure TSDIAppForm.actQueryExecute(Sender: TObject);
begin
self.FDGUIxFormsMemo3.clear;
self.FDGUIxFormsMemo4.clear;
FParserQuery.Columns := self.FDGUIxFormsMemo2.Lines.Text;
FParserQuery.Context := self.FDGUIxFormsMemo1.Lines;
end;
procedure TSDIAppForm.actSettingExecute(Sender: TObject);
begin
frmSetting.ShowModal;
end;
procedure TSDIAppForm.doOnLine(const S: string);
begin
showLog(S);
showStatus(S);
end;
procedure TSDIAppForm.doResultLine(const S: string);
begin
showResult(S);
showStatus(S);
end;
procedure TSDIAppForm.FileExit1Execute(Sender: TObject);
begin
Close;
end;
procedure TSDIAppForm.HelpAbout1Execute(Sender: TObject);
begin
AboutBox.ShowModal;
end;
procedure TSDIAppForm.showLog(const S: string);
begin
self.FDGUIxFormsMemo4.Lines.Add(S);
end;
procedure TSDIAppForm.showResult(const S: string);
begin
self.FDGUIxFormsMemo3.Lines.Add(S);
end;
procedure TSDIAppForm.showStatus(const S: string);
begin
self.StatusBar.Panels[0].Text := S;
Application.ProcessMessages;
end;
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ Copyright (c) 1997 Master-Bank }
{ }
{*******************************************************}
unit rxIcoList;
interface
{$I RX.INC}
uses
Messages, Windows,
SysUtils, Classes, Graphics;
type
{ TIconList class }
TIconList = class(TPersistent)
private
FList: TList;
FUpdateCount: Integer;
FOnChange: TNotifyEvent;
procedure ReadData(Stream: TStream);
procedure WriteData(Stream: TStream);
procedure SetUpdateState(Updating: Boolean);
procedure IconChanged(Sender: TObject);
function AddIcon(Icon: TIcon): Integer;
protected
procedure Changed; virtual;
procedure DefineProperties(Filer: TFiler); override;
function Get(Index: Integer): TIcon; virtual;
function GetCount: Integer; virtual;
procedure Put(Index: Integer; Icon: TIcon); virtual;
public
constructor Create;
destructor Destroy; override;
function Add(Icon: TIcon): Integer; virtual;
function AddResource(Instance: THandle; ResId: PChar): Integer; virtual;
procedure Assign(Source: TPersistent); override;
procedure BeginUpdate;
procedure EndUpdate;
procedure Clear; virtual;
procedure Delete(Index: Integer); virtual;
procedure Exchange(Index1, Index2: Integer); virtual;
function IndexOf(Icon: TIcon): Integer; virtual;
procedure Insert(Index: Integer; Icon: TIcon); virtual;
procedure InsertResource(Index: Integer; Instance: THandle;
ResId: PChar); virtual;
procedure LoadResource(Instance: THandle; const ResIds: array of PChar);
procedure LoadFromStream(Stream: TStream); virtual;
procedure Move(CurIndex, NewIndex: Integer); virtual;
procedure SaveToStream(Stream: TStream); virtual;
property Count: Integer read GetCount;
property Icons[Index: Integer]: TIcon read Get write Put; default;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
implementation
{ TIconList }
constructor TIconList.Create;
begin
inherited Create;
FList := TList.Create;
end;
destructor TIconList.Destroy;
begin
FOnChange := nil;
Clear;
FList.Free;
inherited Destroy;
end;
procedure TIconList.BeginUpdate;
begin
if FUpdateCount = 0 then SetUpdateState(True);
Inc(FUpdateCount);
end;
procedure TIconList.Changed;
begin
if (FUpdateCount = 0) and Assigned(FOnChange) then FOnChange(Self);
end;
procedure TIconList.EndUpdate;
begin
Dec(FUpdateCount);
if FUpdateCount = 0 then SetUpdateState(False);
end;
procedure TIconList.ReadData(Stream: TStream);
var
Len, Cnt: Longint;
I: Integer;
Icon: TIcon;
Mem: TMemoryStream;
begin
BeginUpdate;
try
Clear;
Mem := TMemoryStream.Create;
try
Stream.Read(Cnt, SizeOf(Longint));
for I := 0 to Cnt - 1 do begin
Stream.Read(Len, SizeOf(Longint));
if Len > 0 then begin
Icon := TIcon.Create;
try
Mem.SetSize(Len);
Stream.Read(Mem.Memory^, Len);
Mem.Position := 0;
Icon.LoadFromStream(Mem);
AddIcon(Icon);
except
Icon.Free;
raise;
end;
end
else AddIcon(nil);
end;
finally
Mem.Free;
end;
finally
EndUpdate;
end;
end;
procedure TIconList.WriteData(Stream: TStream);
var
I: Integer;
Len: Longint;
Mem: TMemoryStream;
begin
Mem := TMemoryStream.Create;
try
Len := FList.Count;
Stream.Write(Len, SizeOf(Longint));
for I := 0 to FList.Count - 1 do begin
Mem.Clear;
if (Icons[I] <> nil) and not Icons[I].Empty then begin
Icons[I].SaveToStream(Mem);
Len := Mem.Size;
end
else Len := 0;
Stream.Write(Len, SizeOf(Longint));
if Len > 0 then Stream.Write(Mem.Memory^, Mem.Size);
end;
finally
Mem.Free;
end;
end;
procedure TIconList.DefineProperties(Filer: TFiler);
function DoWrite: Boolean;
var
I: Integer;
Ancestor: TIconList;
begin
Ancestor := TIconList(Filer.Ancestor);
if (Ancestor <> nil) and (Ancestor.Count = Count) and (Count > 0) then
begin
Result := False;
for I := 0 to Count - 1 do begin
Result := Icons[I] <> Ancestor.Icons[I];
if Result then Break;
end
end
else Result := Count > 0;
end;
begin
Filer.DefineBinaryProperty('Icons', ReadData, WriteData,
DoWrite);
end;
function TIconList.Get(Index: Integer): TIcon;
begin
Result := TObject(FList[Index]) as TIcon;
end;
function TIconList.GetCount: Integer;
begin
Result := FList.Count;
end;
procedure TIconList.IconChanged(Sender: TObject);
begin
Changed;
end;
procedure TIconList.Put(Index: Integer; Icon: TIcon);
begin
BeginUpdate;
try
if Index = Count then Add(nil);
if Icons[Index] = nil then FList[Index] := TIcon.Create;
Icons[Index].OnChange := IconChanged;
Icons[Index].Assign(Icon);
finally
EndUpdate;
end;
end;
function TIconList.AddIcon(Icon: TIcon): Integer;
begin
Result := FList.Add(Icon);
if Icon <> nil then Icon.OnChange := IconChanged;
Changed;
end;
function TIconList.Add(Icon: TIcon): Integer;
var
Ico: TIcon;
begin
Ico := TIcon.Create;
try
Ico.Assign(Icon);
Result := AddIcon(Ico);
except
Ico.Free;
raise;
end;
end;
function TIconList.AddResource(Instance: THandle; ResId: PChar): Integer;
var
Ico: TIcon;
begin
Ico := TIcon.Create;
try
Ico.Handle := LoadIcon(Instance, ResId);
Result := AddIcon(Ico);
except
Ico.Free;
raise;
end;
end;
procedure TIconList.Assign(Source: TPersistent);
var
I: Integer;
begin
if Source = nil then Clear
else if Source is TIconList then begin
BeginUpdate;
try
Clear;
for I := 0 to TIconList(Source).Count - 1 do
Add(TIconList(Source)[I]);
finally
EndUpdate;
end;
end
else if Source is TIcon then begin
BeginUpdate;
try
Clear;
Add(TIcon(Source));
finally
EndUpdate;
end;
end
else inherited Assign(Source);
end;
procedure TIconList.Clear;
var
I: Integer;
begin
BeginUpdate;
try
for I := FList.Count - 1 downto 0 do Delete(I);
finally
EndUpdate;
end;
end;
procedure TIconList.Delete(Index: Integer);
var
Icon: TIcon;
begin
Icon := Icons[Index];
if Icon <> nil then begin
Icon.OnChange := nil;
Icon.Free;
end;
FList.Delete(Index);
Changed;
end;
procedure TIconList.Exchange(Index1, Index2: Integer);
begin
FList.Exchange(Index1, Index2);
Changed;
end;
function TIconList.IndexOf(Icon: TIcon): Integer;
begin
Result := FList.IndexOf(Icon);
end;
procedure TIconList.InsertResource(Index: Integer; Instance: THandle;
ResId: PChar);
var
Ico: TIcon;
begin
Ico := TIcon.Create;
try
Ico.Handle := LoadIcon(Instance, ResId);
FList.Insert(Index, Ico);
Ico.OnChange := IconChanged;
except
Ico.Free;
raise;
end;
Changed;
end;
procedure TIconList.Insert(Index: Integer; Icon: TIcon);
var
Ico: TIcon;
begin
Ico := TIcon.Create;
try
Ico.Assign(Icon);
FList.Insert(Index, Ico);
Ico.OnChange := IconChanged;
except
Ico.Free;
raise;
end;
Changed;
end;
procedure TIconList.LoadResource(Instance: THandle; const ResIds: array of PChar);
var
I: Integer;
begin
BeginUpdate;
try
for I := Low(ResIds) to High(ResIds) do
AddResource(Instance, ResIds[I]);
finally
EndUpdate;
end;
end;
procedure TIconList.Move(CurIndex, NewIndex: Integer);
begin
FList.Move(CurIndex, NewIndex);
Changed;
end;
procedure TIconList.SetUpdateState(Updating: Boolean);
begin
if not Updating then Changed;
end;
procedure TIconList.LoadFromStream(Stream: TStream);
begin
ReadData(Stream);
end;
procedure TIconList.SaveToStream(Stream: TStream);
begin
WriteData(Stream);
end;
end. |
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC TFDBatchMove dataset driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Comp.BatchMove.DataSet;
interface
uses
System.Classes, Data.DB,
FireDAC.Stan.Intf,
FireDAC.Comp.Client, FireDAC.Comp.BatchMove;
type
TFDBatchMoveDataSetDriver = class;
TFDBatchMoveDataSetReader = class;
TFDBatchMoveDataSetWriter = class;
TFDBatchMoveDataSetDriver = class(TFDBatchMoveDriver, IFDBatchMoveDriver)
private
FActive: Boolean;
FDataSet: TDataSet;
FOptimise: Boolean;
procedure SetDataSet(const AValue: TDataSet);
function GetProvider: IProviderSupportNG;
function GetFDDataSet: TFDAdaptedDataSet; inline;
function IsMemTable: Boolean;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
// IFDBatchMoveDriver
function CheckDefined(ARaise: Boolean): Boolean; virtual;
procedure Open(AStartTx: Boolean); virtual;
procedure Close(AStopTxError: Boolean); virtual;
procedure Refresh; virtual;
procedure AbortJob;
function AddAutoFields: Boolean;
procedure DeleteAutoFields;
function GetCatalog: String;
function GetIsUnicode: Boolean;
function GetIsOpen: Boolean; virtual;
function GetFieldCount: Integer;
function GetFieldName(AIndex: Integer): String;
function GetFieldIndex(const AName: String; ACheck: Boolean): Integer;
function GetFieldInfo(AIndex: Integer; var AType: TFDDataType;
var ASize: LongWord; var APrec, AScale: Integer; var AInKey, AIsIdentity: Boolean): TObject;
procedure GetTableDefs(AFieldDefs: TFieldDefs; AIndexDefs: TIndexDefs);
// introduced
property DataSet: TDataSet read FDataSet write SetDataSet;
property Optimise: Boolean read FOptimise write FOptimise default True;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Provider: IProviderSupportNG read GetProvider;
property FDDataSet: TFDAdaptedDataSet read GetFDDataSet;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDBatchMoveDataSetReader = class(TFDBatchMoveDataSetDriver, IFDBatchMoveReader)
private
FRewind: Boolean;
protected
// IFDBatchMoveReader
function GetSourceTableName: String;
procedure Open(AStartTx: Boolean); override;
procedure ReadHeader;
function Eof: Boolean;
procedure ReadRecord;
function GetFieldValue(AField: TObject): Variant;
procedure NextRecord;
procedure GuessFormat(AAnalyze: TFDBatchMoveAnalyze = [taDelimSep, taHeader, taFields]);
public
constructor Create(AOwner: TComponent); override;
published
property Rewind: Boolean read FRewind write FRewind default True;
property DataSet;
property Optimise;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDBatchMoveDataSetWriter = class(TFDBatchMoveDataSetDriver, IFDBatchMoveWriter)
private
FConnection: TFDCustomConnection;
FDisconnected: Boolean;
FDirect: Boolean;
protected
// IFDBatchMoveWriter
procedure Open(AStartTx: Boolean); override;
procedure Close(AStopTxError: Boolean); override;
procedure Refresh; override;
procedure CreateTable;
procedure StartTransaction;
procedure CommitTransaction;
procedure RollbackTransaction;
procedure Erase(ANoUndo: Boolean);
procedure WriteHeader;
procedure SetFieldValue(AField: TObject; const AValue: Variant);
function FindRecord: Boolean;
function InsertRecord: Integer;
function UpdateRecord: Integer;
function DeleteRecord: Integer;
function FlushRecords: Integer;
published
property Direct: Boolean read FDirect write FDirect default False;
property DataSet;
property Optimise;
end;
implementation
uses
System.SysUtils,
FireDAC.Stan.Util, FireDAC.Stan.Consts, FireDAC.Stan.Error, FireDAC.Stan.Option,
FireDAC.Comp.DataSet;
{-------------------------------------------------------------------------------}
{ TFDBatchMoveDataSetDriver }
{-------------------------------------------------------------------------------}
constructor TFDBatchMoveDataSetDriver.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FOptimise := True;
end;
{-------------------------------------------------------------------------------}
destructor TFDBatchMoveDataSetDriver.Destroy;
begin
DataSet := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetDriver.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if Operation = opRemove then
if AComponent = DataSet then
DataSet := nil;
inherited Notification(AComponent, Operation);
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetDriver.SetDataSet(const AValue: TDataSet);
begin
if DataSet <> AValue then begin
if DataSet <> nil then
DataSet.RemoveFreeNotification(Self);
FDataSet := AValue;
if DataSet <> nil then
DataSet.FreeNotification(Self);
end;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.GetProvider: IProviderSupportNG;
begin
Result := DataSet as IProviderSupportNG;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.GetFDDataSet: TFDAdaptedDataSet;
begin
Result := TFDAdaptedDataSet(DataSet);
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.IsMemTable: Boolean;
begin
Result := (DataSet <> nil) and (DataSet is TFDCustomMemTable) and
(TFDCustomMemTable(DataSet).Command = nil);
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.CheckDefined(ARaise: Boolean): Boolean;
var
iErr: Integer;
begin
Result := (DataSet <> nil) and
not ((BatchMove.Reader <> nil) and (TObject(BatchMove.Reader) is TFDBatchMoveDataSetDriver) and
(BatchMove.Writer <> nil) and (TObject(BatchMove.Writer) is TFDBatchMoveDataSetDriver) and
(TFDBatchMoveDataSetDriver(BatchMove.Reader).DataSet = TFDBatchMoveDataSetDriver(BatchMove.Writer).DataSet));
if not Result and ARaise then begin
if Self is TFDBatchMoveDataSetReader then
iErr := er_FD_DPNoSrcDS
else
iErr := er_FD_DPNoDestDS;
FDException(BatchMove, [S_FD_LComp, S_FD_LComp_PDM], iErr, []);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetDriver.Open(AStartTx: Boolean);
begin
FActive := DataSet.Active;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetDriver.Close(AStopTxError: Boolean);
begin
DataSet.Active := FActive;
DataSet.EnableControls;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetDriver.Refresh;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetDriver.AbortJob;
begin
if (DataSet <> nil) and (DataSet is TFDAdaptedDataSet) then
TFDAdaptedDataSet(DataSet).AbortJob(True);
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.AddAutoFields: Boolean;
begin
// nothing
Result := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetDriver.DeleteAutoFields;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.GetCatalog: String;
begin
if (DataSet is TFDAdaptedDataSet) and
(TFDAdaptedDataSet(DataSet).PointedConnection <> nil) and
(TFDAdaptedDataSet(DataSet).PointedConnection.ConnectionIntf <> nil) then
Result := TFDAdaptedDataSet(DataSet).PointedConnection.ConnectionIntf.CurrentCatalog
else
Result := '';
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.GetIsUnicode: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.GetIsOpen: Boolean;
begin
Result := DataSet.Active;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.GetFieldCount: Integer;
begin
Result := DataSet.FieldCount;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.GetFieldName(AIndex: Integer): String;
begin
Result := DataSet.Fields[AIndex].FieldName;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.GetFieldIndex(const AName: String; ACheck: Boolean): Integer;
var
oField: TField;
begin
if ACheck then
Result := DataSet.FieldByName(AName).Index
else begin
oField := DataSet.FindField(AName);
if oField <> nil then
Result := oField.Index
else
Result := -1;
end;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetDriver.GetFieldInfo(AIndex: Integer; var AType: TFDDataType;
var ASize: LongWord; var APrec, AScale: Integer; var AInKey, AIsIdentity: Boolean): TObject;
var
eAttrs: TFDDataAttributes;
oField: TField;
begin
AType := dtUnknown;
ASize := 0;
APrec := 0;
AScale := 0;
eAttrs := [];
oField := DataSet.Fields[AIndex];
TFDFormatOptions.FieldDef2ColumnDef(oField, AType, ASize, APrec, AScale, eAttrs);
AInKey := pfInKey in oField.ProviderFlags;
AIsIdentity := (oField is TFDAutoIncField) or
(DataSet is TFDDataSet) and (caAutoInc in TFDDataSet(DataSet).GetFieldColumn(oField).ActualAttributes);
Result := oField;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetDriver.GetTableDefs(AFieldDefs: TFieldDefs; AIndexDefs: TIndexDefs);
var
oIndDefs: TIndexDefs;
sKeyFields: String;
oInd: TIndexDef;
begin
if not DataSet.FieldDefs.Updated then
DataSet.FieldDefs.Update;
AFieldDefs.Assign(DataSet.FieldDefs);
oIndDefs := nil;
sKeyFields := '';
try
if Provider <> nil then begin
oIndDefs := Provider.PSGetIndexDefs();
sKeyFields := Provider.PSGetKeyFields();
end;
if oIndDefs = nil then
AIndexDefs.Clear
else
AIndexDefs.Assign(oIndDefs);
finally
FDFree(oIndDefs);
end;
if sKeyFields <> '' then begin
oInd := AIndexDefs.GetIndexForFields(sKeyFields, False);
if oInd <> nil then begin
if not (ixPrimary in oInd.Options) then
oInd.Options := oInd.Options + [ixPrimary];
end
else
AIndexDefs.Add('', sKeyFields, [ixPrimary]);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDBatchMoveDataSetReader }
{-------------------------------------------------------------------------------}
constructor TFDBatchMoveDataSetReader.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FRewind := True;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetReader.GetSourceTableName: String;
begin
if Provider <> nil then
Result := Provider.PSGetTableName
else
Result := '';
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetReader.Open(AStartTx: Boolean);
var
oFO: TFDFetchOptions;
begin
inherited Open(AStartTx);
DataSet.DisableControls;
if Optimise and not DataSet.Active and
(DataSet is TFDAdaptedDataSet) and not IsMemTable and FDDataSet.ClientCursor then begin
oFO := FDDataSet.FetchOptions;
oFO.Items := [fiBlobs, fiDetails];
oFO.Mode := fmOnDemand;
if oFO.RowsetSize < BatchMove.CommitCount then
oFO.RowsetSize := BatchMove.CommitCount;
oFO.Cache := [];
if (FDDataSet.IndexName = '') and (FDDataSet.IndexFieldNames = '') then
oFO.Unidirectional := True;
end;
if Rewind and DataSet.Active and not DataSet.Bof then
try
DataSet.First;
except
if not IsMemTable then begin
DataSet.Close;
DataSet.Open;
end;
end
else
DataSet.Active := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetReader.ReadHeader;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetReader.Eof: Boolean;
begin
Result := DataSet.Eof;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetReader.ReadRecord;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetReader.GetFieldValue(AField: TObject): Variant;
begin
Result := TField(AField).Value;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetReader.NextRecord;
begin
try
DataSet.Next;
except
DataSet.UpdateCursorPos;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetReader.GuessFormat(AAnalyze: TFDBatchMoveAnalyze);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
{ TFDBatchMoveDataSetWriter }
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetWriter.Open(AStartTx: Boolean);
begin
inherited Open(AStartTx);
FDisconnected := False;
FConnection := nil;
if DataSet is TFDAdaptedDataSet then begin
FConnection := FDDataSet.PointedConnection;
if FConnection <> nil then begin
FDisconnected := not FConnection.Connected;
FConnection.Connected := True;
end;
end;
DataSet.DisableControls;
if (poCreateDest in BatchMove.Options) and
(DataSet is TFDDataSet) and not FDDataSet.Exists then
CreateTable;
if DataSet is TFDAdaptedDataSet then begin
if Optimise then begin
FDDataSet.FetchOptions.Items := [fiMeta];
FDDataSet.FetchOptions.Mode := fmManual;
FDDataSet.UpdateOptions.FastUpdates := True;
end;
if (FDDataSet.Command <> nil) and (FDDataSet.Command.CommandText.Count > 0) then
FDDataSet.Online;
end;
if AStartTx and (BatchMove.CommitCount > 0) then
StartTransaction;
FActive := DataSet.Active;
DataSet.Active := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetWriter.CreateTable;
begin
if (DataSet is TFDDataSet) and not FDDataSet.Exists then begin
FDDataSet.Active := False;
BatchMove.Reader.GetTableDefs(FDDataSet.FieldDefs, FDDataSet.IndexDefs);
FDDataSet.CreateDataSet;
end
else
FDCapabilityNotSupported(BatchMove, [S_FD_LComp, S_FD_LComp_PDM]);
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetWriter.Close(AStopTxError: Boolean);
begin
inherited Close(AStopTxError);
if AStopTxError then
RollbackTransaction
else
CommitTransaction;
if (FConnection <> nil) and FDisconnected then
FConnection.Connected := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetWriter.Refresh;
begin
inherited Refresh;
if not IsMemTable then
if DataSet is TFDAdaptedDataSet then
FDDataSet.Disconnect
else
DataSet.Close;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetWriter.StartTransaction;
begin
if poUseTransactions in BatchMove.Options then
if (Provider <> nil) and not Provider.PSInTransaction then
Provider.PSStartTransaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetWriter.RollbackTransaction;
begin
if poUseTransactions in BatchMove.Options then
if (Provider <> nil) and Provider.PSInTransaction then
Provider.PSEndTransaction(False);
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetWriter.CommitTransaction;
begin
if poUseTransactions in BatchMove.Options then
if (Provider <> nil) and Provider.PSInTransaction then
Provider.PSEndTransaction(True);
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetWriter.Erase(ANoUndo: Boolean);
begin
if (Direct or ANoUndo) and (DataSet is TFDAdaptedDataSet) then begin
FDDataSet.ServerDeleteAll(ANoUndo);
FDDataSet.Refresh;
end
else begin
DataSet.First;
while not DataSet.IsEmpty do
DataSet.Delete;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetWriter.WriteHeader;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDBatchMoveDataSetWriter.SetFieldValue(AField: TObject;
const AValue: Variant);
begin
TField(AField).Value := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetWriter.FindRecord: Boolean;
begin
if Direct and (DataSet is TFDAdaptedDataSet) then begin
FDDataSet.ServerSetKey;
BatchMove.Mappings.Move(True);
Result := FDDataSet.ServerGotoKey;
end
else
Result := DataSet.Locate(BatchMove.Mappings.KeyFields, BatchMove.Mappings.KeyValues, []);
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetWriter.InsertRecord: Integer;
begin
if Direct and (DataSet is TFDAdaptedDataSet) then begin
FDDataSet.ServerAppend;
BatchMove.Mappings.Move(False);
FDDataSet.ServerPerform;
end
else begin
DataSet.Append;
try
BatchMove.Mappings.Move(False);
DataSet.Post;
except
DataSet.Cancel;
raise;
end;
end;
Result := 1;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetWriter.UpdateRecord: Integer;
begin
if Direct and (DataSet is TFDAdaptedDataSet) then begin
FDDataSet.ServerEdit;
BatchMove.Mappings.Move(False);
FDDataSet.ServerPerform;
end
else begin
DataSet.Edit;
try
BatchMove.Mappings.Move(False);
DataSet.Post;
except
DataSet.Cancel;
raise;
end;
end;
Result := 1;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetWriter.DeleteRecord: Integer;
begin
if Direct and (DataSet is TFDAdaptedDataSet) then begin
FDDataSet.ServerDelete;
BatchMove.Mappings.Move(False);
FDDataSet.ServerPerform;
end
else
DataSet.Delete;
Result := 1;
end;
{-------------------------------------------------------------------------------}
function TFDBatchMoveDataSetWriter.FlushRecords: Integer;
begin
// nothing
Result := 0;
end;
end.
|
{
@abstract(@code(google.maps.Map) class from Google Maps API.)
@author(Xavier Martinez (cadetill) <cadetill@gmail.com>)
@created(Septembre 30, 2015)
@lastmod(October 1, 2015)
The GMMap contains the implementation of TCustomGMMap class that encapsulate the @code(google.maps.Map) class from Google Maps API and other related classes.
}
unit GMMap;
{$I ..\gmlib.inc}
{$R ..\Resources\gmmapres.RES}
interface
uses
{$IFDEF DELPHIXE2}
System.SysUtils, System.Classes,
{$ELSE}
SysUtils, Classes,
{$ENDIF}
GMClasses, GMLatLng, GMLatLngBounds, GMSets;
type
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMMapTypeControlOptions.txt)
TGMMapTypeControlOptions = class(TGMPersistentStr)
private
FMapTypeIds: TGMMapTypeIds;
FStyle: TGMMapTypeControlStyle;
FPosition: TGMControlPosition;
procedure SetMapTypeIds(const Value: TGMMapTypeIds);
procedure SetPosition(const Value: TGMControlPosition);
procedure SetStyle(const Value: TGMMapTypeControlStyle);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\docs\GMMap.TGMMapTypeControlOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMMapTypeControlOptions.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\docs\GMMap.TGMMapTypeControlOptions.MapTypeIds.txt)
property MapTypeIds: TGMMapTypeIds read FMapTypeIds write SetMapTypeIds default [mtHYBRID, mtROADMAP, mtSATELLITE, mtTERRAIN, mtOSM];
// @include(..\docs\GMMap.TGMMapTypeControlOptions.Position.txt)
property Position: TGMControlPosition read FPosition write SetPosition default cpTOP_RIGHT;
// @include(..\docs\GMMap.TGMMapTypeControlOptions.Style.txt)
property Style: TGMMapTypeControlStyle read FStyle write SetStyle default mtcDEFAULT;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMOverviewMapControlOptions.txt)
TGMOverviewMapControlOptions = class(TGMPersistentStr)
private
FOpened: Boolean;
procedure SetOpened(const Value: Boolean);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\docs\GMMap.TGMOverviewMapControlOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMOverviewMapControlOptions.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\docs\GMMap.TGMOverviewMapControlOptions.Opened.txt)
property Opened: Boolean read FOpened write SetOpened default False;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMPanControlOptions.txt)
TGMPanControlOptions = class(TGMPersistentStr)
private
FPosition: TGMControlPosition;
procedure SetPosition(const Value: TGMControlPosition);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\docs\GMMap.TGMPanControlOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMPanControlOptions.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\docs\GMMap.TGMPanControlOptions.Position.txt)
property Position: TGMControlPosition read FPosition write SetPosition default cpTOP_LEFT;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMRotateControlOptions.txt)
TGMRotateControlOptions = class(TGMPersistentStr)
private
FPosition: TGMControlPosition;
procedure SetPosition(const Value: TGMControlPosition);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\docs\GMMap.TGMRotateControlOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMRotateControlOptions.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\docs\GMMap.TGMRotateControlOptions.Position.txt)
property Position: TGMControlPosition read FPosition write SetPosition default cpTOP_LEFT;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMScaleControlOptions.txt)
TGMScaleControlOptions = class(TGMPersistentStr)
private
FStyle: TGMScaleControlStyle;
procedure SetStyle(const Value: TGMScaleControlStyle);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\docs\GMMap.TGMScaleControlOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMScaleControlOptions.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\docs\GMMap.TGMScaleControlOptions.Style.txt)
property Style: TGMScaleControlStyle read FStyle write SetStyle default scDEFAULT;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMZoomControlOptions.txt)
TGMZoomControlOptions = class(TGMPersistentStr)
private
FStyle: TGMZoomControlStyle;
FPosition: TGMControlPosition;
procedure SetStyle(const Value: TGMZoomControlStyle);
procedure SetPosition(const Value: TGMControlPosition);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\docs\GMMap.TGMZoomControlOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMZoomControlOptions.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\docs\GMMap.TGMZoomControlOptions.Position.txt)
property Position: TGMControlPosition read FPosition write SetPosition default cpTOP_LEFT;
// @include(..\docs\GMMap.TGMZoomControlOptions.Style.txt)
property Style: TGMZoomControlStyle read FStyle write SetStyle default zcDEFAULT;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMStreetViewControlOptions.txt)
TGMStreetViewControlOptions = class(TGMPersistentStr)
private
FPosition: TGMControlPosition;
procedure SetPosition(const Value: TGMControlPosition);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\docs\GMMap.TGMStreetViewControlOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMStreetViewControlOptions.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\docs\GMMap.TGMStreetViewControlOptions.Position.txt)
property Position: TGMControlPosition read FPosition write SetPosition default cpTOP_LEFT;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMCustomMapTypeStyler.txt)
TGMCustomMapTypeStyler = class(TGMInterfacedCollectionItem)
private
FSaturation: Integer;
FGamma: Real;
FLightness: Integer;
FInvertLightness: Boolean;
FVisibility: TGMVisibility;
FWeight: Integer;
procedure SetGamma(const Value: Real);
procedure SetInvertLightness(const Value: Boolean);
procedure SetLightness(const Value: Integer);
procedure SetSaturation(const Value: Integer);
procedure SetVisibility(const Value: TGMVisibility);
procedure SetWeight(const Value: Integer);
protected
// @exclude
function GetAPIUrl: string; override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
// @include(..\docs\GMMap.TGMCustomMapTypeStyler.Gamma.txt)
property Gamma: Real read FGamma write SetGamma;
// @include(..\docs\GMMap.TGMCustomMapTypeStyler.InvertLightness.txt)
property InvertLightness: Boolean read FInvertLightness write SetInvertLightness default True;
// @include(..\docs\GMMap.TGMCustomMapTypeStyler.Lightness.txt)
property Lightness: Integer read FLightness write SetLightness default 0;
// @include(..\docs\GMMap.TGMCustomMapTypeStyler.Saturation.txt)
property Saturation: Integer read FSaturation write SetSaturation default 0;
// @include(..\docs\GMMap.TGMCustomMapTypeStyler.Visibility.txt)
property Visibility: TGMVisibility read FVisibility write SetVisibility default vOn;
// @include(..\docs\GMMap.TGMCustomMapTypeStyler.Weight.txt)
property Weight: Integer read FWeight write SetWeight default 0;
public
// @include(..\docs\GMMap.TGMCustomMapTypeStyler.Create.txt)
constructor Create(Collection: TCollection); override;
// @include(..\docs\GMMap.TGMCustomMapTypeStyler.Assign.txt)
procedure Assign(Source: TPersistent); override;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMCustomMapTypeStyle.txt)
TGMCustomMapTypeStyle = class(TGMInterfacedCollectionItem)
private
FElementType: TGMMapTypeStyleElementType;
FFeatureType: TGMMapTypeStyleFeatureType;
procedure SetElementType(const Value: TGMMapTypeStyleElementType);
procedure SetFeatureType(const Value: TGMMapTypeStyleFeatureType);
protected
// @exclude
function GetAPIUrl: string; override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
// @include(..\docs\GMMap.TGMCustomMapTypeStyle.ElementType.txt)
property ElementType: TGMMapTypeStyleElementType read FElementType write SetElementType default setALL;
// @include(..\docs\GMMap.TGMCustomMapTypeStyle.FeatureType.txt)
property FeatureType: TGMMapTypeStyleFeatureType read FFeatureType write SetFeatureType default sftALL;
public
// @include(..\docs\GMMap.TGMCustomMapTypeStyle.Create.txt)
constructor Create(Collection: TCollection); override;
// @include(..\docs\GMMap.TGMCustomMapTypeStyle.Assign.txt)
procedure Assign(Source: TPersistent); override;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMStreetViewAddressControlOptions.txt)
TGMStreetViewAddressControlOptions = class(TGMPersistentStr)
private
FPosition: TGMControlPosition;
procedure SetPosition(const Value: TGMControlPosition);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\docs\GMMap.TGMStreetViewAddressControlOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMStreetViewAddressControlOptions.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\docs\GMMap.TGMStreetViewAddressControlOptions.Position.txt)
property Position: TGMControlPosition read FPosition write SetPosition default cpTOP_LEFT;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMFullScreenControlOptions.txt)
TGMFullScreenControlOptions = class(TGMPersistentStr)
private
FPosition: TGMControlPosition;
procedure SetPosition(const Value: TGMControlPosition);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\docs\GMClasses.TGMInterfacedOwnedPersistent.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMFullScreenControlOptions.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\docs\GMMap.TGMFullScreenControlOptions.Position.txt)
property Position: TGMControlPosition read FPosition write SetPosition default cpRIGHT_TOP;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMStreetViewPov.txt)
TGMStreetViewPov = class(TGMPersistentStr)
private
FPitch: Integer;
FHeading: Integer;
procedure SetHeading(const Value: Integer);
procedure SetPitch(const Value: Integer);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\docs\GMMap.TGMStreetViewPov.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMStreetViewPov.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\docs\GMMap.TGMStreetViewPov.Heading.txt)
property Heading: Integer read FHeading write SetHeading default 0;
// @include(..\docs\GMMap.TGMStreetViewPov.Pitch.txt)
property Pitch: Integer read FPitch write SetPitch default 0;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.txt)
TGMStreetViewPanoramaOptions = class(TGMPersistentStr)
private
FAddressControlOptions: TGMStreetViewAddressControlOptions;
FScrollwheel: Boolean;
FZoomControlOptions: TGMZoomControlOptions;
FAddressControl: Boolean;
FDisableDoubleClickZoom: Boolean;
FClickToGo: Boolean;
FZoomControl: Boolean;
FPanControlOptions: TGMPanControlOptions;
FLinksControl: Boolean;
FVisible: Boolean;
FPanControl: Boolean;
FEnableCloseButton: Boolean;
FPov: TGMStreetViewPov;
FImageDateControl: Boolean;
FDisableDefaultUI: Boolean;
FFullScreenControlOptions: TGMFullScreenControlOptions;
FFullScreenControl: Boolean;
procedure SetAddressControl(const Value: Boolean);
procedure SetClickToGo(const Value: Boolean);
procedure SetDisableDefaultUI(const Value: Boolean);
procedure SetDisableDoubleClickZoom(const Value: Boolean);
procedure SetEnableCloseButton(const Value: Boolean);
procedure SetImageDateControl(const Value: Boolean);
procedure SetLinksControl(const Value: Boolean);
procedure SetPanControl(const Value: Boolean);
procedure SetScrollwheel(const Value: Boolean);
procedure SetVisible(const Value: Boolean);
procedure SetZoomControl(const Value: Boolean);
procedure SetFullScreenControl(const Value: Boolean);
protected
// @exclude
function GetAPIUrl: string; override;
public
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.Destroy.txt)
destructor Destroy; override;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
published
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.AddressControl.txt)
property AddressControl: Boolean read FAddressControl write SetAddressControl default True;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.AddressControlOptions.txt)
property AddressControlOptions: TGMStreetViewAddressControlOptions read FAddressControlOptions write FAddressControlOptions;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.ClickToGo.txt)
property ClickToGo: Boolean read FClickToGo write SetClickToGo default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.DisableDefaultUI.txt)
property DisableDefaultUI: Boolean read FDisableDefaultUI write SetDisableDefaultUI default False;
// @include(..\docs\GMMap.TGMCustomMapOptions.DisableDoubleClickZoom.txt)
property DisableDoubleClickZoom: Boolean read FDisableDoubleClickZoom write SetDisableDoubleClickZoom default False;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.EnableCloseButton.txt)
property EnableCloseButton: Boolean read FEnableCloseButton write SetEnableCloseButton default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.FullScreenControl.txt)
property FullScreenControl: Boolean read FFullScreenControl write SetFullScreenControl default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.FullScreenControlOptions.txt)
property FullScreenControlOptions: TGMFullScreenControlOptions read FFullScreenControlOptions write FFullScreenControlOptions;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.ImageDateControl.txt)
property ImageDateControl: Boolean read FImageDateControl write SetImageDateControl default False;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.LinksControl.txt)
property LinksControl: Boolean read FLinksControl write SetLinksControl default False;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.PanControl.txt)
property PanControl: Boolean read FPanControl write SetPanControl default True;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.PanControlOptions.txt)
property PanControlOptions: TGMPanControlOptions read FPanControlOptions write FPanControlOptions;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.Pov.txt)
property Pov: TGMStreetViewPov read FPov write FPov;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.Scrollwheel.txt)
property Scrollwheel: Boolean read FScrollwheel write SetScrollwheel default True;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.Visible.txt)
property Visible: Boolean read FVisible write SetVisible default False;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.ZoomControl.txt)
property ZoomControl: Boolean read FZoomControl write SetZoomControl default True;
// @include(..\docs\GMMap.TGMStreetViewPanoramaOptions.ZoomControlOptions.txt)
property ZoomControlOptions: TGMZoomControlOptions read FZoomControlOptions write FZoomControlOptions;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMCustomMapOptions.txt)
TGMCustomMapOptions = class(TGMPersistentStr, IGMControlChanges)
private
FTilt: Integer;
FScrollwheel: Boolean;
FNoClear: Boolean;
FKeyboardShortcuts: Boolean;
FDraggingCursor: string;
FMinZoom: Integer;
FDisableDoubleClickZoom: Boolean;
FDraggable: Boolean;
FMapTypeId: TGMMapTypeId;
FHeading: Integer;
FDraggableCursor: string;
FDisableDefaultUI: Boolean;
FCenter: TGMLatLng;
FZoom: Integer;
FMaxZoom: Integer;
FMapMaker: Boolean;
FMapTypeControl: Boolean;
FMapTypeControlOptions: TGMMapTypeControlOptions;
FOverviewMapControl: Boolean;
FOverviewMapControlOptions: TGMOverviewMapControlOptions;
FPanControlOptions: TGMPanControlOptions;
FPanControl: Boolean;
FRotateControl: Boolean;
FRotateControlOptions: TGMRotateControlOptions;
FScaleControlOptions: TGMScaleControlOptions;
FScaleControl: Boolean;
FStreetViewControlOptions: TGMStreetViewControlOptions;
FStreetViewControl: Boolean;
FZoomControl: Boolean;
FZoomControlOptions: TGMZoomControlOptions;
FStreetView: TGMStreetViewPanoramaOptions;
FFullScreenControl: Boolean;
FFullScreenControlOptions: TGMFullScreenControlOptions;
procedure SetDisableDefaultUI(const Value: Boolean);
procedure SetDisableDoubleClickZoom(const Value: Boolean);
procedure SetDraggable(const Value: Boolean);
procedure SetDraggableCursor(const Value: string);
procedure SetDraggingCursor(const Value: string);
procedure SetHeading(const Value: Integer);
procedure SetKeyboardShortcuts(const Value: Boolean);
procedure SetMapMaker(const Value: Boolean);
procedure SetMapTypeId(const Value: TGMMapTypeId);
procedure SetMaxZoom(const Value: Integer);
procedure SetMinZoom(const Value: Integer);
procedure SetNoClear(const Value: Boolean);
procedure SetScrollwheel(const Value: Boolean);
procedure SetTilt(const Value: Integer);
procedure SetZoom(const Value: Integer);
procedure SetMapTypeControl(const Value: Boolean);
procedure SetOverviewMapControl(const Value: Boolean);
procedure SetPanControl(const Value: Boolean);
procedure SetRotateControl(const Value: Boolean);
procedure SetScaleControl(const Value: Boolean);
procedure SetStreetViewControl(const Value: Boolean);
procedure SetZoomControl(const Value: Boolean);
procedure SetFullScreenControl(const Value: Boolean);
protected
// @include(..\docs\GMClasses.IGMControlChanges.PropertyChanged.txt)
procedure PropertyChanged(Prop: TPersistent; PropName: string);
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
// @include(..\docs\GMMap.TGMCustomMapOptions.Center.txt)
property Center: TGMLatLng read FCenter write FCenter;
// @include(..\docs\GMMap.TGMCustomMapOptions.DisableDefaultUI.txt)
property DisableDefaultUI: Boolean read FDisableDefaultUI write SetDisableDefaultUI default False;
// @include(..\docs\GMMap.TGMCustomMapOptions.DisableDoubleClickZoom.txt)
property DisableDoubleClickZoom: Boolean read FDisableDoubleClickZoom write SetDisableDoubleClickZoom default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.Draggable.txt)
property Draggable: Boolean read FDraggable write SetDraggable default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.DraggableCursor.txt)
property DraggableCursor: string read FDraggableCursor write SetDraggableCursor;
// @include(..\docs\GMMap.TGMCustomMapOptions.DraggingCursor.txt)
property DraggingCursor: string read FDraggingCursor write SetDraggingCursor;
// @include(..\docs\GMMap.TGMCustomMapOptions.FullScreenControl.txt)
property FullScreenControl: Boolean read FFullScreenControl write SetFullScreenControl default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.FullScreenControlOptions.txt)
property FullScreenControlOptions: TGMFullScreenControlOptions read FFullScreenControlOptions write FFullScreenControlOptions;
// @include(..\docs\GMMap.TGMCustomMapOptions.Heading.txt)
property Heading: Integer read FHeading write SetHeading default 0;
// @include(..\docs\GMMap.TGMCustomMapOptions.KeyboardShortcuts.txt)
property KeyboardShortcuts: Boolean read FKeyboardShortcuts write SetKeyboardShortcuts default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.MapMaker.txt)
property MapMaker: Boolean read FMapMaker write SetMapMaker default False;
// @include(..\docs\GMMap.TGMCustomMapOptions.MapTypeControl.txt)
property MapTypeControl: Boolean read FMapTypeControl write SetMapTypeControl default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.MapTypeControlOptions.txt)
property MapTypeControlOptions: TGMMapTypeControlOptions read FMapTypeControlOptions write FMapTypeControlOptions;
// @include(..\docs\GMMap.TGMCustomMapOptions.MapTypeId.txt)
property MapTypeId: TGMMapTypeId read FMapTypeId write SetMapTypeId default mtROADMAP;
// @include(..\docs\GMMap.TGMCustomMapOptions.MaxZoom.txt)
property MaxZoom: Integer read FMaxZoom write SetMaxZoom default 0;
// @include(..\docs\GMMap.TGMCustomMapOptions.MinZoom.txt)
property MinZoom: Integer read FMinZoom write SetMinZoom default 0;
// @include(..\docs\GMMap.TGMCustomMapOptions.NoClear.txt)
property NoClear: Boolean read FNoClear write SetNoClear default False;
// @include(..\docs\GMMap.TGMCustomMapOptions.OverviewMapControl.txt)
property OverviewMapControl: Boolean read FOverviewMapControl write SetOverviewMapControl default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.OverviewMapControlOptions.txt)
property OverviewMapControlOptions: TGMOverviewMapControlOptions read FOverviewMapControlOptions write FOverviewMapControlOptions;
// @include(..\docs\GMMap.TGMCustomMapOptions.PanControl.txt)
property PanControl: Boolean read FPanControl write SetPanControl default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.PanControlOptions.txt)
property PanControlOptions: TGMPanControlOptions read FPanControlOptions write FPanControlOptions;
// @include(..\docs\GMMap.TGMCustomMapOptions.RotateControl.txt)
property RotateControl: Boolean read FRotateControl write SetRotateControl default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.RotateControlOptions.txt)
property RotateControlOptions: TGMRotateControlOptions read FRotateControlOptions write FRotateControlOptions;
// @include(..\docs\GMMap.TGMCustomMapOptions.ScaleControl.txt)
property ScaleControl: Boolean read FScaleControl write SetScaleControl default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.ScaleControlOptions.txt)
property ScaleControlOptions: TGMScaleControlOptions read FScaleControlOptions write FScaleControlOptions;
// @include(..\docs\GMMap.TGMCustomMapOptions.Scrollwheel.txt)
property Scrollwheel: Boolean read FScrollwheel write SetScrollwheel default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.StreetView.txt)
property StreetView: TGMStreetViewPanoramaOptions read FStreetView write FStreetView;
// @include(..\docs\GMMap.TGMCustomMapOptions.StreetViewControl.txt)
property StreetViewControl: Boolean read FStreetViewControl write SetStreetViewControl default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.StreetViewControlOptions.txt)
property StreetViewControlOptions: TGMStreetViewControlOptions read FStreetViewControlOptions write FStreetViewControlOptions;
// @include(..\docs\GMMap.TGMCustomMapOptions.Tilt.txt)
property Tilt: Integer read FTilt write SetTilt default 0;
// @include(..\docs\GMMap.TGMCustomMapOptions.Zoom.txt)
property Zoom: Integer read FZoom write SetZoom default 8;
// @include(..\docs\GMMap.TGMCustomMapOptions.ZoomControl.txt)
property ZoomControl: Boolean read FZoomControl write SetZoomControl default True;
// @include(..\docs\GMMap.TGMCustomMapOptions.ZoomControlOptions.txt)
property ZoomControlOptions: TGMZoomControlOptions read FZoomControlOptions write FZoomControlOptions;
public
// @include(..\docs\GMMap.TGMCustomMapOptions.Create.txt)
constructor Create(AOwner: TPersistent); override;
// @include(..\docs\GMMap.TGMCustomMapOptions.Destroy.txt)
destructor Destroy; override;
// @include(..\docs\GMMap.TGMCustomMapOptions.GetAPIUrl.txt)
function GetAPIUrl: string; override;
// @include(..\docs\GMMap.TGMCustomMapOptions.Assign.txt)
procedure Assign(Source: TPersistent); override;
end;
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMMap.TGMCustomGMMap.txt)
TGMCustomGMMap = class(TGMComponent, IGMExecJS, IGMControlChanges)
private
FGoogleAPIVer: TGoogleAPIVer;
FActive: Boolean;
FGoogleAPIKey: string;
FIntervalEvents: Integer;
FOnActiveChange: TNotifyEvent;
FOnIntervalEventsChange: TNotifyEvent;
FSignedIn: Boolean;
FAPILang: TGMAPILang;
FPrecision: Integer;
FOnPrecisionChange: TNotifyEvent;
FOnPropertyChanges: TPropertyChanges;
procedure SetGoogleAPIVer(const Value: TGoogleAPIVer);
procedure SetActive(const Value: Boolean); {*1 *}
procedure SetGoogleAPIKey(const Value: string);
procedure SetIntervalEvents(const Value: Integer);
procedure SetSignedIn(const Value: Boolean);
procedure SetAPILang(const Value: TGMAPILang);
procedure SetPrecision(const Value: Integer);
protected
// @include(..\docs\GMMap.TGMCustomGMMap.FWebBrowser.txt)
FWebBrowser: TComponent;
// @include(..\docs\GMClasses.IGMControlChanges.PropertyChanged.txt)
procedure PropertyChanged(Prop: TPersistent; PropName: string);
// @include(..\docs\GMMap.TGMCustomGMMap.GetTempPath.txt)
function GetTempPath: string; virtual; abstract;
// @include(..\docs\GMMap.TGMCustomGMMap.SetIntervalTimer.txt)
procedure SetIntervalTimer(Interval: Integer); virtual; abstract;
// @include(..\docs\GMMap.TGMCustomGMMap.LoadMap.txt)
procedure LoadMap; virtual; abstract;
// @include(..\docs\GMMap.TGMCustomGMMap.LoadBlankPage.txt)
procedure LoadBlankPage; virtual; abstract;
// @include(..\docs\GMMap.TGMCustomGMMap.GetBaseHTMLCode.txt)
function GetBaseHTMLCode: string;
// @include(..\docs\GMMap.TGMCustomGMMap.ExecuteJavaScript.txt)
procedure ExecuteJavaScript(NameFunct, Params: string); virtual; abstract;
// @include(..\docs\GMMap.TGMCustomGMMap.OnTimer.txt)
procedure OnTimer(Sender: TObject); virtual; (*1 *)
{ function GetBounds: TGMLatLngBounds;
function GetCenter: TGMLatLng;
function GetHeading: Real;
function GetMapTypeId: TGMMapTypeId;
function GetTilt: Real;
function GetZoom: Integer;
procedure PanBy(x, y: Integer);
procedure PanTo(LatLng: TGMLatLng);
procedure PanToBounds(LatLngBounds: TGMLatLngBounds);
procedure SetCenter(Latlng: TGMLatLng);
procedure SetHeading(Heading: Real);
procedure SetMapTypeId(MapTypeId: TGMMapTypeId);
procedure SetTilt(Tilt: Real);
procedure SetZoom(Zoom: Integer);
}
// @include(..\docs\GMMap.TGMCustomGMMap.Active.txt)
property Active: Boolean read FActive write SetActive default False;
// @include(..\docs\GMMap.TGMCustomGMMap.GoogleAPIVer.txt)
property GoogleAPIVer: TGoogleAPIVer read FGoogleAPIVer write SetGoogleAPIVer default api323;
// @include(..\docs\GMMap.TGMCustomGMMap.GoogleAPIKey.txt)
property GoogleAPIKey: string read FGoogleAPIKey write SetGoogleAPIKey;
// @include(..\docs\GMMap.TGMCustomGMMap.IntervalEvents.txt)
property IntervalEvents: Integer read FIntervalEvents write SetIntervalEvents default 200;
// @include(..\docs\GMMap.TGMCustomGMMap.SignedIn.txt)
property SignedIn: Boolean read FSignedIn write SetSignedIn default False;
// @include(..\docs\GMMap.TGMCustomGMMap.APILang.txt)
property APILang: TGMAPILang read FAPILang write SetAPILang default lEnglish;
// @include(..\docs\GMMap.TGMCustomGMMap.Precision.txt)
property Precision: Integer read FPrecision write SetPrecision default 0;
// @include(..\docs\GMMap.TGMCustomGMMap.OnActiveChange.txt)
property OnActiveChange: TNotifyEvent read FOnActiveChange write FOnActiveChange;
// @include(..\docs\GMMap.TGMCustomGMMap.OnIntervalEventsChange.txt)
property OnIntervalEventsChange: TNotifyEvent read FOnIntervalEventsChange write FOnIntervalEventsChange;
// @include(..\docs\GMMap.TGMCustomGMMap.OnPrecisionChange.txt)
property OnPrecisionChange: TNotifyEvent read FOnPrecisionChange write FOnPrecisionChange;
// @include(..\docs\GMMap.TGMCustomGMMap.OnPropertyChanges.txt)
property OnPropertyChanges: TPropertyChanges read FOnPropertyChanges write FOnPropertyChanges;
public
// @include(..\docs\GMMap.TGMCustomGMMap.Create.txt)
constructor Create(AOwner: TComponent); override;
// @include(..\docs\GMClasses.TGMComponent.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMMap.TGMCustomGMMap.FitBounds.txt)
procedure FitBounds(Bounds: TGMLatLngBounds);
end;
implementation
uses
{$IFDEF DELPHI2010}
System.IOUtils,
{$ENDIF}
{$IFDEF DELPHIXE2}
System.Types,
{$ELSE}
Windows,
{$ENDIF}
GMConstants;
{ TGMCustomMapOptions }
procedure TGMCustomMapOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMCustomMapOptions then
begin
Center.Assign(TGMCustomMapOptions(Source).Center);
DisableDefaultUI := TGMCustomMapOptions(Source).DisableDefaultUI;
DisableDoubleClickZoom := TGMCustomMapOptions(Source).DisableDoubleClickZoom;
Draggable := TGMCustomMapOptions(Source).Draggable;
DraggableCursor := TGMCustomMapOptions(Source).DraggableCursor;
DraggingCursor := TGMCustomMapOptions(Source).DraggingCursor;
FullScreenControl := TGMCustomMapOptions(Source).FullScreenControl;
FullScreenControlOptions.Assign(TGMCustomMapOptions(Source).FullScreenControlOptions);
Heading := TGMCustomMapOptions(Source).Heading;
KeyboardShortcuts := TGMCustomMapOptions(Source).KeyboardShortcuts;
MapMaker := TGMCustomMapOptions(Source).MapMaker;
MapTypeControl := TGMCustomMapOptions(Source).MapTypeControl;
MapTypeControlOptions.Assign(TGMCustomMapOptions(Source).MapTypeControlOptions);
MapTypeId := TGMCustomMapOptions(Source).MapTypeId;
MaxZoom := TGMCustomMapOptions(Source).MaxZoom;
MinZoom := TGMCustomMapOptions(Source).MinZoom;
NoClear := TGMCustomMapOptions(Source).NoClear;
OverviewMapControl := TGMCustomMapOptions(Source).OverviewMapControl;
OverviewMapControlOptions.Assign(TGMCustomMapOptions(Source).OverviewMapControlOptions);
PanControl := TGMCustomMapOptions(Source).PanControl;
PanControlOptions.Assign(TGMCustomMapOptions(Source).PanControlOptions);
RotateControl := TGMCustomMapOptions(Source).RotateControl;
RotateControlOptions.Assign(TGMCustomMapOptions(Source).RotateControlOptions);
ScaleControl := TGMCustomMapOptions(Source).ScaleControl;
ScaleControlOptions.Assign(TGMCustomMapOptions(Source).ScaleControlOptions);
Scrollwheel := TGMCustomMapOptions(Source).Scrollwheel;
StreetView.Assign(TGMCustomMapOptions(Source).StreetView);
StreetViewControl := TGMCustomMapOptions(Source).StreetViewControl;
StreetViewControlOptions.Assign(TGMCustomMapOptions(Source).StreetViewControlOptions);
Tilt := TGMCustomMapOptions(Source).Tilt;
Zoom := TGMCustomMapOptions(Source).Zoom;
ZoomControl := TGMCustomMapOptions(Source).ZoomControl;
ZoomControlOptions.Assign(TGMCustomMapOptions(Source).ZoomControlOptions);
end;
end;
constructor TGMCustomMapOptions.Create(AOwner: TPersistent);
begin
inherited;
FCenter := TGMLatLng.Create(Self, 0, 0, False);
FDisableDefaultUI := False;
FDisableDoubleClickZoom := True;
FDraggable := True;
FDraggableCursor := '';
FDraggingCursor := '';
FFullScreenControl := True;
FFullScreenControlOptions := TGMFullScreenControlOptions.Create(Self);
FHeading := 0;
FKeyboardShortcuts := True;
FMapMaker := False;
FMapTypeControl := True;
FMapTypeControlOptions := TGMMapTypeControlOptions.Create(Self);
FMapTypeId := mtROADMAP;
FMaxZoom := 0;
FMinZoom := 0;
FNoClear := False;
FOverviewMapControl := True;
FOverviewMapControlOptions := TGMOverviewMapControlOptions.Create(Self);
FPanControl := True;
FPanControlOptions := TGMPanControlOptions.Create(Self);
FRotateControl := True;
FRotateControlOptions := TGMRotateControlOptions.Create(Self);
FScaleControl := True;
FScaleControlOptions := TGMScaleControlOptions.Create(Self);
FScrollwheel := True;
FStreetView := TGMStreetViewPanoramaOptions.Create(Self);
FStreetViewControl := True;
FStreetViewControlOptions := TGMStreetViewControlOptions.Create(Self);
FTilt := 0;
FZoom := 8;
FZoomControl := True;
FZoomControlOptions := TGMZoomControlOptions.Create(Self);
end;
destructor TGMCustomMapOptions.Destroy;
begin
if Assigned(FCenter) then FreeAndNil(FCenter);
if Assigned(FFullScreenControlOptions) then FreeAndNil(FFullScreenControlOptions);
if Assigned(FMapTypeControlOptions) then FreeAndNil(FMapTypeControlOptions);
if Assigned(FOverviewMapControlOptions) then FreeAndNil(FOverviewMapControlOptions);
if Assigned(FPanControlOptions) then FreeAndNil(FPanControlOptions);
if Assigned(FScaleControlOptions) then FreeAndNil(FScaleControlOptions);
if Assigned(FStreetView) then FreeAndNil(FStreetView);
if Assigned(FStreetViewControlOptions) then FreeAndNil(FStreetViewControlOptions);
if Assigned(FZoomControlOptions) then FreeAndNil(FZoomControlOptions);
inherited;
end;
function TGMCustomMapOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#MapOptions';
end;
procedure TGMCustomMapOptions.PropertyChanged(Prop: TPersistent;
PropName: string);
var
Intf: IGMControlChanges;
begin
if (GetOwner <> nil) and Supports(GetOwner, IGMControlChanges, Intf) then
begin
if Assigned(Prop) then
Intf.PropertyChanged(Prop, PropName)
else
Intf.PropertyChanged(Self, PropName);
end
else
if Assigned(OnChange) then OnChange(Self);
end;
function TGMCustomMapOptions.PropToString: string;
const
Str = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s';
begin
Result := inherited PropToString;
if Result <> '' then Result := Result + ',';
Result := Result +
Format(Str, [
FCenter.PropToString,
LowerCase(TGMTransform.GMBoolToStr(FDisableDefaultUI, True)),
LowerCase(TGMTransform.GMBoolToStr(FDisableDoubleClickZoom, True)),
LowerCase(TGMTransform.GMBoolToStr(FDraggable, True)),
QuotedStr(FDraggableCursor),
QuotedStr(FDraggingCursor),
LowerCase(TGMTransform.GMBoolToStr(FFullScreenControl, True)),
FFullScreenControlOptions.PropToString,
IntToStr(FHeading),
LowerCase(TGMTransform.GMBoolToStr(FKeyboardShortcuts, True)),
LowerCase(TGMTransform.GMBoolToStr(FMapMaker, True)),
LowerCase(TGMTransform.GMBoolToStr(FMapTypeControl, True)),
FMapTypeControlOptions.PropToString,
QuotedStr(TGMTransform.MapTypeIdToStr(FMapTypeId)),
IntToStr(FMaxZoom),
IntToStr(FMinZoom),
LowerCase(TGMTransform.GMBoolToStr(FNoClear, True)),
LowerCase(TGMTransform.GMBoolToStr(FOverviewMapControl, True)),
FOverviewMapControlOptions.PropToString,
LowerCase(TGMTransform.GMBoolToStr(FPanControl, True)),
FPanControlOptions.PropToString,
LowerCase(TGMTransform.GMBoolToStr(FRotateControl, True)),
FRotateControlOptions.PropToString,
LowerCase(TGMTransform.GMBoolToStr(FScaleControl, True)),
FScaleControlOptions.PropToString,
LowerCase(TGMTransform.GMBoolToStr(FScrollwheel, True)),
FStreetView.PropToString,
LowerCase(TGMTransform.GMBoolToStr(FStreetViewControl, True)),
FStreetViewControlOptions.PropToString,
IntToStr(FTilt),
IntToStr(FZoom),
LowerCase(TGMTransform.GMBoolToStr(FZoomControl, True)),
FZoomControlOptions.PropToString
]);
end;
procedure TGMCustomMapOptions.SetDisableDefaultUI(const Value: Boolean);
begin
if FDisableDefaultUI = Value then Exit;
FDisableDefaultUI := Value;
ControlChanges('DisableDefaultUI');
end;
procedure TGMCustomMapOptions.SetDisableDoubleClickZoom(const Value: Boolean);
begin
if FDisableDoubleClickZoom = Value then Exit;
FDisableDoubleClickZoom := Value;
ControlChanges('DisableDoubleClickZoom');
end;
procedure TGMCustomMapOptions.SetDraggable(const Value: Boolean);
begin
if FDraggable = Value then Exit;
FDraggable := Value;
ControlChanges('Draggable');
end;
procedure TGMCustomMapOptions.SetDraggableCursor(const Value: string);
begin
if FDraggableCursor = Value then Exit;
FDraggableCursor := Value;
ControlChanges('DraggableCursor');
end;
procedure TGMCustomMapOptions.SetDraggingCursor(const Value: string);
begin
if FDraggingCursor = Value then Exit;
FDraggingCursor := Value;
ControlChanges('DraggingCursor');
end;
procedure TGMCustomMapOptions.SetFullScreenControl(const Value: Boolean);
begin
if FFullScreenControl = Value then Exit;
FFullScreenControl := Value;
ControlChanges('FullScreenControl');
end;
procedure TGMCustomMapOptions.SetHeading(const Value: Integer);
begin
if FHeading = Value then Exit;
FHeading := Value;
ControlChanges('Heading');
end;
procedure TGMCustomMapOptions.SetKeyboardShortcuts(const Value: Boolean);
begin
if FKeyboardShortcuts = Value then Exit;
FKeyboardShortcuts := Value;
ControlChanges('KeyboardShortcuts');
end;
procedure TGMCustomMapOptions.SetMapMaker(const Value: Boolean);
begin
if FMapMaker = Value then Exit;
FMapMaker := Value;
ControlChanges('MapMaker');
end;
procedure TGMCustomMapOptions.SetMapTypeControl(const Value: Boolean);
begin
if FMapTypeControl = Value then Exit;
FMapTypeControl := Value;
ControlChanges('MapTypeControl');
end;
procedure TGMCustomMapOptions.SetMapTypeId(const Value: TGMMapTypeId);
begin
if FMapTypeId = Value then Exit;
FMapTypeId := Value;
ControlChanges('MapTypeId');
end;
procedure TGMCustomMapOptions.SetMaxZoom(const Value: Integer);
begin
if FMaxZoom = Value then Exit;
FMaxZoom := Value;
ControlChanges('MaxZoom');
end;
procedure TGMCustomMapOptions.SetMinZoom(const Value: Integer);
begin
if FMinZoom = Value then Exit;
FMinZoom := Value;
ControlChanges('MinZoom');
end;
procedure TGMCustomMapOptions.SetNoClear(const Value: Boolean);
begin
if FNoClear = Value then Exit;
FNoClear := Value;
ControlChanges('NoClear');
end;
procedure TGMCustomMapOptions.SetOverviewMapControl(const Value: Boolean);
begin
if FOverviewMapControl = Value then Exit;
FOverviewMapControl := Value;
ControlChanges('OverviewMapControl');
end;
procedure TGMCustomMapOptions.SetPanControl(const Value: Boolean);
begin
if FPanControl = Value then Exit;
FPanControl := Value;
ControlChanges('PanControl');
end;
procedure TGMCustomMapOptions.SetRotateControl(const Value: Boolean);
begin
if FRotateControl = Value then Exit;
FRotateControl := Value;
ControlChanges('RotateControl');
end;
procedure TGMCustomMapOptions.SetScaleControl(const Value: Boolean);
begin
if FScaleControl = Value then Exit;
FScaleControl := Value;
ControlChanges('ScaleControl');
end;
procedure TGMCustomMapOptions.SetScrollwheel(const Value: Boolean);
begin
if FScrollwheel = Value then Exit;
FScrollwheel := Value;
ControlChanges('Scrollwheel');
end;
procedure TGMCustomMapOptions.SetStreetViewControl(const Value: Boolean);
begin
if FStreetViewControl = Value then Exit;
FStreetViewControl := Value;
ControlChanges('StreetViewControl');
end;
procedure TGMCustomMapOptions.SetTilt(const Value: Integer);
begin
if FTilt = Value then Exit;
FTilt := Value;
ControlChanges('Tilt');
end;
procedure TGMCustomMapOptions.SetZoom(const Value: Integer);
begin
if FZoom = Value then Exit;
FZoom := Value;
ControlChanges('Zoom');
end;
procedure TGMCustomMapOptions.SetZoomControl(const Value: Boolean);
begin
if FZoomControl = Value then Exit;
FZoomControl := Value;
ControlChanges('ZoomControl');
end;
{ TGMMapTypeControlOptions }
procedure TGMMapTypeControlOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMMapTypeControlOptions then
begin
MapTypeIds := TGMMapTypeControlOptions(Source).MapTypeIds;
Position := TGMMapTypeControlOptions(Source).Position;
Style := TGMMapTypeControlOptions(Source).Style;
end;
end;
constructor TGMMapTypeControlOptions.Create(AOwner: TPersistent);
begin
inherited;
FPosition := cpTOP_RIGHT;
FStyle := mtcDEFAULT;
FMapTypeIds := [mtHYBRID, mtROADMAP, mtSATELLITE, mtTERRAIN, mtOSM];
end;
function TGMMapTypeControlOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#MapTypeControlOptions';
end;
function TGMMapTypeControlOptions.PropToString: string;
const
Str = '%s,%s,%s';
begin
Result := Format(Str, [
QuotedStr(TGMTransform.MapTypeIdsToStr(MapTypeIds, ';')),
QuotedStr(TGMTransform.PositionToStr(Position)),
QuotedStr(TGMTransform.MapTypeControlStyleToStr(Style))
]);
end;
procedure TGMMapTypeControlOptions.SetMapTypeIds(const Value: TGMMapTypeIds);
begin
if FMapTypeIds = Value then Exit;
FMapTypeIds := Value;
ControlChanges('MapTypeIds');
end;
procedure TGMMapTypeControlOptions.SetPosition(const Value: TGMControlPosition);
begin
if FPosition = Value then Exit;
FPosition := Value;
ControlChanges('Position');
end;
procedure TGMMapTypeControlOptions.SetStyle(const Value: TGMMapTypeControlStyle);
begin
if FStyle = Value then Exit;
FStyle := Value;
ControlChanges('Style');
end;
{ TGMOverviewMapControlOptions }
procedure TGMOverviewMapControlOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMOverviewMapControlOptions then
begin
Opened := TGMOverviewMapControlOptions(Source).Opened;
end;
end;
constructor TGMOverviewMapControlOptions.Create(AOwner: TPersistent);
begin
inherited;
FOpened := False;
end;
function TGMOverviewMapControlOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#OverviewMapControlOptions';
end;
function TGMOverviewMapControlOptions.PropToString: string;
const
Str = '%s';
begin
Result := Format(Str, [
LowerCase(TGMTransform.GMBoolToStr(Opened, True))
]);
end;
procedure TGMOverviewMapControlOptions.SetOpened(const Value: Boolean);
begin
if FOpened = Value then Exit;
FOpened := Value;
ControlChanges('Opened');
end;
{ TGMPanControlOptions }
procedure TGMPanControlOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMPanControlOptions then
begin
Position := TGMPanControlOptions(Source).Position;
end;
end;
constructor TGMPanControlOptions.Create(AOwner: TPersistent);
begin
inherited;
FPosition := cpTOP_LEFT;
end;
function TGMPanControlOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#PanControlOptions';
end;
function TGMPanControlOptions.PropToString: string;
const
Str = '%s';
begin
Result := Format(Str, [
QuotedStr(TGMTransform.PositionToStr(Position))
]);
end;
procedure TGMPanControlOptions.SetPosition(const Value: TGMControlPosition);
begin
if FPosition = Value then Exit;
FPosition := Value;
ControlChanges('Position');
end;
{ TGMRotateControlOptions }
procedure TGMRotateControlOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMRotateControlOptions then
begin
Position := TGMRotateControlOptions(Source).Position;
end;
end;
constructor TGMRotateControlOptions.Create(AOwner: TPersistent);
begin
inherited;
FPosition := cpTOP_LEFT;
end;
function TGMRotateControlOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#RotateControlOptions';
end;
function TGMRotateControlOptions.PropToString: string;
const
Str = '%s';
begin
Result := Format(Str, [
QuotedStr(TGMTransform.PositionToStr(Position))
]);
end;
procedure TGMRotateControlOptions.SetPosition(const Value: TGMControlPosition);
begin
if FPosition = Value then Exit;
FPosition := Value;
ControlChanges('Position');
end;
{ TGMScaleControlOptions }
procedure TGMScaleControlOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMScaleControlOptions then
begin
Style := TGMScaleControlOptions(Source).Style;
end;
end;
constructor TGMScaleControlOptions.Create(AOwner: TPersistent);
begin
inherited;
FStyle := scDEFAULT;
end;
function TGMScaleControlOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#ScaleControlOptions';
end;
function TGMScaleControlOptions.PropToString: string;
const
Str = '%s';
begin
Result := Format(Str, [
QuotedStr(TGMTransform.ScaleControlStyleToStr(Style))
]);
end;
procedure TGMScaleControlOptions.SetStyle(const Value: TGMScaleControlStyle);
begin
if FStyle = Value then Exit;
FStyle := Value;
ControlChanges('Style');
end;
{ TGMStreetViewControlOptions }
procedure TGMStreetViewControlOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMStreetViewControlOptions then
begin
Position := TGMStreetViewControlOptions(Source).Position;
end;
end;
constructor TGMStreetViewControlOptions.Create(AOwner: TPersistent);
begin
inherited;
FPosition := cpTOP_LEFT;
end;
function TGMStreetViewControlOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#StreetViewControlOptions';
end;
function TGMStreetViewControlOptions.PropToString: string;
const
Str = '%s';
begin
Result := Format(Str, [
QuotedStr(TGMTransform.PositionToStr(FPosition))
]);
end;
procedure TGMStreetViewControlOptions.SetPosition(
const Value: TGMControlPosition);
begin
if FPosition = Value then Exit;
FPosition := Value;
ControlChanges('Position');
end;
{ TGMCustomMapTypeStyle }
procedure TGMCustomMapTypeStyle.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMCustomMapTypeStyle then
begin
ElementType := TGMCustomMapTypeStyle(Source).ElementType;
FeatureType := TGMCustomMapTypeStyle(Source).FeatureType;
end;
end;
constructor TGMCustomMapTypeStyle.Create(Collection: TCollection);
begin
inherited;
FElementType := setALL;
FFeatureType := sftALL;
end;
function TGMCustomMapTypeStyle.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#MapTypeStyle';
end;
function TGMCustomMapTypeStyle.PropToString: string;
const
Str = '%s,%s';
begin
Result := inherited PropToString;
if Result <> '' then Result := Result + ',';
Result := Result +
Format(Str, [
TGMTransform.MapTypeStyleElementTypeToStr(FElementType),
TGMTransform.MapTypeStyleFeatureTypeToStr(FeatureType)
]);
end;
procedure TGMCustomMapTypeStyle.SetElementType(const Value: TGMMapTypeStyleElementType);
begin
if FElementType = Value then Exit;
FElementType := Value;
ControlChanges('ElementType');
end;
procedure TGMCustomMapTypeStyle.SetFeatureType(const Value: TGMMapTypeStyleFeatureType);
begin
if FFeatureType = Value then Exit;
FFeatureType := Value;
ControlChanges('FeatureType');
end;
{ TGMCustomMapTypeStyler }
procedure TGMCustomMapTypeStyler.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMCustomMapTypeStyler then
begin
Gamma := TGMCustomMapTypeStyler(Source).Gamma;
InvertLightness := TGMCustomMapTypeStyler(Source).InvertLightness;
Lightness := TGMCustomMapTypeStyler(Source).Lightness;
Saturation := TGMCustomMapTypeStyler(Source).Saturation;
Visibility := TGMCustomMapTypeStyler(Source).Visibility;
Weight := TGMCustomMapTypeStyler(Source).Weight;
end;
end;
constructor TGMCustomMapTypeStyler.Create(Collection: TCollection);
begin
inherited;
FGamma := 1;
FInvertLightness := True;
FLightness := 0;
FSaturation := 0;
FVisibility := vOn;
FWeight := 0;
end;
function TGMCustomMapTypeStyler.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#MapTypeStyler';
end;
function TGMCustomMapTypeStyler.PropToString: string;
const
Str = '%s,%s,%s,%s,%s,%s';
begin
Result := inherited PropToString;
if Result <> '' then Result := Result + ',';
Result := Result +
Format(Str, [
StringReplace(FloatToStr(FGamma), ',', '.', [rfReplaceAll]),
LowerCase(TGMTransform.GMBoolToStr(FInvertLightness, True)),
IntToStr(FLightness),
IntToStr(FSaturation),
TGMTransform.VisibilityToStr(FVisibility),
IntToStr(FWeight)
]);
end;
procedure TGMCustomMapTypeStyler.SetGamma(const Value: Real);
begin
if FGamma = Value then Exit;
FGamma := Value;
if FGamma < 0.01 then FGamma := 0.01;
if FGamma > 10 then FGamma := 10;
ControlChanges('Gamma');
end;
procedure TGMCustomMapTypeStyler.SetInvertLightness(const Value: Boolean);
begin
if FInvertLightness = Value then Exit;
FInvertLightness := Value;
ControlChanges('InvertLightness');
end;
procedure TGMCustomMapTypeStyler.SetLightness(const Value: Integer);
begin
if FLightness = Value then Exit;
FLightness := Value;
if FLightness < -100 then FGamma := -100;
if FLightness > 100 then FGamma := 100;
ControlChanges('Lightness');
end;
procedure TGMCustomMapTypeStyler.SetSaturation(const Value: Integer);
begin
if FSaturation = Value then Exit;
FSaturation := Value;
if FSaturation < -100 then FGamma := -100;
if FSaturation > 100 then FGamma := 100;
ControlChanges('Saturation');
end;
procedure TGMCustomMapTypeStyler.SetVisibility(const Value: TGMVisibility);
begin
if FVisibility = Value then Exit;
FVisibility := Value;
ControlChanges('Visibility');
end;
procedure TGMCustomMapTypeStyler.SetWeight(const Value: Integer);
begin
if FWeight = Value then Exit;
FWeight := Value;
if FWeight < 0 then FWeight := 0;
ControlChanges('Weight');
end;
{ TGMCustomGMMap }
procedure TGMCustomGMMap.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMCustomGMMap then
begin
Active := TGMCustomGMMap(Source).Active;
GoogleAPIVer := TGMCustomGMMap(Source).GoogleAPIVer;
GoogleAPIKey := TGMCustomGMMap(Source).GoogleAPIKey;
IntervalEvents := TGMCustomGMMap(Source).IntervalEvents;
SignedIn := TGMCustomGMMap(Source).SignedIn;
APILang := TGMCustomGMMap(Source).APILang;
end;
end;
constructor TGMCustomGMMap.Create(AOwner: TComponent);
begin
inherited;
FActive := False;
FGoogleAPIKey := '';
FGoogleAPIVer := api323;
FIntervalEvents := 200;
FSignedIn := False;
FAPILang := lEnglish;
end;
procedure TGMCustomGMMap.FitBounds(Bounds: TGMLatLngBounds);
begin
ExecuteJavaScript('FitBounds', Bounds.PropToString);
end;
function TGMCustomGMMap.GetBaseHTMLCode: string;
var
List: TStringList;
Stream: TResourceStream;
StrTmp: string;
begin
if not Assigned(FWebBrowser) then
raise EGMUnassignedObject.Create(['WebBrowser'], Language); // Object %s unassigned.
Result := '';
List := TStringList.Create;
try
try
Stream := TResourceStream.Create(HInstance, ct_RES_MAPA_CODE, RT_RCDATA);
List.LoadFromStream(Stream);
// replaces API_KEY variable
List.Text := StringReplace(List.Text, ct_API_KEY, FGoogleAPIKey, []);
// replaces API_VER variable
StrTmp := TGMTransform.GoogleAPIVerToStr(FGoogleAPIVer);
List.Text := StringReplace(List.Text, ct_API_VER, StrTmp, []);
// replaces API_SIGNED variable
StrTmp := LowerCase(TGMTransform.GMBoolToStr(FSignedIn, True));
List.Text := StringReplace(List.Text, ct_API_SIGNED, StrTmp, []);
// replaces API_LAN variable
StrTmp := LowerCase(TGMTransform.APILangToStr(FAPILang));
List.Text := StringReplace(List.Text, ct_API_LAN, StrTmp, []);
{$IFDEF DELPHI2010}
StrTmp := IncludeTrailingPathDelimiter(TPath.GetTempPath) + ct_FILE_NAME;
{$ELSE}
StrTmp := IncludeTrailingPathDelimiter(GetTempPath) + ct_FILE_NAME;
{$ENDIF}
List.SaveToFile(StrTmp);
Result := StrTmp;
finally
if Assigned(Stream) then FreeAndNil(Stream);
if Assigned(List) then FreeAndNil(List);
end;
except
raise EGMCanLoadResource.Create(Language); // Can't load map resource.
end;
end;
procedure TGMCustomGMMap.OnTimer(Sender: TObject);
begin
end;
procedure TGMCustomGMMap.PropertyChanged(Prop: TPersistent; PropName: string);
const
Str1 = '%s';
Str2 = '%s,%s';
begin
if not FActive then Exit;
if (Prop is TGMCustomMapOptions) and SameText(PropName, 'Zoom') then
ExecuteJavaScript('MapChangeProperty', Format(Str2, [
QuotedStr(PropName),
IntToStr(TGMCustomMapOptions(Prop).Zoom)
]));
if (Prop is TGMLatLng) then
ExecuteJavaScript('MapChangeCenter', Format(Str1, [
TGMLatLng(Prop).PropToString
]));
if Assigned(FOnPropertyChanges) then FOnPropertyChanges(Prop, PropName);
end;
procedure TGMCustomGMMap.SetActive(const Value: Boolean);
begin
if FActive = Value then Exit;
FActive := Value;
if csDesigning in ComponentState then Exit;
if not Assigned(FWebBrowser) then Exit;
if FActive then
LoadMap
else
LoadBlankPage;
//SetEnableTimer(FActive); (*1 *)
if Assigned(FOnActiveChange) then FOnActiveChange(Self);
end;
procedure TGMCustomGMMap.SetAPILang(const Value: TGMAPILang);
begin
if FAPILang = Value then Exit;
if FActive and not (csDesigning in ComponentState) and not (csLoading in ComponentState) then
raise EGMMapIsActive.Create(Language); // The map is active. To change this property you must to deactivate it first.
FAPILang := Value;
end;
procedure TGMCustomGMMap.SetGoogleAPIKey(const Value: string);
begin
if FGoogleAPIKey = Value then Exit;
if FActive and not (csDesigning in ComponentState) and not (csLoading in ComponentState) then
raise EGMMapIsActive.Create(Language); // The map is active. To change this property you must to deactivate it first.
FGoogleAPIKey := Value;
end;
procedure TGMCustomGMMap.SetGoogleAPIVer(const Value: TGoogleAPIVer);
begin
if FGoogleAPIVer = Value then Exit;
if FActive and not (csDesigning in ComponentState) and not (csLoading in ComponentState) then
raise EGMMapIsActive.Create(Language); // The map is active. To change this property you must to deactivate it first.
FGoogleAPIVer := Value;
end;
procedure TGMCustomGMMap.SetIntervalEvents(const Value: Integer);
begin
if FIntervalEvents = Value then Exit;
FIntervalEvents := Value;
SetIntervalTimer(FIntervalEvents);
if csDesigning in ComponentState then Exit;
if Assigned(FOnIntervalEventsChange) then FOnIntervalEventsChange(Self);
end;
procedure TGMCustomGMMap.SetPrecision(const Value: Integer);
begin
if FPrecision = Value then Exit;
FPrecision := Value;
if FPrecision < 0 then FPrecision := 0;
if FPrecision > 17 then FPrecision := 17;
if Assigned(FOnPrecisionChange) then FOnPrecisionChange(Self);
end;
procedure TGMCustomGMMap.SetSignedIn(const Value: Boolean);
begin
if FSignedIn = Value then Exit;
if FActive and not (csDesigning in ComponentState) and not (csLoading in ComponentState) then
raise EGMMapIsActive.Create(Language); // The map is active. To change this property you must to deactivate it first.
FSignedIn := Value;
end;
{ TGMZoomControlOptions }
procedure TGMZoomControlOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMZoomControlOptions then
begin
Position := TGMZoomControlOptions(Source).Position;
Style := TGMZoomControlOptions(Source).Style;
end;
end;
constructor TGMZoomControlOptions.Create(AOwner: TPersistent);
begin
inherited;
FPosition := cpTOP_LEFT;
FStyle := zcDEFAULT;
end;
function TGMZoomControlOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#ZoomControlOptions';
end;
function TGMZoomControlOptions.PropToString: string;
const
Str = '%s,%s';
begin
Result := Format(Str, [
QuotedStr(TGMTransform.PositionToStr(Position)),
QuotedStr(TGMTransform.ZoomControlStyleToStr(Style))
]);
end;
procedure TGMZoomControlOptions.SetPosition(const Value: TGMControlPosition);
begin
if FPosition = Value then Exit;
FPosition := Value;
ControlChanges('Position');
end;
procedure TGMZoomControlOptions.SetStyle(const Value: TGMZoomControlStyle);
begin
if FStyle = Value then Exit;
FStyle := Value;
ControlChanges('Style');
end;
{ TGMStreetViewPanoramaOptions }
procedure TGMStreetViewPanoramaOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMStreetViewPanoramaOptions then
begin
AddressControl := TGMStreetViewPanoramaOptions(Source).AddressControl;
AddressControlOptions.Assign(TGMStreetViewPanoramaOptions(Source).AddressControlOptions);
ClickToGo := TGMStreetViewPanoramaOptions(Source).ClickToGo;
DisableDefaultUI := TGMStreetViewPanoramaOptions(Source).DisableDefaultUI;
DisableDoubleClickZoom := TGMStreetViewPanoramaOptions(Source).DisableDoubleClickZoom;
EnableCloseButton := TGMStreetViewPanoramaOptions(Source).EnableCloseButton;
FullScreenControl := TGMStreetViewPanoramaOptions(Source).FullScreenControl;
FullScreenControlOptions.Assign(TGMStreetViewPanoramaOptions(Source).FullScreenControlOptions);
ImageDateControl := TGMStreetViewPanoramaOptions(Source).ImageDateControl;
LinksControl := TGMStreetViewPanoramaOptions(Source).LinksControl;
PanControl := TGMStreetViewPanoramaOptions(Source).PanControl;
PanControlOptions.Assign(TGMStreetViewPanoramaOptions(Source).PanControlOptions);
Pov.Assign(TGMStreetViewPanoramaOptions(Source).Pov);
Scrollwheel := TGMStreetViewPanoramaOptions(Source).Scrollwheel;
Visible := TGMStreetViewPanoramaOptions(Source).Visible;
ZoomControl := TGMStreetViewPanoramaOptions(Source).ZoomControl;
ZoomControlOptions.Assign(TGMStreetViewPanoramaOptions(Source).ZoomControlOptions);
end;
end;
constructor TGMStreetViewPanoramaOptions.Create(AOwner: TPersistent);
begin
inherited;
FAddressControl := True;
FAddressControlOptions := TGMStreetViewAddressControlOptions.Create(Self);
FClickToGo := True;
FDisableDefaultUI := False;
FDisableDoubleClickZoom := False;
FEnableCloseButton := True;
FFullScreenControl := True;
FFullScreenControlOptions := TGMFullScreenControlOptions.Create(Self);
FImageDateControl := False;
FLinksControl := False;
FPanControl := True;
FPanControlOptions := TGMPanControlOptions.Create(Self);
FPov := TGMStreetViewPov.Create(Self);
FScrollwheel := True;
FVisible := False;
FZoomControl := True;
FZoomControlOptions := TGMZoomControlOptions.Create(Self);
end;
destructor TGMStreetViewPanoramaOptions.Destroy;
begin
if Assigned(FAddressControlOptions) then FreeAndNil(FAddressControlOptions);
if Assigned(FFullScreenControlOptions) then FreeAndNil(FFullScreenControlOptions);
if Assigned(FPanControlOptions) then FreeAndNil(FPanControlOptions);
if Assigned(FPov) then FreeAndNil(FPov);
if Assigned(FZoomControlOptions) then FreeAndNil(FZoomControlOptions);
inherited;
end;
function TGMStreetViewPanoramaOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#StreetViewPanoramaOptions';
end;
function TGMStreetViewPanoramaOptions.PropToString: string;
const
Str = '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s';
begin
Result := inherited PropToString;
if Result <> '' then Result := Result + ',';
Result := Result +
Format(Str, [
LowerCase(TGMTransform.GMBoolToStr(FAddressControl, True)),
FAddressControlOptions.PropToString,
LowerCase(TGMTransform.GMBoolToStr(FClickToGo, True)),
LowerCase(TGMTransform.GMBoolToStr(FDisableDefaultUI, True)),
LowerCase(TGMTransform.GMBoolToStr(FDisableDoubleClickZoom, True)),
LowerCase(TGMTransform.GMBoolToStr(FEnableCloseButton, True)),
LowerCase(TGMTransform.GMBoolToStr(FFullScreenControl, True)),
FFullScreenControlOptions.PropToString,
LowerCase(TGMTransform.GMBoolToStr(FImageDateControl, True)),
LowerCase(TGMTransform.GMBoolToStr(FLinksControl, True)),
LowerCase(TGMTransform.GMBoolToStr(FPanControl, True)),
FPanControlOptions.PropToString,
FPov.PropToString,
LowerCase(TGMTransform.GMBoolToStr(FScrollwheel, True)),
LowerCase(TGMTransform.GMBoolToStr(FVisible, True)),
LowerCase(TGMTransform.GMBoolToStr(FZoomControl, True)),
FZoomControlOptions.PropToString
]);
end;
procedure TGMStreetViewPanoramaOptions.SetAddressControl(const Value: Boolean);
begin
if FAddressControl = Value then Exit;
FAddressControl := Value;
ControlChanges('AddressControl');
end;
procedure TGMStreetViewPanoramaOptions.SetClickToGo(const Value: Boolean);
begin
if FClickToGo = Value then Exit;
FClickToGo := Value;
ControlChanges('ClickToGo');
end;
procedure TGMStreetViewPanoramaOptions.SetDisableDefaultUI(
const Value: Boolean);
begin
if FDisableDefaultUI = Value then Exit;
FDisableDefaultUI := Value;
ControlChanges('DisableDefaultUI');
end;
procedure TGMStreetViewPanoramaOptions.SetDisableDoubleClickZoom(
const Value: Boolean);
begin
if FDisableDoubleClickZoom = Value then Exit;
FDisableDoubleClickZoom := Value;
ControlChanges('DisableDoubleClickZoom');
end;
procedure TGMStreetViewPanoramaOptions.SetEnableCloseButton(
const Value: Boolean);
begin
if FEnableCloseButton = Value then Exit;
FEnableCloseButton := Value;
ControlChanges('EnableCloseButton');
end;
procedure TGMStreetViewPanoramaOptions.SetFullScreenControl(
const Value: Boolean);
begin
if FFullScreenControl = Value then Exit;
FFullScreenControl := Value;
ControlChanges('FullScreenControl');
end;
procedure TGMStreetViewPanoramaOptions.SetImageDateControl(
const Value: Boolean);
begin
if FImageDateControl = Value then Exit;
FImageDateControl := Value;
ControlChanges('ImageDateControl');
end;
procedure TGMStreetViewPanoramaOptions.SetLinksControl(const Value: Boolean);
begin
if FLinksControl = Value then Exit;
FLinksControl := Value;
ControlChanges('LinksControl');
end;
procedure TGMStreetViewPanoramaOptions.SetPanControl(const Value: Boolean);
begin
if FPanControl = Value then Exit;
FPanControl := Value;
ControlChanges('PanControl');
end;
procedure TGMStreetViewPanoramaOptions.SetScrollwheel(const Value: Boolean);
begin
if FScrollwheel = Value then Exit;
FScrollwheel := Value;
ControlChanges('Scrollwheel');
end;
procedure TGMStreetViewPanoramaOptions.SetVisible(const Value: Boolean);
begin
if FVisible = Value then Exit;
FVisible := Value;
ControlChanges('Visible');
end;
procedure TGMStreetViewPanoramaOptions.SetZoomControl(const Value: Boolean);
begin
if FZoomControl = Value then Exit;
FZoomControl := Value;
ControlChanges('ZoomControl');
end;
{ TGMStreetViewAddressControlOptions }
procedure TGMStreetViewAddressControlOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMStreetViewAddressControlOptions then
begin
Position := TGMStreetViewAddressControlOptions(Source).Position;
end;
end;
constructor TGMStreetViewAddressControlOptions.Create(AOwner: TPersistent);
begin
inherited;
FPosition := cpTOP_LEFT;
end;
function TGMStreetViewAddressControlOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#StreetViewAddressControlOptions';
end;
function TGMStreetViewAddressControlOptions.PropToString: string;
const
Str = '%s';
begin
Result := Format(Str, [
QuotedStr(TGMTransform.PositionToStr(FPosition))
]);
end;
procedure TGMStreetViewAddressControlOptions.SetPosition(
const Value: TGMControlPosition);
begin
if FPosition = Value then Exit;
FPosition := Value;
ControlChanges('Position');
end;
{ TGMStreetViewPov }
procedure TGMStreetViewPov.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMStreetViewPov then
begin
Heading := TGMStreetViewPov(Source).Heading;
Pitch := TGMStreetViewPov(Source).Pitch;
end;
end;
constructor TGMStreetViewPov.Create(AOwner: TPersistent);
begin
inherited;
FHeading := 0;
FPitch := 0;
end;
function TGMStreetViewPov.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#StreetViewPov';
end;
function TGMStreetViewPov.PropToString: string;
const
Str = '%s,%s';
begin
Result := Format(Str, [
IntToStr(FHeading),
IntToStr(FPitch)
]);
end;
procedure TGMStreetViewPov.SetHeading(const Value: Integer);
begin
if FHeading = Value then Exit;
FHeading := Value;
if FHeading < 0 then FHeading := 0;
if FHeading > 270 then FHeading := 270;
ControlChanges('Heading');
end;
procedure TGMStreetViewPov.SetPitch(const Value: Integer);
begin
if FPitch = Value then Exit;
FPitch := Value;
if FPitch < -90 then FPitch := -90;
if FPitch > 90 then FPitch := 90;
ControlChanges('Pitch');
end;
{ TGMFullScreenControlOptions }
procedure TGMFullScreenControlOptions.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMFullScreenControlOptions then
begin
Position := TGMFullScreenControlOptions(Source).Position;
end;
end;
constructor TGMFullScreenControlOptions.Create(AOwner: TPersistent);
begin
inherited;
FPosition := cpRIGHT_TOP;
end;
function TGMFullScreenControlOptions.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#FullscreenControlOptions';
end;
function TGMFullScreenControlOptions.PropToString: string;
const
Str = '%s';
begin
Result := Format(Str, [
QuotedStr(TGMTransform.PositionToStr(FPosition))
]);
end;
procedure TGMFullScreenControlOptions.SetPosition(
const Value: TGMControlPosition);
begin
if FPosition = Value then Exit;
FPosition := Value;
ControlChanges('Position');
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ Internet Application Runtime }
{ }
{ Copyright (C) 2000-2002 Borland Software Corporation }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit ApacheApp;
interface
uses SysUtils, Classes, HTTPD, ApacheHTTP, HTTPApp, WebBroker;
type
{ TApacheApplication }
TApacheFactory = class;
TApacheRequestEvent = function (Req: Prequest_rec): integer;
TApacheInitEvent = procedure (Server: PServer_rec; Pool: Ppool);
TApacheCreateDirConfigEvent = function (Pool: Ppool; szDir: pchar): pointer;
TApacheCreateSvrConfigEvent = function (Pool: Ppool; Server: Pserver_rec): pointer;
TApacheMergeConfigEvent = function (Pool: Ppool; BaseConf, NewConf: pointer): pointer;
TApacheApplication = class(TWebApplication)
private
FFactory: TApacheFactory;
procedure SetFactory(Value: TApacheFactory);
function GetFactory: TApacheFactory;
procedure ApacheHandleException(Sender: TObject);
protected
function NewRequest(var r: request_rec): TApacheRequest;
function NewResponse(ApacheRequest: TApacheRequest): TApacheResponse;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Initialize; override;
function ProcessRequest(var r: request_rec): ap_int;
end;
TApacheFactory = class(TObject)
private
FApplication: TApacheApplication;
protected
function NewRequest(var r: request_rec): TApacheRequest; virtual;
function NewResponse(ApacheRequest: TApacheRequest): TApacheResponse; virtual;
public
constructor Create;
end;
function apache_handlers(r: Prequest_rec): integer; cdecl; export;
procedure set_module(defModule: Pmodule);
var
// Default content-typehandler is "<modulename>-content"
ContentType: array [0..255] of char;
default_handler: array [0..1] of handler_rec
= ((content_type: ContentType; handler: apache_handlers),
(content_type: nil; handler: nil));
request_handlers: phandler_rec = @default_handler;
apache_module: module;
{$EXTERNALSYM apache_module}
ApacheOnInit: TApacheInitEvent = nil;
ApacheOnChildInit: TApacheInitEvent = nil;
ApacheOnChildExit: TApacheInitEvent = nil;
ApacheOnCreateDirConfig: TApacheCreateDirConfigEvent = nil;
ApacheOnMergeDirConfig: TApacheMergeConfigEvent = nil;
ApacheOnCreateServerConfig: TApacheCreateSvrConfigEvent = nil;
ApacheOnMergeServerConfig: TApacheMergeConfigEvent = nil;
ApacheOnLogger: TApacheRequestEvent = nil;
ApacheOnFixUps: TApacheRequestEvent = nil;
ApacheOnTypeChecker: TApacheRequestEvent = nil;
ApacheOnAuthChecker: TApacheRequestEvent = nil;
ApacheOnCheckUserId: TApacheRequestEvent = nil;
ApacheOnHeaderParser: TApacheRequestEvent = nil;
ApacheOnAccessChecker: TApacheRequestEvent = nil;
ApacheOnPostReadRequest: TApacheRequestEvent = nil;
ApacheOnTranslateHandler: TApacheRequestEvent = nil;
var
ModuleName: array[0..255] of char;
implementation
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
BrkrConst;
var
default_module_ptr: Pmodule;
// Helper functions
procedure set_module(defModule: Pmodule);
begin
default_module_ptr := defModule;
end;
function GetContentType: string;
var
p1, p2: pchar;
begin
{$IFDEF MSWINDOWS}
p1 := strrscan(ModuleName, '\'); {do not localize}
{$ENDIF}
{$IFDEF LINUX}
p1 := strrscan(ModuleName, '/'); {do not localize}
{$ENDIF}
if p1 <> nil then p1 := p1 + 1
else p1 := ModuleName;
p2 := strrscan(ModuleName, '.'); {do not localize}
if p2 = nil then p2 := p1 + strlen(p1);
SetString(result, p1, p2 - p1);
result := LowerCase(result) + '-handler'; {do not localize}
end;
// Apache dispatch interface
function apache_handlers(r: Prequest_rec): integer; cdecl; export;
begin
result := (Application as TApacheApplication).ProcessRequest(r^);
end;
procedure apache_init(server: Pserver_rec; pool: Ppool); cdecl; export;
begin
with (Application as TApacheApplication) do
if Assigned(ApacheOnInit) then
ApacheOnInit(server, pool);
end;
procedure apache_child_init(Server: Pserver_rec; Pool: Ppool); cdecl; export;
begin
with (Application as TApacheApplication) do
if Assigned(ApacheOnChildInit) then
ApacheOnChildInit(server, pool);
end;
procedure apache_child_exit(server: Pserver_rec; pool: Ppool); cdecl; export;
begin
with (Application as TApacheApplication) do
if Assigned(ApacheOnChildExit) then
ApacheOnChildExit(server, pool);
end;
function apache_create_dir_config(pool: Ppool; szDir: pchar): pointer; cdecl; export;
begin
result := nil;
with (Application as TApacheApplication) do
if Assigned(ApacheOnCreateDirConfig) then
result := ApacheOnCreateDirConfig(pool, szDir);
end;
function apache_merge_dir_config(pool: Ppool; base_conf, new_conf: pointer): pointer; cdecl; export;
begin
result := base_conf;
with (Application as TApacheApplication) do
if Assigned(ApacheOnMergeDirConfig) then
result := ApacheOnMergeDirConfig(pool, base_conf, new_conf);
end;
function apache_create_server_config(pool: Ppool; server: Pserver_rec): pointer; cdecl; export;
begin
result := server;
with (Application as TApacheApplication) do
if Assigned(ApacheOnCreateServerConfig) then
result := ApacheOnCreateServerConfig(pool, server);
end;
function apache_merge_server_config(pool: Ppool; base_conf, new_conf: pointer): pointer; cdecl; export;
begin
result := base_conf;
with (Application as TApacheApplication) do
if Assigned(ApacheOnMergeServerConfig) then
result := ApacheOnMergeServerConfig(pool, base_conf, new_conf);
end;
function apache_logger(r: Prequest_rec): integer; cdecl; export;
begin
result := 0;
with (Application as TApacheApplication) do
if Assigned(ApacheOnLogger) then
result := ApacheOnLogger(r);
end;
function apache_fixer_upper(r: Prequest_rec): integer; cdecl; export;
begin
result := 0;
with (Application as TApacheApplication) do
if Assigned(ApacheOnFixUps) then
result := ApacheOnFixUps(r);
end;
function apache_type_checker(r: Prequest_rec): integer; cdecl; export;
begin
result := 0;
with (Application as TApacheApplication) do
if Assigned(ApacheOnTypeChecker) then
result := ApacheOnTypeChecker(r);
end;
function apache_auth_checker(r: Prequest_rec): integer; cdecl; export;
begin
result := 0;
with (Application as TApacheApplication) do
if Assigned(ApacheOnAuthChecker) then
result := ApacheOnAuthChecker(r);
end;
function apache_check_user_id(r: Prequest_rec): integer; cdecl; export;
begin
result := 0;
with (Application as TApacheApplication) do
if Assigned(ApacheOnCheckUserId) then
result := ApacheOnCheckUserId(r);
end;
function apache_header_parser(r: Prequest_rec): integer; cdecl; export;
begin
result := 0;
with (Application as TApacheApplication) do
if Assigned(ApacheOnHeaderParser) then
result := ApacheOnHeaderParser(r);
end;
function apache_access_checker(r: Prequest_rec): integer; cdecl; export;
begin
result := 0;
with (Application as TApacheApplication) do
if Assigned(ApacheOnAccessChecker) then
result := ApacheOnAccessChecker(r);
end;
function apache_post_read_request(r: Prequest_rec): integer; cdecl; export;
begin
result := 0;
with (Application as TApacheApplication) do
if Assigned(ApacheOnPostReadRequest) then
result := ApacheOnPostReadRequest(r);
end;
function apache_translate_handler(r: Prequest_rec): integer; cdecl; export;
begin
result := 0;
with (Application as TApacheApplication) do
if Assigned(ApacheOnTranslateHandler) then
result := ApacheOnTranslateHandler(r);
end;
// TApacheApplication
procedure HandleServerException(E: TObject; var r: request_rec);
var
ErrorMessage, EMsg: string;
begin
if E is Exception then
EMsg := Exception(E).Message
else
EMsg := '';
ErrorMessage := Format(sInternalServerError, [E.ClassName, EMsg]);
r.content_type := 'text/html';
ap_table_set(r.headers_out, 'Content-Length', pchar(IntToStr(Length(ErrorMessage))));
ap_send_http_header(@r);
ap_rputs(pchar(ErrorMessage), @r);
end;
constructor TApacheApplication.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Classes.ApplicationHandleException := ApacheHandleException;
FFactory := nil;
end;
destructor TApacheApplication.Destroy;
begin
Classes.ApplicationHandleException := nil;
inherited Destroy;
end;
procedure TApacheApplication.Initialize;
begin
{ NOTE: Use the pointer and not the apache_module instance directly to
allow another module to be set (C++Builder uses that technique) }
with default_module_ptr^ do
begin
// STANDARD_MODULE_STUFF
// must appear in all module records.
version := MODULE_MAGIC_NUMBER_MAJOR;
minor_version := MODULE_MAGIC_NUMBER_MINOR;
module_index := -1;
name := ModuleName;
dynamic_load_handle := nil;
next := nil;
magic := MODULE_MAGIC_COOKIE;
cmds := nil;
handlers := request_handlers;
if Assigned(ApacheOnInit) then
init := apache_init
else init := nil;
if Assigned(ApacheOnCreateDirConfig) then
create_dir_config := apache_create_dir_config
else create_dir_config := nil;
if Assigned(ApacheOnMergeDirConfig) then
merge_dir_config := apache_merge_dir_config
else merge_dir_config := nil;
if Assigned(ApacheOnCreateServerConfig) then
create_server_config := apache_create_server_config
else create_server_config := nil;
if Assigned(ApacheOnMergeServerConfig) then
merge_server_config := apache_merge_server_config
else merge_server_config := nil;
if Assigned(ApacheOnTranslateHandler) then
translate_handler := apache_translate_handler
else translate_handler := nil;
if Assigned(ApacheOnCheckUserId) then
ap_check_user_id := apache_check_user_id
else ap_check_user_id := nil;
if Assigned(ApacheOnAuthChecker) then
auth_checker := apache_auth_checker
else auth_checker := nil;
if Assigned(ApacheOnAccessChecker) then
access_checker := apache_access_checker
else access_checker := nil;
if Assigned(ApacheOnTypeChecker) then
type_checker := apache_type_checker
else type_checker := nil;
if Assigned(ApacheOnFixUps) then
fixer_upper := apache_fixer_upper
else fixer_upper := nil;
if Assigned(ApacheOnLogger) then
logger := apache_logger
else logger := nil;
if Assigned(ApacheOnHeaderParser) then
header_parser := apache_header_parser
else header_parser := nil;
if Assigned(ApacheOnChildInit) then
child_init := apache_child_init
else child_init := nil;
if Assigned(ApacheOnChildExit) then
child_exit := apache_child_exit
else child_exit := nil;
if Assigned(ApacheOnPostReadRequest) then
post_read_request := apache_post_read_request
else post_read_request := nil;
end;
end;
function TApacheApplication.ProcessRequest(var r: request_rec): ap_int;
var
HTTPRequest: TApacheRequest;
HTTPResponse: TApacheResponse;
begin
try
HTTPRequest := NewRequest(r);
try
HTTPResponse := NewResponse(HTTPRequest);
try
{ NOTE: Most exceptions will be handled in the except clause below.
or via a handler }
HandleRequest(HTTPRequest, HTTPResponse);
Result := HTTPResponse.ReturnCode; { Typically will be AP_OK }
finally
HTTPResponse.Free;
end;
finally
HTTPRequest.Free;
end;
except
HandleServerException(ExceptObject, r);
{ NOTE: Tell Apache we've handled this request; so there's no need to
pass this on to other modules }
Result := AP_OK;
end;
end;
procedure TApacheApplication.ApacheHandleException(Sender: TObject);
var
Handled: Boolean;
Intf: IWebExceptionHandler;
E: TObject;
begin
Handled := False;
if (ExceptObject is Exception) and
Supports(Sender, IWebExceptionHandler, Intf) then
Intf.HandleException(Exception(ExceptObject), Handled);
if not Handled then
begin
E := ExceptObject;
AcquireExceptionObject;
raise E;
end;
end;
procedure TApacheApplication.SetFactory(Value: TApacheFactory);
begin
Assert(FFactory = nil, 'Duplication ApacheFactory');
FFactory := Value;
end;
function TApacheApplication.GetFactory: TApacheFactory;
begin
if not Assigned(FFactory) then
FFactory := TApacheFactory.Create;
Result := FFactory;
end;
function TApacheApplication.NewRequest(var r: request_rec): TApacheRequest;
begin
Result := GetFactory.NewRequest(r);
end;
function TApacheApplication.NewResponse(ApacheRequest: TApacheRequest): TApacheResponse;
begin
Result := GetFactory.NewResponse(ApacheRequest);
end;
// TApacheFactory
constructor TApacheFactory.Create;
begin
inherited Create;
FApplication := Application as TApacheApplication;
FApplication.SetFactory(Self);
end;
function TApacheFactory.NewRequest(var r: request_rec): TApacheRequest;
begin
Result := TApacheRequest.Create(r);
end;
function TApacheFactory.NewResponse(ApacheRequest: TApacheRequest): TApacheResponse;
begin
Result := TApacheResponse.Create(ApacheRequest);
end;
procedure InitApplication;
var
S: string;
P: PChar;
begin
set_module(@apache_module);
Application := TApacheApplication.Create(nil);
S := GetModuleName(HInstance);
P := PChar(S);
if Length(S) + 1 > sizeof(ModuleName) then
// Exclude first part of path if path is very long
P := P + (Length(S)+ 1) - sizeof(ModuleName);
StrLCopy(ModuleName, P, sizeof(ModuleName));
StrLCopy(ContentType, pchar(GetContentType), sizeof(ContentType) - 1);
end;
procedure DoneApplication;
begin
try
Application.Free;
Application := nil;
except
on E:Exception do
if Assigned(HandleShutdownException) then
begin
Application := nil; // Application of no use at this point so clear it
Classes.ApplicationHandleException := nil;
HandleShutdownException(E);
end;
end;
end;
initialization
InitApplication;
AddExitProc(DoneApplication);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.