text stringlengths 14 6.51M |
|---|
unit ETL.DataModule.Main;
interface
uses Vcl.Controls, System.Classes, System.ImageList, Vcl.ImgList, cxGraphics, Vcl.Menus,
System.Actions, Vcl.ActnList;
type
TDmMain = class(TDataModule)
IL32: TcxImageList;
IL64: TcxImageList;
ILOld16: TImageList;
PopupLink: TPopupMenu;
MnEditLabel: TMenuItem;
MenuItem5: TMenuItem;
MnDelLink: TMenuItem;
AlComp: TActionList;
AcEditScript: TAction;
AcPreview: TAction;
AcEditTitle: TAction;
PopupComp: TPopupMenu;
MnEdit: TMenuItem;
MnPreview: TMenuItem;
N2: TMenuItem;
MenuItem1: TMenuItem;
N1: TMenuItem;
MnDeleteComponent: TMenuItem;
AcDelete: TAction;
IL16: TcxImageList;
AcRefresh: TAction;
Refresh1: TMenuItem;
procedure MnEditLabelClick(Sender: TObject);
procedure AcEditScriptExecute(Sender: TObject);
procedure AcPreviewExecute(Sender: TObject);
procedure AcEditTitleExecute(Sender: TObject);
procedure AcDeleteExecute(Sender: TObject);
procedure AcRefreshExecute(Sender: TObject);
private
public
end;
var
DmMain: TDmMain;
implementation
{ %CLASSGROUP 'Vcl.Controls.TControl' }
{$R *.dfm}
uses uMsg, ETL.Component, ETL.Link;
procedure TDmMain.AcDeleteExecute(Sender: TObject);
begin
TComponentETL(PopupComp.PopupComponent).Delete
end;
procedure TDmMain.AcEditScriptExecute(Sender: TObject);
begin
TComponentETL(PopupComp.PopupComponent).Edit;
end;
procedure TDmMain.AcEditTitleExecute(Sender: TObject);
var
s: string;
begin
s := TComponentETL(PopupComp.PopupComponent).Title;
if TMensagem.InputQuery('Edit Label', s) then
TComponentETL(PopupComp.PopupComponent).Title := s;
end;
procedure TDmMain.AcPreviewExecute(Sender: TObject);
var
LComponentETL: TComponentETL;
begin
LComponentETL := TComponentETL(PopupComp.PopupComponent);
if LComponentETL.Updated then
if TMensagem.Confirmacao('Do you want to update the data?') then
// if TMensagem.Confirmacao('Deseja atualizar os dados?') then
LComponentETL.RefreshPreviewForm;
LComponentETL.Preview;
end;
procedure TDmMain.AcRefreshExecute(Sender: TObject);
begin
TComponentETL(PopupComp.PopupComponent).RefreshPreviewForm;
end;
procedure TDmMain.MnEditLabelClick(Sender: TObject);
var
s: string;
begin
s := TLinkComponents(PopupLink.PopupComponent).Text;
if TMensagem.InputQuery('Edit Label', s) then
TLinkComponents(PopupLink.PopupComponent).Text := s;
end;
end.
|
{**************************************************************************}
{ }
{ This Source Code Form is subject to the terms of the Mozilla Public }
{ License, v. 2.0. If a copy of the MPL was not distributed with this }
{ file, You can obtain one at http://mozilla.org/MPL/2.0/. }
{ }
{ Software distributed under the License is distributed on an }
{ "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express }
{ or implied. See the License for the specific language }
{ governing rights and limitations under the License. }
{ }
{ Copyright Eric Grange / Creative IT }
{ }
{**************************************************************************}
unit dwsVMTOffsets;
interface
uses
dwsExprs, dwsDataContext, dwsSymbols;
var
vmt_Prepared : Boolean;
vmt_IDataContext_GetSelf : Integer;
vmt_IDataContext_AsPVariant : Integer;
vmt_IDataContext_AsPData : Integer;
vmt_IDataContext_FData : Integer;
vmt_IScriptObj_ExternalObject : Integer;
vmt_TExprBase_EvalNoResult : Integer;
vmt_TExprBase_EvalAsInteger : Integer;
vmt_TExprBase_EvalAsFloat : Integer;
vmt_TExprBase_EvalAsBoolean : Integer;
vmt_TExprBase_EvalAsString: Integer;
vmt_TExprBase_EvalAsScriptObj: Integer;
vmt_TExprBase_EvalAsVariant: Integer;
vmt_TExprBase_EvalAsDataContext: Integer;
vmt_TExprBase_AssignValueAsFloat : Integer;
vmt_TExprBase_AssignValueAsInteger : Integer;
vmt_ScriptDynamicArray_IScriptObj_To_FData : Integer;
vmt_ScriptObjInstance_IScriptObj_To_FData : Integer;
func_ustr_clear: pointer;
func_handle_finally: pointer;
func_intf_clear: pointer;
func_var_clr: pointer;
func_dyn_array_clear: pointer;
func_var_from_int: pointer;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses Variants;
// PrepareVMTOffsets
//
procedure PrepareVMTOffsets;
asm
mov vmt_Prepared, True
mov vmt_IDataContext_GetSelf, VMTOFFSET IDataContext.GetSelf
mov vmt_IDataContext_AsPData, VMTOFFSET IDataContext.AsPData
mov vmt_IDataContext_AsPVariant, VMTOFFSET IDataContext.AsPVariant
mov vmt_IScriptObj_ExternalObject, VMTOFFSET IScriptObj.GetExternalObject
mov vmt_TExprBase_EvalNoResult, VMTOFFSET TExprBase.EvalNoResult
mov vmt_TExprBase_EvalAsInteger, VMTOFFSET TExprBase.EvalAsInteger
mov vmt_TExprBase_EvalAsFloat, VMTOFFSET TExprBase.EvalAsFloat
mov vmt_TExprBase_EvalAsBoolean, VMTOFFSET TExprBase.EvalAsBoolean
mov vmt_TExprBase_EvalAsString, VMTOFFSET TExprBase.EvalAsString
mov vmt_TExprBase_EvalAsScriptObj, VMTOFFSET TExprBase.EvalAsScriptObj
mov vmt_TExprBase_EvalAsVariant, VMTOFFSET TExprBase.EvalAsVariant
mov vmt_TExprBase_EvalAsDataContext, VMTOFFSET TExprBase.EvalAsDataContext
mov vmt_TExprBase_AssignValueAsFloat, VMTOFFSET TExprBase.AssignValueAsFloat
mov vmt_TExprBase_AssignValueAsInteger, VMTOFFSET TExprBase.AssignValueAsInteger
{!!!FIXME!!!}
{$IFNDEF FPC}
mov func_ustr_clear, offset System.@UStrClr
mov func_intf_clear, offset System.@IntfClear
mov func_var_clr, offset variants.@VarClr
mov func_dyn_array_clear, offset system.@DynArrayClear
mov func_handle_finally, offset System.@HandleFinally
mov func_var_from_int, offset Variants.@VarFromInt
{$ENDIF}
end;
procedure PrepareDynArrayIDataContextToFDataOffset;
var
sda : TScriptDynamicArray;
soi : TScriptObjInstance;
i : IScriptObj;
begin
sda:=TScriptDynamicArray.CreateNew(nil);
i:=IScriptObj(sda);
vmt_ScriptDynamicArray_IScriptObj_To_FData:=NativeInt(i.AsPData)-NativeInt(i);
soi:=TScriptObjInstance.Create(nil);
i:=IScriptObj(soi);
vmt_ScriptObjInstance_IScriptObj_To_FData:=NativeInt(i.AsPData)-NativeInt(i);
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
PrepareVMTOffsets;
PrepareDynArrayIDataContextToFDataOffset;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ Copyright(c) 2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Surfaces;
interface
uses
System.UITypes, System.Generics.Collections, System.Classes, FMX.PixelFormats;
type
TBitmapSurface = class(TPersistent)
private
FBits: Pointer;
FPitch: Integer;
FWidth: Integer;
FHeight: Integer;
FPixelFormat: TPixelFormat;
FBytesPerPixel: Integer;
function GetScanline(Index: Integer): Pointer;
function GetPixel(X, Y: Integer): Cardinal;
procedure SetPixel(X, Y: Integer; const Value: Cardinal);
public
property Bits: Pointer read FBits;
property Pitch: Integer read FPitch;
property Width: Integer read FWidth;
property Height: Integer read FHeight;
property PixelFormat: TPixelFormat read FPixelFormat;
property BytesPerPixel: Integer read FBytesPerPixel;
property Scanline[Index: Integer]: Pointer read GetScanline;
property Pixels[X, Y: Integer]: Cardinal read GetPixel write SetPixel;
function GetPixelAddr(X, Y: Integer): Pointer;
procedure SetSize(AWidth, AHeight: Integer; APixelFormat: TPixelFormat = pfUnknown);
procedure Clear(Color: Cardinal);
constructor Create();
destructor Destroy(); override;
end;
TMipmapSurface = class(TBitmapSurface)
private type
TMipmapSurfaces = TObjectList<TMipmapSurface>;
private
FChildMipmaps: TMipmapSurfaces;
function GetMipCount(): Integer;
function GetMip(MipIndex: Integer): TMipmapSurface;
protected
procedure StretchHalfFrom(const Source: TMipmapSurface);
public
property MipCount: Integer read GetMipCount;
property Mip[MipIndex: Integer]: TMipmapSurface read GetMip;
procedure GenerateMips();
procedure ClearMips();
constructor Create();
destructor Destroy(); override;
end;
implementation
uses
System.SysUtils, System.RTLConsts;
function ComputePixelAverage2(Color1, Color2: TAlphaColor): TAlphaColor;
begin
TAlphaColorRec(Result).R := (Integer(TAlphaColorRec(Color1).R) + TAlphaColorRec(Color2).R) div 2;
TAlphaColorRec(Result).G := (Integer(TAlphaColorRec(Color1).G) + TAlphaColorRec(Color2).G) div 2;
TAlphaColorRec(Result).B := (Integer(TAlphaColorRec(Color1).B) + TAlphaColorRec(Color2).B) div 2;
TAlphaColorRec(Result).A := (Integer(TAlphaColorRec(Color1).A) + TAlphaColorRec(Color2).A) div 2;
end;
function ComputePixelAverage4(Color1, Color2, Color3, Color4: TAlphaColor): TAlphaColor;
begin
TAlphaColorRec(Result).R := (Integer(TAlphaColorRec(Color1).R) + TAlphaColorRec(Color2).R + TAlphaColorRec(Color3).R +
TAlphaColorRec(Color4).R) div 4;
TAlphaColorRec(Result).G := (Integer(TAlphaColorRec(Color1).G) + TAlphaColorRec(Color2).G + TAlphaColorRec(Color3).G +
TAlphaColorRec(Color4).G) div 4;
TAlphaColorRec(Result).B := (Integer(TAlphaColorRec(Color1).B) + TAlphaColorRec(Color2).B + TAlphaColorRec(Color3).B +
TAlphaColorRec(Color4).B) div 4;
TAlphaColorRec(Result).A := (Integer(TAlphaColorRec(Color1).A) + TAlphaColorRec(Color2).A + TAlphaColorRec(Color3).A +
TAlphaColorRec(Color4).A) div 4;
end;
constructor TBitmapSurface.Create();
begin
inherited;
FBits := nil;
FPitch := 0;
FWidth := 0;
FHeight := 0;
FPixelFormat := pfUnknown;
FBytesPerPixel := 0;
end;
destructor TBitmapSurface.Destroy();
begin
if (Assigned(FBits)) then
begin
FreeMem(FBits);
FBits := nil;
end;
inherited;
end;
function TBitmapSurface.GetScanline(Index: Integer): Pointer;
begin
if (Index >= 0) and (Index < FHeight) then
Result := Pointer(NativeInt(FBits) + (NativeInt(FPitch) * Index))
else
raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
end;
function TBitmapSurface.GetPixel(X, Y: Integer): Cardinal;
var
SrcPtr: Pointer;
begin
if (X < 0) or (Y < 0) or (X >= FWidth) or (Y >= FHeight) then
raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
if (FPixelFormat <> pfUnknown) then
begin
SrcPtr := Pointer(NativeInt(FBits) + (NativeInt(FPitch) * Y) + (NativeInt(X) * GetPixelFormatBytes(FPixelFormat)));
Result := PixelToAlphaColor(SrcPtr, FPixelFormat);
end
else
Result := 0;
end;
procedure TBitmapSurface.SetPixel(X, Y: Integer; const Value: Cardinal);
var
DestPtr: Pointer;
begin
if (X < 0) or (Y < 0) or (X >= FWidth) or (Y >= FHeight) then
raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
if (FPixelFormat <> pfUnknown) then
begin
DestPtr := Pointer(NativeInt(FBits) + (NativeInt(FPitch) * Y) + (NativeInt(X) * GetPixelFormatBytes(FPixelFormat)));
AlphaColorToPixel(Value, DestPtr, FPixelFormat);
end;
end;
function TBitmapSurface.GetPixelAddr(X, Y: Integer): Pointer;
begin
if (X < 0) or (Y < 0) or (X >= FWidth) or (Y >= FHeight) then
raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
if (FPixelFormat <> pfUnknown) then
begin
Result := Pointer(NativeInt(FBits) + (NativeInt(FPitch) * Y) + (NativeInt(X) * GetPixelFormatBytes(FPixelFormat)));
end
else
begin
Result := Pointer(NativeInt(FBits) + (NativeInt(FPitch) * Y) + (NativeInt(X) * FBytesPerPixel));
end;
end;
procedure TBitmapSurface.SetSize(AWidth, AHeight: Integer; APixelFormat: TPixelFormat);
var
NumOfBytes: Integer;
begin
FPixelFormat := APixelFormat;
if (FPixelFormat = pfUnknown) then
FPixelFormat := pfA8R8G8B8;
FBytesPerPixel := GetPixelFormatBytes(FPixelFormat);
FWidth := AWidth;
if (FWidth < 0) then
FWidth := 0;
FHeight := AHeight;
if (FHeight < 0) then
FHeight := 0;
FPitch := FWidth * FBytesPerPixel;
NumOfBytes := FWidth * FHeight * FBytesPerPixel;
ReallocMem(FBits, NumOfBytes);
FillChar(FBits^, NumOfBytes, 0);
end;
procedure TBitmapSurface.Clear(Color: Cardinal);
var
Index: Integer;
Dest: Pointer;
begin
if (FWidth < 1) or (FHeight < 1) or (not Assigned(FBits)) then
Exit;
Dest := FBits;
for Index := 0 to (FWidth * FHeight) - 1 do
begin
AlphaColorToPixel(Color, Dest, FPixelFormat);
Inc(NativeInt(Dest), FBytesPerPixel);
end;
end;
constructor TMipmapSurface.Create();
begin
inherited;
FChildMipmaps := TMipmapSurfaces.Create();
end;
destructor TMipmapSurface.Destroy();
begin
FChildMipmaps.Free;
inherited;
end;
function TMipmapSurface.GetMipCount(): Integer;
begin
Result := FChildMipmaps.Count;
end;
function TMipmapSurface.GetMip(MipIndex: Integer): TMipmapSurface;
begin
if (MipIndex >= 0) and (MipIndex < FChildMipmaps.Count) then
Result := FChildMipmaps[MipIndex]
else
raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange);
end;
procedure TMipmapSurface.StretchHalfFrom(const Source: TMipmapSurface);
var
PosX, PosY: Integer;
NewWidth, NewHeight: Integer;
begin
if (Source.PixelFormat = pfUnknown) or (Source.Width < 1) or (Source.Height < 1) or ((Source.Width < 2) and (Source.Height < 2)) then
Exit;
NewWidth := Source.Width div 2;
if (NewWidth < 1) then
NewWidth := 1;
NewHeight := Source.Height div 2;
if (NewHeight < 1) then
NewHeight := 1;
if (FWidth <> NewWidth) or (FHeight <> NewHeight) or (FPixelFormat <> Source.PixelFormat) then
SetSize(NewWidth, NewHeight, Source.PixelFormat);
if (Source.Width > 1) and (Source.Height = 1) then
begin // (W)x(1) -> (W/2)x(1)
for PosX := 0 to FWidth - 1 do
Pixels[PosX, 0] := ComputePixelAverage2(Source.Pixels[PosX * 2, 0], Source.Pixels[(PosX * 2) + 1, 0]);
end
else if (Source.Width = 1) and (Source.Height > 1) then
begin // (1)x(H) -> (1)x(H/2)
for PosY := 0 to FHeight - 1 do
Pixels[0, PosY] := ComputePixelAverage2(Source.Pixels[0, PosY * 2], Source.Pixels[0, (PosY * 2) + 1]);
end
else
begin // General solution (W and H are bigger than 1)
for PosY := 0 to FHeight - 1 do
for PosX := 0 to FWidth - 1 do
Pixels[PosX, PosY] := ComputePixelAverage4(Source.Pixels[PosX * 2, PosY * 2], Source.Pixels[(PosX * 2) + 1, PosY * 2],
Source.Pixels[PosX * 2, (PosY * 2) + 1], Source.Pixels[(PosX * 2) + 1, (PosY * 2) + 1]);
end;
end;
procedure TMipmapSurface.GenerateMips();
var
Source, Dest: TMipmapSurface;
NewIndex: Integer;
begin
FChildMipmaps.Clear();
Source := Self;
while ((Source.Width > 1) or (Source.Height > 1)) and (Source.PixelFormat <> pfUnknown) do
begin
NewIndex := FChildMipmaps.Add(TMipmapSurface.Create());
Dest := FChildMipmaps[NewIndex];
if (not Assigned(Dest)) then
Break;
Dest.StretchHalfFrom(Source);
Source := Dest;
end;
end;
procedure TMipmapSurface.ClearMips();
begin
FChildMipmaps.Clear();
end;
end.
|
unit EntradaSaida;
interface
uses SysUtils, Contnrs;
type
TEntradaSaida = class
private
Fcodigo :Integer;
Fnum_documento :Integer;
Fdata :TDateTime;
Fentrada_saida :String;
Ftipo :String;
Fobservacao :String;
Fcodigo_item :Integer;
Fquantidade :Real;
Fcodigo_usuario :Integer;
FPreco_custo :Real;
FCodigo_fornecedor: integer;
FValor_total: Real;
FCodigo_validade: Integer;
public
property codigo :Integer read Fcodigo write Fcodigo;
property num_documento :Integer read Fnum_documento write Fnum_documento;
property data :TDateTime read Fdata write Fdata;
property entrada_saida :String read Fentrada_saida write Fentrada_saida;
property tipo :String read Ftipo write Ftipo;
property observacao :String read Fobservacao write Fobservacao;
{ codigo_item e o codigo do produto normal ou codigo do produto/dispensa }
property codigo_item :Integer read Fcodigo_item write Fcodigo_item;
property quantidade :Real read Fquantidade write Fquantidade;
property codigo_usuario :Integer read Fcodigo_usuario write Fcodigo_usuario;
property preco_custo :Real read Fpreco_custo write Fpreco_custo;
property codigo_fornecedor :integer read FCodigo_fornecedor write FCodigo_fornecedor;
property valor_total :Real read FValor_total write FValor_total;
property codigo_validade :Integer read FCodigo_validade write FCodigo_validade;
end;
implementation
{ TEntradaSaida }
end.
|
Unit ColorWheel;
Interface
Uses
Classes, Forms, Graphics;
Type
TValueBar=Class;
TColorWheel=Class( TControl )
Protected
FValueBar: TValueBar;
FHue: longint;
FSaturation: real;
FCursorDrawn: boolean;
FOldCursorX, FOldCursorY: longint;
FOldCursorSize: longint;
FMarginWidth: longint;
FCursorSize: longint;
FWhiteAreaPercent: longint; // 0 to 50 percent of circle radius that is pure white
FOnChange: TNotifyEvent;
Procedure SetupComponent; Override;
Procedure SetupShow; Override;
Procedure HSFromPoint( X, Y: longint;
Var H: longint;
Var S: real );
Procedure DrawCursor;
Procedure Resize; override;
Procedure SetMarginWidth( NewWidth: longint );
Procedure SetCursorSize( NewSize: longint );
Procedure SetValueBar( ValueBar: TValueBar );
Procedure SetWhiteAreaPercent( WhiteAreaPercent: longint );
Procedure Notification(AComponent:TComponent;Operation:TOperation); override;
Function DrawWidth: longint;
Function DrawHeight: longint;
Procedure MouseDown( Button: TMouseButton;
ShiftState: TShiftState;
X, Y: Longint ); Override;
Procedure MouseMove( ShiftState: TShiftState;
X, Y: Longint ); Override;
Procedure MouseUp( Button: TMouseButton;
ShiftState: TShiftState;
X, Y: Longint ); Override;
Procedure Change;
Property OnCloseQuery; // hide it
Public
Destructor Destroy; Override;
Procedure Redraw( const rec: Trect ); override;
Property Hue: longint read FHue;
Property Saturation: real read FSaturation;
Procedure SetSelectedColor( const NewColor: TColor );
Published
Property Color;
Property ParentColor;
Property ValueBar: TValueBar read FValueBar write SetValueBar;
Property MarginWidth: longint read FMarginWidth write SetMarginWidth;
Property CursorSize: longint read FCursorSize write SetCursorSize;
Property ZOrder;
Property WhiteAreaPercent: longint read FWhiteAreaPercent write SetWhiteAreaPercent;
Property OnChange: TNotifyEvent read FOnChange write FOnChange;
End;
TValueBar=Class( TControl )
Protected
FColorWheel: TColorWheel;
FHue: longint;
FSaturation: real;
FValue: real;
FCursorDrawn: boolean;
FOldCursorY: longint;
FMarginWidth: longint;
FCursorHeight: longint;
FOnChange: TNotifyEvent;
FDither: boolean;
Procedure SetupComponent; Override;
Procedure SetupShow; Override;
Procedure DrawCursor;
Procedure Resize; override;
Procedure SetMarginWidth( NewWidth: longint );
Procedure SetValue( Value: real );
Procedure SetDither( Dither: boolean );
Procedure SetCursorHeight( CursorHeight: longint );
Function GetSelectedColor: TColor;
Procedure Change;
Function DrawWidth: longint;
Function DrawHeight: longint;
Procedure MouseDown( Button: TMouseButton;
ShiftState: TShiftState;
X, Y: Longint ); Override;
Procedure MouseMove( ShiftState: TShiftState;
X, Y: Longint ); Override;
Procedure MouseUp( Button: TMouseButton;
ShiftState: TShiftState;
X, Y: Longint ); Override;
Function ValueFromY( Y: longint ): real;
Procedure DrawLine( Y: longint );
Property OnCloseQuery; // hide it
Public
Destructor Destroy; Override;
Procedure Redraw( const rec: Trect ); override;
Procedure SetHS( Hue: longint; Sat: real );
Published
Property Color;
Property ParentColor;
Property Value: real read FValue write SetValue;
Property SelectedColor: TColor read GetSelectedColor;
property Dither: boolean read FDither write SetDither;
Property MarginWidth: longint read FMarginWidth write SetMarginWidth;
Property CursorHeight: longint read FCursorHeight write SetCursorHeight;
Property ZOrder;
Property OnChange: TNotifyEvent read FOnChange write FOnChange;
End;
Exports
TColorWheel,'User','ColorWheel.bmp',
TValueBar, 'User', 'ValueBar.bmp';
Implementation
Uses
ColorMapping, PMGPI;
Const
RadToHue: real = 1536/(2*pi);
Procedure TColorWheel.SetupComponent;
Begin
Inherited SetupComponent;
FMarginWidth:= 5;
FCursorSize:= 5;
Width:= 100;
Height:= 100;
Name:= 'ColorWheel';
ParentColor:= True;
Exclude(ComponentState, csAcceptsControls);
FWhiteAreaPercent:= 10;
End;
Procedure TColorWheel.SetupShow;
Begin
Inherited SetupShow;
End;
Destructor TColorWheel.Destroy;
Begin
Inherited Destroy;
End;
Procedure TColorWheel.ReDraw( const rec: Trect );
Var
x,y : longint;
Hue: longint;
saturation: real;
c: tcolor;
r: TRect;
Begin
Canvas.ClipRect:= rec;
// clear background rectangle
Canvas.FillRect( rec, Color );
if ( Width < MarginWidth * 2 ) or
( Height < MarginWidth * 2 ) then
// margins too big
exit;
{ Bugger there is a bug in Arc - it starts drawing
from last position
Canvas.Pen.Color:= clBtnHighlight;
Canvas.Arc( Width div 2, Height div 2,
DrawWidth div 2 + 1, DrawHeight div 2 + 1,
45, 180 );
Canvas.Pen.Color:= clBtnShadow;
Canvas.Arc( Width div 2, Height div 2,
DrawWidth div 2 + 1, DrawHeight div 2 + 1,
225, 180 );}
if Designed then
begin
// When designing, don't draw colors
// but draw an outline
Canvas.Pen.Style:= psDash;
r.Left:= 0;
r.Right:= Width - 1;
r.Bottom:= 0;
r.Top:= Height - 1;
Canvas.Rectangle( r );
Canvas.Ellipse( Width div 2, Height div 2,
DrawWidth div 2 + 1, DrawHeight div 2 + 1 );
exit;
end;
if ( Width < MarginWidth * 2 ) or ( Height < MarginWIdth * 2 ) then
exit;
// scan all potential pixels and draw points on the wheel
for X:=0 to DrawWidth-1 do
begin
for Y:=0 to DrawHeight-1 do
begin
// work out hue and saturation for point
HSFromPoint( X, Y, Hue, Saturation );
if Saturation<=1.0 then
begin
// point is within wheel
C:= HSVToRGB( Hue, Saturation, 1.0 );
// draw the pixel
Canvas.Pixels[ X+FMarginWidth, Y+FMarginWidth ]:= C;
end;
end;
end;
FCursorDrawn:= false; // make cursor draw without erasing first
DrawCursor;
Canvas.DeleteClipRegion;
End;
Function TColorWheel.DrawWidth: longint;
Begin
Result:= Width - FMarginWidth*2;
End;
Function TColorWheel.DrawHeight: longint;
Begin
Result:= Height - FMarginWidth*2;
End;
Procedure TColorWheel.SetSelectedColor( const NewColor: TColor );
Var
Value: real;
Begin
RGBToHSV( NewColor, FHue, FSaturation, Value );
Change;
if FValueBar<>nil then
FValueBar.Value:= Value;
End;
Procedure TColorWheel.Change;
Var
C: TColor;
H: longint;
S, V: real;
Begin
DrawCursor;
C:= HSVToRGB( FHue, FSaturation, 1.0 );
RGBToHSV( C, H, S, V );
if FValueBar<>nil then
FValueBar.SetHS( H, S );
if FOnChange <> nil then
FOnChange( self );
End;
Function AngleFrom( x, y: real ): real;
//
// 1|0
// ---+----
// 2|3
Begin
if X = 0 then
begin
if Y > 0 then
Result:= pi/2
else
Result:= 3*pi/2;
end
else
begin
Result:= arctan( abs( y ) / abs( x ) );
if ( x < 0 ) and ( y>=0 ) then
// quadrant 1
Result:= pi-Result
else if ( x < 0 ) and ( y<0 ) then
// quadrant 2
Result:= Result+pi
else if ( x >= 0 ) and ( y<0 ) then
// quadrant 3
Result:= 2*pi-Result;
end;
end;
// Calculate hue and saturation for a given point in the color wheel
Procedure TColorWheel.HSFromPoint( X, Y: longint;
Var H: longint;
Var S: real );
Var
xp, yp: real;
halfw, halfh: longint;
Begin
halfw:= DrawWidth div 2;
halfh:= DrawHeight div 2;
xp:= ( x- halfw )/halfw; // x as -1..1
yp:= ( y- halfh )/halfh; // y as -1..1
H:= RadToHue * AngleFrom( xp, yp );
S:= sqrt( xp*xp+yp*yp );
// scale saturation and limit to white, for white area
S:= S * ( 1 + ( FWhiteAreaPercent / 100.0 ) ) - ( FWhiteAreaPercent / 100.0 );
if S < 0 then
S:= 0;
end;
Procedure TColorWheel.DrawCursor;
Var
Angle: real;
X, Y: longint;
OldMode: TPenMode;
S: real;
Begin
if Handle = 0 then
exit;
if ( Width < MarginWidth * 2 ) or
( Height < MarginWidth * 2 ) then
exit;
Canvas.Pen.Width:= 2;
Angle:= FHue/RadToHue;
// Scale distance from centre for white area
S:= FSaturation;
if S > 0 then
S:= S * ( 1 - ( FWhiteAreaPercent / 100.0 ) ) + ( FWhiteAreaPercent / 100.0 );
// work out point for selected hue and saturation
X:= Width div 2+cos( Angle )*S* ( DrawWidth div 2 );
Y:= Height div 2+sin( Angle )*S* ( DrawHeight div 2 );
OldMode:= Canvas.Pen.Mode;
Canvas.Pen.Mode:= pmNot; // invert pixels
if FCursorDrawn then
begin
// erase
Canvas.Line( FOldCursorX-FOldCursorSize, FOldCursorY,
FOldCursorX+FOldCursorSize, FOldCursorY );
Canvas.Line( FOldCursorX, FOldCursorY-FOldCursorSize,
FOldCursorX, FOldCursorY+FOldCursorSize );
end;
// draw cursor
Canvas.Line( X-FCursorSize, Y,
X+FCursorSize, Y );
Canvas.Line( X, Y-FCursorSize,
X, Y+FCursorSize );
FOldCursorX:= X;
FOldCursorY:= Y;
FOldCursorSize:= FCursorSize;
FCursorDrawn:= true;
Canvas.Pen.Mode:= OldMode;
End;
Procedure TColorWheel.Resize;
Begin
Invalidate;
End;
Procedure TColorWheel.SetMarginWidth( NewWidth: longint );
Begin
FMarginWidth:= NewWidth;
if Handle = 0 then
exit;
Invalidate;
End;
Procedure TColorWheel.SetCursorSize( NewSize: longint );
Begin
FCursorSize:= NewSize;
if Handle = 0 then
exit;
DrawCursor;
End;
Procedure TColorWheel.SetValueBar( ValueBar: TValueBar );
Begin
if FValueBar<>nil then
// tell the old value bar it's no longer controlled by this wheel
FValueBar.FColorWheel:= nil;
FValueBar:= ValueBar;
if FValueBar<>nil then
begin
// Tell value bar it is controlled by this component
FValueBar.FColorWheel:= Self;
// request notification when other is freed
FValueBar.FreeNotification(Self);
end;
End;
Procedure TColorWheel.SetWhiteAreaPercent( WhiteAreaPercent: longint );
begin
if WhiteAreaPercent > 50 then
WhiteAreaPercent:= 50;
if WhiteAreaPercent < 0 then
WhiteAreaPercent:= 0;
FWhiteAreaPercent:= WhiteAreaPercent;
Invalidate;
end;
Procedure TColorWheel.Notification(AComponent:TComponent;Operation:TOperation);
Begin
Inherited Notification(AComponent,Operation);
If Operation = opRemove Then
Begin
If AComponent = FValueBar Then
FValueBar:= Nil;
end;
end;
Procedure TColorWheel.MouseDown( Button: TMouseButton;
ShiftState: TShiftState;
X, Y: Longint );
Begin
dec( X, FMarginWidth );
dec( Y, FMarginWidth );
HSFromPoint( X, Y, FHue, FSaturation );
if FSaturation>1.0 then
FSaturation:= 1.0;
Change;
MouseCapture:= True;
End;
Procedure TColorWheel.MouseMove( ShiftState: TShiftState;
X, Y: Longint );
Begin
if not MouseCapture then
exit;
dec( X, FMarginWidth );
dec( Y, FMarginWidth );
HSFromPoint( X, Y, FHue, FSaturation );
if FSaturation>1.0 then
FSaturation:= 1.0;
Change;
End;
Procedure TColorWheel.MouseUp( Button: TMouseButton;
ShiftState: TShiftState;
X, Y: Longint );
Begin
if not MouseCapture then
exit;
MouseCapture:= false;
End;
// --------------------------------
// Value bar
Procedure TValueBar.SetupComponent;
Begin
Inherited SetupComponent;
FMarginWidth:= 5;
Width:= 100;
Height:= 100;
Name:= 'ValueBar';
ParentColor:= True;
Exclude(ComponentState, csAcceptsControls);
FDither:= false;
FCursorHeight:= 10;
End;
Procedure TValueBar.SetupShow;
Begin
Inherited SetupShow;
End;
Destructor TValueBar.Destroy;
Begin
Inherited Destroy;
End;
Procedure TValueBar.DrawLine( Y: longint );
var
DrawVal: real;
c: tcolor;
r: TRect;
begin
DrawVal:= ValueFromY( Y );
C:= HSVToRGB( FHue, FSaturation, DrawVal );
if FDither then
begin
// draw using fillrect, which will dither
r.left:= FMarginWidth;
r.bottom:= Y;
r.Right:= Width-FMarginWidth;
r.top:= Y;
Canvas.FillRect( r, C );
end
else
begin
// draw using line, which will not dither
Canvas.Pen.Color:= C;
Canvas.Line( FMarginWidth, Y ,
Width-FMarginWidth-1, Y );
end;
end;
Procedure TValueBar.ReDraw( const rec: Trect );
Var
y : longint;
r: TRect;
Begin
Canvas.ClipRect:= rec;
if Designed then
begin
// when designing just drwa
// a rectangle to indicate
Canvas.FillRect( rec, Color );
Canvas.Pen.Style:= psDash;
r.Left:= 0;
r.Right:= Width - 1;
r.Bottom:= 0;
r.Top:= Height - 1;
Canvas.Rectangle( r );
if ( Width < MarginWidth * 2 ) or
( Height < MarginWidth * 2 ) then
exit;
r.left:= FMarginWidth;
r.top:= Height - FMarginWidth - 1;
r.right:= Width - FMarginWidth;
r.bottom:= FMarginWidth;
Canvas.Rectangle( r );
exit;
end;
// Draw margins
r.left:=0;
r.bottom:=0;
r.right:= FMarginWidth-1;
r.top:= Height-1;
Canvas.FillRect( r, Color ); // left
r.left:= Width-FMarginWidth;
r.right:= Width-1;
Canvas.FillRect( r, Color ); // right
r.left:= FMarginWidth;
r.right:=Width-FMarginWidth - 1;
r.bottom:= Height - FMarginWidth;
r.top:= Height - 1;
Canvas.FillRect( r, Color ); // top
r.bottom:= 0;
r.top:= FMarginWidth - 1;
Canvas.FillRect( r, Color ); // bottom
if ( Width < MarginWidth * 2 ) or
( Height < MarginWidth * 2 ) then
exit;
for Y:=0 to DrawHeight - 1 do
DrawLine( Y + FMarginWidth );
FCursorDrawn:= false;
DrawCursor;
Canvas.DeleteClipRegion;
End;
Procedure TValueBar.SetHS( Hue: longint; Sat: real );
Begin
FHue:= Hue;
FSaturation:= Sat;
Invalidate;
Change;
End;
Procedure TValueBar.SetValue( Value: real );
Begin
FValue:= Value;
Change;
End;
Function TValueBar.DrawWidth: longint;
Begin
Result:= Width - FMarginWidth*2;
End;
Function TValueBar.DrawHeight: longint;
Begin
Result:= Height - FMarginWidth*2;
End;
Procedure TValueBar.DrawCursor;
Var
Y: longint;
OldMode: TPenMode;
r: TRect;
Begin
if Handle = 0 then
exit;
if ( Width < MarginWidth * 2 ) or
( Height < MarginWidth * 2 ) then
exit;
if FCursorDrawn then
begin
// erase
// redraw margins
r.left:= 0;
r.right:= FMarginWidth - 1;
r.top:= FOldCursorY + FCursorHeight div 2;
r.bottom:= FOldCursorY - FCursorHeight div 2;
Canvas.FillRect( r, Color ); // left
r.left:= Width - FMarginWidth;
r.right:= Width - 1;
Canvas.FillRect( r, Color ); // left
for Y:= r.bottom to r.top do
if ( Y < FMarginWidth ) or ( Y >= ( Height - FMarginWidth ) ) then
begin
// top/ bottom margin
Canvas.Pen.Color:= Color;
Canvas.Line( FMarginWidth, Y, Width - FMarginWidth - 1, Y );
end
else
DrawLine( Y );
end;
Y:= FValue * ( DrawHeight-1 ) + FMarginWidth ;
r.left:= FMarginWidth;
r.right:= Width - FMarginWidth - 1;
r.top:= Y + FCursorHeight div 2;
r.bottom:= Y - FCursorHeight div 2;
Canvas.FillRect( r, GetSelectedColor );
Canvas.Pen.Color:= clBlack;
Canvas.ShadowedBorder( r, clBtnHighlight, clBtnShadow );
FOldCursorY:= Y;
FCursorDrawn:= true;
// Canvas.Pen.Mode:= OldMode;
End;
Procedure TValueBar.Resize;
Begin
if Handle = 0 then
exit;
Invalidate;
End;
Procedure TValueBar.SetMarginWidth( NewWidth: longint );
Begin
if MarginWidth<0 then
MarginWidth:= 0;
FMarginWidth:= NewWidth;
Invalidate;
End;
Procedure TValueBar.SetDither( Dither: boolean );
Begin
FDither:= Dither;
Invalidate;
End;
Procedure TValueBar.SetCursorHeight( CursorHeight: longint );
begin
if CursorHeight < 3 then
CursorHeight:= 3;
FCursorHeight:= CursorHeight;
Invalidate;
end;
Function TValueBar.GetSelectedColor: TColor;
Begin
Result:= HSVToRGB( FHue, FSaturation, FValue );
if not FDither then
Result:= GpiQueryNearestColor( Screen.Canvas.Handle,
0,
Result );
End;
Function TValueBar.ValueFromY( Y: longint ): real;
begin
Result:= ( Y-MarginWidth )/( DrawHeight-1 );
if Result<0 then
Result:= 0;
if Result>1.0 then
Result:= 1.0;
end;
Procedure TValueBar.MouseDown( Button: TMouseButton;
ShiftState: TShiftState;
X, Y: Longint );
Begin
FValue:= ValueFromY( Y );
Change;
MouseCapture:= True;
End;
Procedure TValueBar.MouseMove( ShiftState: TShiftState;
X, Y: Longint );
Begin
if not MouseCapture then
exit;
FValue:= ValueFromY( Y );
Change;
End;
Procedure TValueBar.MouseUp( Button: TMouseButton;
ShiftState: TShiftState;
X, Y: Longint );
Begin
if not MouseCapture then
exit;
MouseCapture:= false;
End;
Procedure TValueBar.Change;
begin
DrawCursor;
if FOnChange <> nil then
FOnChange( self );
end;
Initialization
{Register classes}
RegisterClasses([TColorWheel, TValueBar]);
End.
|
unit BCEnemy;
interface
uses iNESImage, contnrs;
// Used to store information about the enemy.
type
TBCEnemy = class(TiNESImageAccessor)
public
EnemyType : Byte;
Unused1 : Byte;
Unused2 : Byte;
Powerups : Byte;
ShieldStrength : Byte;
Amount : Byte;
constructor Create(pDataOffset : Integer;pAmountOffset : Integer);
end;
{ This is a class that will be used to store the
levels. This is a descendant of the TObjectList class.
The reason that I am not using a TObjectList, is that
for every access, you have to explicitly cast your objects
to their correct type.}
TBCEnemyList = class(TObjectList)
protected
function GetItem(Index: Integer) : TBCEnemy;
procedure SetItem(Index: Integer; const Value: TBCEnemy);
public
function Add(AObject: TBCEnemy) : Integer;
property Items[Index: Integer] : TBCEnemy read GetItem write SetItem;default;
function Last : TBCEnemy;
end;
implementation
{ TBCEnemy }
constructor TBCEnemy.Create(pDataOffset : Integer;pAmountOffset : Integer);
var
EnemyByte : Byte;
begin
EnemyByte :=ROM[pDataOffset];
self.EnemyType := EnemyByte Shr 5;
self.Unused1 := (Enemybyte Shr 4) and 1;
self.Unused2 := (Enemybyte Shr 3) and 1;
self.Powerups := (EnemyByte Shr 2) and 1;
self.ShieldStrength := EnemyByte and 3;
self.Amount :=ROM[pAmountOffset];
end;
{ TBCEnemyList }
function TBCEnemyList.Add(AObject: TBCEnemy): Integer;
begin
Result := inherited Add(AObject);
end;
function TBCEnemyList.GetItem(Index: Integer): TBCEnemy;
begin
Result := TBCEnemy(inherited Items[Index]);
end;
function TBCEnemyList.Last: TBCEnemy;
begin
result := TBCEnemy(inherited Last);
end;
procedure TBCEnemyList.SetItem(Index: Integer; const Value: TBCEnemy);
begin
inherited Items[Index] := Value;
end;
end.
|
{
Sobre o autor:
Guinther Pauli
Cursos Treinamentos Consultoria
Delphi Certified Professional - 3,5,6,7,2005,2006,Delphi Web,Kylix,XE
Microsoft Certified Professional - MCP,MCAD,MCSD.NET,MCTS,MCPD (C#,ASP.NET, Arquitetura)
Colaborador Editorial Revistas .net Magazine e ClubeDelphi
MVP (Most Valuable Professional) - Embarcadero Technologies - US
http://guintherpauli.blogspot.com
http://www.gpauli.com
http://www.facebook.com/guintherpauli
http://www.twitter.com/guintherpauli
http://br.linkedin.com/in/guintherpauli
Emails: guintherpauli@gmail.com; guinther@gpauli.com
Suporte Skype: guinther.pauli
}
unit uFrmMetaData;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uDM, Vcl.StdCtrls, Vcl.ComCtrls,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, Vcl.Grids, Vcl.DBGrids,
FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TFrmMetaData = class(TForm)
metaInfo: TFDMetaInfoQuery;
ds: TDataSource;
boxTabelas: TComboBox;
grid: TDBGrid;
Label1: TLabel;
boxInfoKind: TComboBox;
Label2: TLabel;
procedure FormShow(Sender: TObject);
procedure boxInfoKindChange(Sender: TObject);
private
function Database(): string;
procedure FillMetaInfoKindBox();
end;
var
FrmMetaData: TFrmMetaData;
implementation
{$R *.dfm}
uses
TypInfo;
procedure TFrmMetaData.boxInfoKindChange(Sender: TObject);
var
tabela: string;
begin
metaInfo.MetaInfoKind := TFDPhysMetaInfoKind(boxInfoKind.ItemIndex);
if boxTabelas.Text <> '' then
metaInfo.ObjectName := boxTabelas.Text;
metaInfo.Close();
metaInfo.Open();
// para firebird não precisa estas duas colunas
grid.Columns[1].Visible := false;
grid.Columns[2].Visible := false;
end;
procedure TFrmMetaData.FillMetaInfoKindBox();
var
i: integer;
begin
for i := Ord(Low(TFDPhysMetaInfoKind)) to ord(High(TFDPhysMetaInfoKind)) do
boxInfoKind.Items.Add(GetEnumName(TypeInfo(TFDPhysMetaInfoKind),i));
end;
procedure TFrmMetaData.FormShow(Sender: TObject);
begin
DM.con.GetTableNames(Database,'','',boxTabelas.Items);
FillMetaInfoKindBox();
end;
function TFrmMetaData.Database(): string;
begin
exit(DM.con.Params.Database);
end;
end.
|
unit Script_Datos;
interface
uses
SysUtils, Classes, DB, IBCustomDataSet, IBQuery, Controls,
Script_Mensaje, ScriptObject, IBDatabase, IBSQL, kbmMemTable,
ScriptDataCacheVertical, ScriptDataCache, Contnrs, ScriptEngine;
type
ESesionNotFound = class(Exception);
{$METHODINFO ON}
TTipoSesion = (tsDiaria, tsSemanal);
TZona = (zSinZona = 0, zAMenos, zAMas, zABMenos, zABMas, zBMenos, zBMas, zOMenos, zOMas);
TAmbienteIntradia = (aiSinAmbiente = 0, aiAlcistaContradiccionesSospechosas,
aiContinuidadPlana, aiRetrocesoTecnico, aiReboteTecnico, aiLigeraPresionAlcista,
aiBajadaMenorEsperada, aiPresionAlcista, aiDebilidadOrientadaBaja,
aiPresionBajista, aiAlzaEnganosa, aiDebilidadOrientadaAlza, aiBajaEnganosa,
aiPresionAlcistaCreciente, aiPresionAlcistaLatenteContenida,
aiBajaSubirMas, aiDecididamenteAlcista, aiIndecisionBandazosAlzaBaja,
aiVolatilidadInclinadaBaja, aiVolatilidadOrientadaAlza,
aiContinuidadCiertaOrientacionBajista, aiPresionBajistaAumento,
aiAlzaPresionBajistaLatente, aiIndefinicionMaxima, aiOrientacionBajistaContradicciones,
aiIndefinicionDecantadaAlza, aiRepeticionPerspectivasBajistas,
aiOrientacionClaramenteBajista);
TDatos = class(TScriptObjectInstance)
private
DataCacheFactory: TScriptDataCacheFactory;
Sesiones: array of integer;
DatosSesionNum: TStringList;
DatosToClean: TStringList;
Cursor: TScriptDataCache;
ScriptDatosEngine: TScriptEngine;
procedure ClearDatosSesionNum;
procedure ClearDatosToClean;
procedure InitializeSesiones;
function GetSesionNum(Index: Integer): TDatos;
function GetIDSesion: integer;
function GetIDValor: integer;
function GetTipoSesion: TTipoSesion;
procedure SetIDSesion(const Value: integer);
procedure SetIDValor(const Value: integer);
procedure SetTipoSesion(const Value: TTipoSesion);
public
constructor Create(const ScriptDatosEngine: TScriptEngine; const DataCacheFactory: TScriptDataCacheFactory);
destructor Destroy; override;
function Mensaje: TMensaje;
function AmbienteIntradia: TAmbienteIntradia;
function BandaAlta: currency;
function BandaBaja: currency;
function Cierre: currency;
function Apertura: currency;
function Volumen: integer;
function CambioAlzaDoble: currency;
function CambioAlzaSimple: currency;
function CambioBajaDoble: currency;
function CambioBajaSimple: currency;
function Correlacion: integer;
function DiasSeguidosNum: integer;
function DiasSeguidosPerCent: single;
function DimensionFractal: currency;
function Dinero: currency;
function DineroAlzaDoble: currency;
function DineroAlzaSimple: currency;
function DineroBajaDoble: currency;
function DineroBajaSimple: currency;
function Dobson10: integer;
function Dobson100: integer;
function Dobson130: integer;
function Dobson40: integer;
function Dobson70: integer;
function DobsonAlto10: integer;
function DobsonAlto100: integer;
function DobsonAlto130: integer;
function DobsonAlto40: integer;
function DobsonAlto70: integer;
function DobsonBajo10: integer;
function DobsonBajo100: integer;
function DobsonBajo130: integer;
function DobsonBajo40: integer;
function DobsonBajo70: integer;
function Maximo: currency;
function MaximoPrevisto: currency;
function MaximoPrevistoAprox: single;
function MaximoSePrevino: currency;
function Media200: currency;
function Minimo: currency;
function MinimoPrevisto: currency;
function MinimoPrevistoAprox: single;
function MinimoSePrevino: currency;
function DobsonNivelActual: integer;
function DobsonNivelBaja: integer;
function DobsonNivelSube: integer;
function IDCotizacion: integer;
function Papel: currency;
function PapelAlzaDoble: currency;
function PapelAlzaSimple: currency;
function PapelBajaDoble: currency;
function PapelBajaSimple: currency;
function PercentAlzaSimple: currency;
function PercentBajaSimple: currency;
function PivotPoint: currency;
function PivotPointR1: currency;
function PivotPointR2: currency;
function PivotPointR3: currency;
function PivotPointS1: currency;
function PivotPointS2: currency;
function PivotPointS3: currency;
function PotencialFractal: integer;
function RentabilidadAbierta: single;
function Rsi14: integer;
function Rsi140: integer;
function Stop: currency;
function Posicionado: currency;
function Variabilidad: single;
function Variacion: single;
function Volatilidad: single;
function Zona: TZona;
function ZonaAlzaDoble: TZona;
function ZonaAlzaSimple: TZona;
function ZonaBajaDoble: TZona;
function ZonaBajaSimple: TZona;
function Riesgo: Single;
function PresionVertical: Single;
function PresionVerticalAlzaSimple: Single;
function PresionVerticalAlzaDoble: Single;
function PresionVerticalBajaSimple: Single;
function PresionVerticalBajaDoble: Single;
function PresionLateral: Single;
function PresionLateralAlzaSimple: Single;
function PresionLateralAlzaDoble: Single;
function PresionLateralBajaSimple: Single;
function PresionLateralBajaDoble: Single;
published
property IDValor: integer read GetIDValor write SetIDValor;
property IDSesion: integer read GetIDSesion write SetIDSesion;
property TipoSesion: TTipoSesion read GetTipoSesion write SetTipoSesion;
public
property SesionNum[Index: Integer]: TDatos read GetSesionNum; default;
end;
{$METHODINFO OFF}
TScriptDatos = class(TScriptObject)
private
ScriptMensaje: TScriptMensaje;
FOIDSesion: integer;
ScriptDataCacheFactory: TScriptDataCacheFactory;
ScriptDatosEngine: TScriptEngine;
FTipoSesion: TTipoSesion;
function GetMensaje: TMensaje;
procedure SetOIDSesion(const Value: integer);
procedure SetTipoSesion(const Value: TTipoSesion);
function GetOIDValor: Integer;
procedure SetOIDValor(const Value: Integer);
property Mensaje: TMensaje read GetMensaje;
protected
function GetScriptInstance: TScriptObjectInstance; override;
function GetTipoSesion: TTipoSesion; virtual;
public
//No podemos pasar un TScriptDatosEngine porque sino se produce una referencia circular
constructor Create(const scriptDatosEngine: TScriptEngine; const verticalCache: boolean); reintroduce;
destructor Destroy; override;
property OIDValor: Integer read GetOIDValor write SetOIDValor;
property OIDSesion: integer read FOIDSesion write SetOIDSesion;
property TipoSesion: TTipoSesion read GetTipoSesion write SetTipoSesion;
end;
implementation
uses dmDataComun, Script, dmBD, dmDataComunSesion, UtilDB, ScriptDataCacheHorizontal,
ScriptDatosEngine;
resourcestring
NO_HAY_DATOS = 'No hay datos para el valor %s - %s en la fecha %s';
SESION_NOT_FOUND = 'No se ha encontrado la sesión %d';
{ TScriptDatos }
//No podemos pasar un TScriptDatosEngine porque sino se produce una referencia circular
constructor TScriptDatos.Create(const scriptDatosEngine: TScriptEngine; const verticalCache: boolean);
begin
inherited Create;
FTipoSesion := tsDiaria;
if verticalCache then
ScriptDataCacheFactory := TScriptDataCacheVerticalFactory.Create
else
ScriptDataCacheFactory := TScriptDataCacheHorizontalFactory.Create;
Self.ScriptDatosEngine := ScriptDatosEngine;
ScriptMensaje := TScriptMensaje.Create;
end;
destructor TScriptDatos.Destroy;
begin
ScriptMensaje.Free;
inherited;
// El inherited hará un Free del ObjectInstance, y ese ObjectInstance, que es un
// TDatos, utiliza la referencia al ScriptDataCacheFactory para realizar un
// ReleaseCursor, por lo que si no hacemos el Free del ScriptDataCacheFactory
// después del inherited, habrá un access violation.
ScriptDataCacheFactory.Free;
end;
function TScriptDatos.GetMensaje: TMensaje;
begin
try
ScriptMensaje.DataFlags := TDatos(FScriptInstance).Cursor.GetMensajeFlags;
result := TMensaje(ScriptMensaje.ScriptInstance);
except
on e: EDatoNoEncontrado do begin
raise;
end;
on e: Exception do begin
result := nil;
end;
end;
end;
function TScriptDatos.GetOIDValor: Integer;
begin
result := TDatos(FScriptInstance).Cursor.OIDValor;
end;
function TScriptDatos.GetScriptInstance: TScriptObjectInstance;
begin
result := TDatos.Create(ScriptDatosEngine, ScriptDataCacheFactory);
end;
function TScriptDatos.GetTipoSesion: TTipoSesion;
begin
result := FTipoSesion;
end;
procedure TScriptDatos.SetOIDSesion(const Value: integer);
begin
FOIDSesion := Value;
TDatos(FScriptInstance).IDSesion := Value;
end;
procedure TScriptDatos.SetOIDValor(const Value: Integer);
begin
TDatos(FScriptInstance).IDValor := Value;
end;
procedure TScriptDatos.SetTipoSesion(const Value: TTipoSesion);
begin
if FTipoSesion <> Value then begin
FTipoSesion := Value;
ScriptDataCacheFactory.InitializeCache;
end;
end;
{ TDatos }
function TDatos.AmbienteIntradia: TAmbienteIntradia;
var ambiente: string;
id: integer;
begin
try
ambiente := Cursor.GetAmbienteIntradia;
if ambiente = '' then
result := aiSinAmbiente
else begin
if ambiente = '0' then
result := aiAlcistaContradiccionesSospechosas
else begin
id := Ord(ambiente[1]) - Ord('A') + 2; // + 2 --> A = aiContinuidadPlana = 2
result := TAmbienteIntradia(id);
end;
end;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := aiSinAmbiente;
end;
end;
end;
function TDatos.Apertura: currency;
begin
try
result := Cursor.GetApertura;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.BandaAlta: currency;
begin
try
result := Cursor.GetBandaAlta;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.BandaBaja: currency;
begin
try
result := Cursor.GetBandaBaja;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.CambioAlzaDoble: currency;
begin
try
result := Cursor.GetCambioAlzaDoble;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.CambioAlzaSimple: currency;
begin
try
result := Cursor.GetCambioAlzaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.CambioBajaDoble: currency;
begin
try
result := Cursor.GetCambioBajaDoble;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.CambioBajaSimple: currency;
begin
try
result := Cursor.GetCambioBajaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Cierre: currency;
begin
try
result := Cursor.GetCierre;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
procedure TDatos.ClearDatosSesionNum;
var i: integer;
begin
for i := DatosSesionNum.Count - 1 downto 0 do
DatosSesionNum.Objects[i].Free;
DatosSesionNum.Clear;
end;
procedure TDatos.ClearDatosToClean;
var i: integer;
begin
for i := DatosToClean.Count - 1 downto 0 do
DatosToClean.Objects[i].Free;
DatosToClean.Clear;
end;
function TDatos.Correlacion: integer;
begin
try
result := Cursor.GetCorrelacion;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
constructor TDatos.Create(const ScriptDatosEngine: TScriptEngine;
const DataCacheFactory: TScriptDataCacheFactory);
begin
inherited Create;
Self.ScriptDatosEngine := ScriptDatosEngine;
Self.DataCacheFactory := dataCacheFactory;
Cursor := DataCacheFactory.GetCursor;
DatosToClean := TStringList.Create;
end;
destructor TDatos.Destroy;
begin
if DatosSesionNum <> nil then begin
ClearDatosSesionNum;
DatosSesionNum.Free;
end;
DataCacheFactory.ReleaseCursor(Cursor);
ClearDatosToClean;
DatosToClean.Free;
inherited Destroy;
end;
function TDatos.DiasSeguidosNum: integer;
begin
try
result := Cursor.GetDiasSeguidosNum;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DiasSeguidosPerCent: single;
begin
try
result := Cursor.GetDiasSeguidosPerCent;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DimensionFractal: currency;
begin
try
result := Cursor.GetDimensionFractal;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Dinero: currency;
begin
try
result := Cursor.GetDinero;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DineroAlzaDoble: currency;
begin
try
result := Cursor.GetDineroAlzaDoble;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DineroAlzaSimple: currency;
begin
try
result := Cursor.GetDineroAlzaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DineroBajaDoble: currency;
begin
try
result := Cursor.GetDineroBajaDoble;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DineroBajaSimple: currency;
begin
try
result := Cursor.GetDineroBajaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Dobson10: integer;
begin
try
result := Cursor.GetDobson10;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Dobson100: integer;
begin
try
result := Cursor.GetDobson100;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Dobson130: integer;
begin
try
result := Cursor.GetDobson130;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Dobson40: integer;
begin
try
result := Cursor.GetDobson40;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Dobson70: integer;
begin
try
result := Cursor.GetDobson70;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonAlto10: integer;
begin
try
result := Cursor.GetDobsonAlto10;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonAlto100: integer;
begin
try
result := Cursor.GetDobsonAlto100;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonAlto130: integer;
begin
try
result := Cursor.GetDobsonAlto130;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonAlto40: integer;
begin
try
result := Cursor.GetDobsonAlto40;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonAlto70: integer;
begin
try
result := Cursor.GetDobsonAlto40;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonBajo10: integer;
begin
try
result := Cursor.GetDobsonBajo10;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonBajo100: integer;
begin
try
result := Cursor.GetDobsonBajo100;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonBajo130: integer;
begin
try
result := Cursor.GetDobsonBajo130;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonBajo40: integer;
begin
try
result := Cursor.GetDobsonBajo40;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonBajo70: integer;
begin
try
result := Cursor.GetDobsonBajo70;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Maximo: currency;
begin
try
result := Cursor.GetMaximo;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.MaximoPrevisto: currency;
begin
try
result := Cursor.GetMaximoPrevisto;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.MaximoPrevistoAprox: single;
begin
try
result := Cursor.GetMaximoPrevistoAprox;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.MaximoSePrevino: currency;
begin
try
result := Cursor.GetMaximoSePrevino;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Media200: currency;
begin
try
result := Cursor.GetMedia200;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Mensaje: TMensaje;
begin
try
result := TScriptDatos(FScriptObject).Mensaje;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := nil;
end;
end;
end;
function TDatos.Minimo: currency;
begin
try
result := Cursor.GetMinimo;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.MinimoPrevisto: currency;
begin
try
result := Cursor.GetMinimoPrevisto;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.MinimoPrevistoAprox: single;
begin
try
result := Cursor.GetMinimoPrevistoAprox;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.MinimoSePrevino: currency;
begin
try
result := Cursor.GetMinimoSePrevino;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonNivelActual: integer;
var nivel: string;
begin
try
nivel := Cursor.GetNivelActual;
if nivel = 'A' then
result := 10
else
if nivel = '' then
result := -1
else
result := StrToInt(nivel);
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonNivelBaja: integer;
var nivel: string;
begin
try
nivel := Cursor.GetNivelBaja;
if nivel = 'A' then
result := 10
else
if nivel = '' then
result := -1
else
result := StrToInt(nivel);
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.DobsonNivelSube: integer;
var nivel: string;
begin
try
nivel := Cursor.GetNivelSube;
if nivel = 'A' then
result := 10
else
if nivel = '' then
result := -1
else
result := StrToInt(nivel);
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.GetIDSesion: integer;
begin
result := Cursor.OIDSesion;
end;
function TDatos.GetIDValor: integer;
begin
result := Cursor.OIDValor;
end;
function TDatos.GetSesionNum(Index: Integer): TDatos;
var i, datosI: integer;
scriptDatos: TScriptDatos;
sI: string;
verticalCache: boolean;
function FindIndexIDSesion: integer;
var i, num, OIDSesion: integer;
begin
num := Length(Sesiones) - 1;
OIDSesion := IDSesion;
for i := 0 to num do begin
if Sesiones[i] = OIDSesion then begin
result := i;
Exit;
end;
end;
// raise ESesionNotFound.Create(Format(SESION_NOT_FOUND, [OIDSesion]));
result := -1;
end;
begin
if Length(Sesiones) = 0 then
InitializeSesiones;
i := FindIndexIDSesion - Index;
if i < 0 then begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := nil;
end
else begin
verticalCache := DataCacheFactory is TScriptDataCacheVerticalFactory;
sI := IntToStr(i);
if verticalCache then begin
datosI := DatosSesionNum.IndexOf(sI);
if datosI >= 0 then begin
scriptDatos := TScriptDatos(DatosSesionNum.Objects[datosI]);
result := TDatos(scriptDatos.FScriptInstance);
end
else begin
scriptDatos := TScriptDatos.Create(ScriptDatosEngine, verticalCache);
result := TDatos(scriptDatos.FScriptInstance);
// result := TDatos.Create(ScriptDatosEngine, DataCacheFactory);
result.SetIDValor(IDValor);
result.SetIDSesion(Sesiones[i]);
DatosSesionNum.AddObject(sI, scriptDatos);
end;
end
else begin
datosI := DatosToClean.IndexOf(sI);
if datosI >= 0 then begin
result := TDatos(DatosToClean.Objects[datosI]);
end
else begin
result := TDatos.Create(ScriptDatosEngine, DataCacheFactory);
DatosToClean.AddObject(sI, result);
result.SetIDValor(IDValor);
result.SetIDSesion(Sesiones[i]);
end;
end;
end;
end;
function TDatos.GetTipoSesion: TTipoSesion;
begin
result := TScriptDatos(FScriptObject).GetTipoSesion;
end;
function TDatos.IDCotizacion: integer;
begin
try
result := Cursor.GetIDCotizacion;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
procedure TDatos.InitializeSesiones;
var q: TIBSQL;
i: Integer;
field: TIBXSQLVAR;
begin
q := TIBSQL.Create(nil);
try
q.Database := BD.GetNewDatabase(q, scdDatos, BD.BDDatos);
q.SQL.Text := 'SELECT count(*) FROM SESION s, COTIZACION c where ' +
'(c.OR_SESION = s.OID_SESION) and (not c.CIERRE is null) and (c.OR_VALOR=:OID_VALOR)';
q.Params[0].AsInteger := IDValor;
ExecQuery(q, false);
SetLength(Sesiones, q.Fields[0].AsInteger);
q.Close;
q.SQL.Text := 'SELECT c.OR_SESION FROM SESION s, COTIZACION c where ' +
'(c.OR_SESION = s.OID_SESION) and (not c.CIERRE is null) and (c.OR_VALOR=:OID_VALOR) order by s.fecha';
q.Params[0].AsInteger := IDValor;
ExecQuery(q, true);
field := q.Fields[0];
i := 0;
while not q.EOF do begin
Sesiones[i] := field.AsInteger;
Inc(i);
q.Next;
end;
finally
q.Free;
end;
if DatosSesionNum = nil then
DatosSesionNum := TStringList.Create
else
ClearDatosSesionNum;
ClearDatosToClean;
end;
function TDatos.Papel: currency;
begin
try
result := Cursor.GetPapel;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PapelAlzaDoble: currency;
begin
try
result := Cursor.GetPapelAlzaDoble;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PapelAlzaSimple: currency;
begin
try
result := Cursor.GetPapelAlzaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PapelBajaDoble: currency;
begin
try
result := Cursor.GetPapelBajaDoble;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PapelBajaSimple: currency;
begin
try
result := Cursor.GetPapelBajaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PercentAlzaSimple: currency;
begin
try
result := Cursor.GetPercentAlzaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PercentBajaSimple: currency;
begin
try
result := Cursor.GetPercentBajaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PivotPoint: currency;
begin
try
result := Cursor.GetPivotPoint;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PivotPointR1: currency;
begin
try
result := Cursor.GetPivotPointR1;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PivotPointR2: currency;
begin
try
result := Cursor.GetPivotPointR2;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PivotPointR3: currency;
begin
try
result := Cursor.GetPivotPointR3;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PivotPointS1: currency;
begin
try
result := Cursor.GetPivotPointS1;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PivotPointS2: currency;
begin
try
result := Cursor.GetPivotPointS2;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PivotPointS3: currency;
begin
try
result := Cursor.GetPivotPointS3;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PotencialFractal: integer;
begin
try
result := Cursor.GetPotencialFractal;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PresionLateral: single;
begin
try
result := Cursor.GetPresionLateral;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PresionLateralAlzaDoble: single;
begin
try
result := Cursor.GetPresionLateralAlzaDoble;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PresionLateralAlzaSimple: single;
begin
try
result := Cursor.GetPresionLateralAlzaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PresionLateralBajaDoble: single;
begin
try
result := Cursor.GetPresionLateralBajaDoble;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PresionLateralBajaSimple: single;
begin
try
result := Cursor.GetPresionLateralBajaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PresionVertical: single;
begin
try
result := Cursor.GetPresionVertical;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PresionVerticalAlzaDoble: single;
begin
try
result := Cursor.GetPresionVerticalAlzaDoble;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PresionVerticalAlzaSimple: single;
begin
try
result := Cursor.GetPresionVerticalAlzaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PresionVerticalBajaDoble: single;
begin
try
result := Cursor.GetPresionVerticalBajaDoble;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.PresionVerticalBajaSimple: single;
begin
try
result := Cursor.GetPresionVerticalBajaSimple;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.RentabilidadAbierta: single;
begin
try
result := Cursor.GetRentabilidadAbierta;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Riesgo: single;
begin
try
result := Cursor.GetRiesgo;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Rsi14: integer;
begin
try
result := Cursor.GetRsi14;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Rsi140: integer;
begin
try
result := Cursor.GetRsi140;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
procedure TDatos.SetIDSesion(const Value: integer);
begin
{ if DatosSesionNum <> nil then
ClearDatosSesionNum;}
Cursor.OIDSesion := Value;
end;
procedure TDatos.SetIDValor(const Value: integer);
begin
if Cursor.OIDValor <> Value then
SetLength(Sesiones, 0);
Cursor.OIDValor := Value;
end;
procedure TDatos.SetTipoSesion(const Value: TTipoSesion);
begin
end;
function TDatos.Stop: currency;
begin
try
result := Cursor.GetStop;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Posicionado: currency;
begin
try
result := Cursor.GetPosicionado;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Variabilidad: single;
begin
try
result := Cursor.GetVariabilidad;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Variacion: single;
begin
try
result := Cursor.GetVariacion;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Volatilidad: single;
begin
try
result := Cursor.GetVolatilidad;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Volumen: integer;
begin
try
result := Cursor.GetVolumen;
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := 0;
end;
end;
end;
function TDatos.Zona: TZona;
var z: string;
begin
try
z := Cursor.GetZona;
if z = '' then
result := zSinZona
else
result := TZona(StrToInt(z));
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := zSinZona;
end;
end;
end;
function TDatos.ZonaAlzaDoble: TZona;
var z: string;
begin
try
z := Cursor.GetZonaAlzaDoble;
if z = '' then
result := zSinZona
else
result := TZona(StrToInt(z));
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := zSinZona;
end;
end;
end;
function TDatos.ZonaAlzaSimple: TZona;
var z: string;
begin
try
z := Cursor.GetZonaAlzaSimple;
if z = '' then
result := zSinZona
else
result := TZona(StrToInt(z));
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := zSinZona;
end;
end;
end;
function TDatos.ZonaBajaDoble: TZona;
var z: string;
begin
try
z := Cursor.GetZonaBajaDoble;
if z = '' then
result := zSinZona
else
result := TZona(StrToInt(z));
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := zSinZona;
end;
end;
end;
function TDatos.ZonaBajaSimple: TZona;
var z: string;
begin
try
z := Cursor.GetZonaBajaSimple;
if z = '' then
result := zSinZona
else
result := TZona(StrToInt(z));
except
on e: EDatoNoEncontrado do begin
TScriptDatosEngine(ScriptDatosEngine).OnEDatoNotFound;
result := zSinZona;
end;
end;
end;
initialization
RegisterEnumeration('TZona', TypeInfo(TZona));
RegisterEnumeration('TAmbienteIntradia', TypeInfo(TAmbienteIntradia));
RegisterEnumeration('TTipoSesion', TypeInfo(TTipoSesion));
end.
|
(*
Copyright (c) 2011, Stefan Glienke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of this library nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*)
unit DSharp.Testing.Verify;
interface
uses
DSharp.Core.Expressions,
TestFramework;
type
ShouldBe = record
public
class function AtLeast<T>(const Value: T): TBooleanExpression; static;
class function AtMost<T>(const Value: T): TBooleanExpression; static;
class function Between<T>(const LowValue, HighValue: T): TBooleanExpression; static;
class function EqualTo<T>(const Value: T): TBooleanExpression; static;
class function GreaterThan<T>(const Value: T): TBooleanExpression; static;
class function LessThan<T>(const Value: T): TBooleanExpression; static;
end;
Verify = record
private
class var FActual: IValueExpression;
public
class constructor Create;
class procedure That<T>(const Value: T; Expression: TBooleanExpression;
const Msg: string = ''); static;
class property Actual: IValueExpression read FActual;
end;
EExpectationFailure = ETestFailure;
const
CExpectationFailed = 'Expected: "%0:s" Actual: %1:s';
implementation
uses
DSharp.Core.Reflection,
Rtti;
{ ShouldBe }
class function ShouldBe.AtLeast<T>(const Value: T): TBooleanExpression;
begin
Result := TBooleanExpression.Create(TGreaterThanOrEqualExpression.Create(
Verify.Actual, TConstantExpression.Create(Value)));
end;
class function ShouldBe.AtMost<T>(const Value: T): TBooleanExpression;
begin
Result := TBooleanExpression.Create(TLessThanOrEqualExpression.Create(
Verify.Actual, TConstantExpression.Create(Value)));
end;
class function ShouldBe.Between<T>(const LowValue, HighValue: T): TBooleanExpression;
begin
Result := TBooleanExpression.Create(TGreaterThanOrEqualExpression.Create(
Verify.Actual, TConstantExpression.Create(LowValue))) and
TBooleanExpression.Create(TLessThanOrEqualExpression.Create(
Verify.Actual, TConstantExpression.Create(HighValue)));
end;
class function ShouldBe.EqualTo<T>(const Value: T): TBooleanExpression;
begin
Result := TBooleanExpression.Create(TEqualExpression.Create(
Verify.Actual, TConstantExpression.Create(Value)));
end;
class function ShouldBe.GreaterThan<T>(const Value: T): TBooleanExpression;
begin
Result := TBooleanExpression.Create(TGreaterThanExpression.Create(
Verify.Actual, TConstantExpression.Create(Value)));
end;
class function ShouldBe.LessThan<T>(const Value: T): TBooleanExpression;
begin
Result := TBooleanExpression.Create(TLessThanExpression.Create(
Verify.Actual, TConstantExpression.Create(Value)));
end;
{ Verify }
class constructor Verify.Create;
begin
FActual := TParameterExpression.Create('?');
end;
class procedure Verify.That<T>(const Value: T; Expression: TBooleanExpression;
const Msg: string);
begin
Actual.Value := TValue.From<T>(Value);
if not Expression.Execute.AsBoolean then
begin
if Msg <> '' then
begin
raise EExpectationFailure.CreateFmt(Msg + ' ' + CExpectationFailed, [
Expression.ToString, Actual.Value.ToString]);
end
else
begin
raise EExpectationFailure.CreateFmt(CExpectationFailed, [
Expression.ToString, Actual.Value.ToString]);
end;
end;
end;
end.
|
unit UtilList;
interface
uses Classes, JclVectors, JclAbstractContainers, SysUtils;
type
EValueNotFound = class(Exception)
private
FName: string;
public
property name: string read FName;
end;
TNameValueList = class abstract(TObject)
private
function GetCount: integer;
function GetName(const i: integer): string;
procedure SetName(const i: integer; const Value: string);
protected
names: TStringList;
function GetIndexName(const name: string): integer;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Clear; virtual;
property Count: integer read GetCount;
property Name[const i: integer]: string read GetName write SetName;
end;
TNameIntegerValueList = class(TNameValueList)
private
type
TIntegerVector = class(TJclIntegerVector)
end;
var
values: TIntegerVector;
function GetNameValue(const name: string): integer;
procedure SetNameValue(const name: string; const Value: integer);
function GetValue(const i: integer): integer;
procedure SetValue(const i: integer; const Value: integer);
public
property NameValue[const name: string]: integer read GetNameValue write SetNameValue;
property Value[const i: integer]: integer read GetValue write SetValue;
procedure Clear; override;
constructor Create; override;
destructor Destroy; override;
end;
TNameCurrencyValueList = class(TNameValueList)
private
type
TCurrencyVector = class(TJclExtendedVector)
end;
var values: TCurrencyVector;
function GetNameValue(const name: string): currency;
procedure SetNameValue(const name: string; const Value: currency);
function GetValue(const i: integer): currency;
procedure SetValue(const i: integer; const Value: currency);
public
property NameValue[const name: string]: currency read GetNameValue write SetNameValue;
property Value[const i: integer]: currency read GetValue write SetValue;
procedure Clear; override;
constructor Create; override;
destructor Destroy; override;
end;
TNameStringValueList = class(TNameValueList)
private
values: TStringList;
function GetNameValue(const name: string): string;
procedure SetNameValue(const name: string; const Value: string);
function GetValue(const i: integer): string;
procedure SetValue(const i: integer; Value: string);
public
property NameValue[const name: string]: string read GetNameValue write SetNameValue;
property Value[const i: integer]: string read GetValue write SetValue;
procedure Clear; override;
constructor Create; override;
destructor Destroy; override;
end;
implementation
const CAPACITY = 10;
{ TNameIntegerValueList }
procedure TNameIntegerValueList.Clear;
begin
inherited;
values.Clear;
end;
constructor TNameIntegerValueList.Create;
begin
inherited;
values := TIntegerVector.Create(CAPACITY);
end;
destructor TNameIntegerValueList.Destroy;
begin
values.Free;
inherited;
end;
function TNameIntegerValueList.GetValue(const i: integer): integer;
begin
result := values.Items[i];
end;
function TNameIntegerValueList.GetNameValue(const name: string): integer;
var i: integer;
begin
i := GetIndexName(name);
result := values.Items[i];
end;
procedure TNameIntegerValueList.SetValue(const i, Value: integer);
begin
values.Items[i] := Value;
end;
procedure TNameIntegerValueList.SetNameValue(const name: string;
const Value: integer);
begin
names.Add(name);
values.Add(value);
end;
{ TNameValueList }
procedure TNameValueList.Clear;
begin
names.Clear;
end;
constructor TNameValueList.Create;
begin
names := TStringList.Create;
names.Duplicates := dupError;
end;
destructor TNameValueList.Destroy;
begin
names.Free;
end;
function TNameValueList.GetCount: integer;
begin
result := names.Count;
end;
function TNameValueList.GetIndexName(const name: string): integer;
var e: EValueNotFound;
begin
result := names.IndexOf(name);
if result = 0 then begin
e := EValueNotFound.Create('Value not found');
e.FName := name;
raise e;
end;
end;
function TNameValueList.GetName(const i: integer): string;
begin
result := names[i];
end;
procedure TNameValueList.SetName(const i: integer; const Value: string);
begin
names[i] := Value;
end;
{ TNameCurrencyValueList }
procedure TNameCurrencyValueList.Clear;
begin
inherited;
TCurrencyVector(values).Clear;
end;
constructor TNameCurrencyValueList.Create;
begin
inherited;
values := TCurrencyVector.Create(CAPACITY);
end;
destructor TNameCurrencyValueList.Destroy;
begin
values.Free;
inherited;
end;
function TNameCurrencyValueList.GetNameValue(const name: string): currency;
var i: integer;
begin
i := GetIndexName(name);
result := values.Items[i];
end;
function TNameCurrencyValueList.GetValue(const i: integer): currency;
begin
result := values.Items[i];
end;
procedure TNameCurrencyValueList.SetNameValue(const name: string;
const Value: currency);
begin
names.Add(name);
values.Add(value);
end;
procedure TNameCurrencyValueList.SetValue(const i: integer; const Value: currency);
begin
values.Items[i] := Value;
end;
{ TNameStringValueList }
procedure TNameStringValueList.Clear;
begin
names.Clear;
values.Clear;
end;
constructor TNameStringValueList.Create;
begin
inherited;
values := TStringList.Create;
end;
destructor TNameStringValueList.Destroy;
begin
values.Free;
inherited;
end;
function TNameStringValueList.GetNameValue(const name: string): string;
var i: integer;
begin
i := GetIndexName(name);
result := values[i];
end;
function TNameStringValueList.GetValue(const i: integer): string;
begin
result := values[i];
end;
procedure TNameStringValueList.SetNameValue(const name, Value: string);
begin
names.Add(name);
values.Add(value);
end;
procedure TNameStringValueList.SetValue(const i: integer; Value: string);
begin
values[i] := Value;
end;
end.
|
unit StringInspectorSpecs;
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
// http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
// License for the specific language governing rights and limitations
// under the License.
//
// The Original Code is DUnitLite.
//
// The Initial Developer of the Original Code is Joe White.
// Portions created by Joe White are Copyright (C) 2007
// Joe White. All Rights Reserved.
//
// Contributor(s):
//
// Alternatively, the contents of this file may be used under the terms
// of the LGPL license (the "LGPL License"), in which case the
// provisions of LGPL License are applicable instead of those
// above. If you wish to allow use of your version of this file only
// under the terms of the LGPL License and not to allow others to use
// your version of this file under the MPL, indicate your decision by
// deleting the provisions above and replace them with the notice and
// other provisions required by the LGPL License. If you do not delete
// the provisions above, a recipient may use your version of this file
// under either the MPL or the LGPL License.
interface
uses
Constraints,
Specifications,
StringInspectors;
type
TStringInspectorSpecification = class(TRegisterableSpecification)
strict protected
procedure SpecifyThatInspecting(AStringToInspect: string;
SatisfiesCondition: IConstraint);
procedure SpecifyThatInspectingSubstring(AStringToInspect: string;
AStartIndex, ALength: Integer; SatisfiesCondition: IConstraint);
end;
StringInspectorSpec = class(TStringInspectorSpecification)
strict private
function Apostrophes(Count: Integer): string;
published
procedure SpecEmptyString;
procedure SpecSingleNormalCharacter;
procedure SpecMultipleNormalCharacters;
procedure SpecSingleLowAsciiCharacter;
procedure SpecMultipleLowAsciiCharacters;
procedure SpecSingleApostrophe;
procedure SpecMultipleApostrophes;
procedure SpecNormalCharactersThenLowAscii;
procedure SpecLowAsciiThenNormalCharacters;
procedure SpecLowAsciiThenApostrophe;
end;
StringInspectorSubstringSpec = class(TStringInspectorSpecification)
published
procedure SpecEntireString;
procedure SpecSkipFirstCharacter;
procedure SpecSkipLastCharacter;
procedure SpecMiddleOfString;
procedure SpecOffBeginningOfString;
procedure SpecOffEndOfString;
end;
implementation
{ TStringInspectorSpecification }
procedure TStringInspectorSpecification.SpecifyThatInspecting(
AStringToInspect: string; SatisfiesCondition: IConstraint);
begin
SpecifyThatInspectingSubstring(AStringToInspect, 1, Length(AStringToInspect),
SatisfiesCondition);
end;
procedure TStringInspectorSpecification.SpecifyThatInspectingSubstring(
AStringToInspect: string; AStartIndex, ALength: Integer;
SatisfiesCondition: IConstraint);
begin
Specify.That(TStringInspector.Inspect(AStringToInspect, AStartIndex, ALength),
SatisfiesCondition);
end;
{ TestStringInspector }
function StringInspectorSpec.Apostrophes(Count: Integer): string;
begin
Result := StringOfChar(Apostrophe, Count);
end;
procedure StringInspectorSpec.SpecEmptyString;
begin
SpecifyThatInspecting('', Should.Yield(Apostrophes(2)));
end;
procedure StringInspectorSpec.SpecLowAsciiThenApostrophe;
begin
SpecifyThatInspecting(#9 + Apostrophe, Should.Yield('#9' + Apostrophes(4)));
end;
procedure StringInspectorSpec.SpecLowAsciiThenNormalCharacters;
begin
SpecifyThatInspecting(#9'ab', Should.Yield('#9' + Apostrophe + 'ab' + Apostrophe));
end;
procedure StringInspectorSpec.SpecMultipleApostrophes;
begin
SpecifyThatInspecting(Apostrophes(2), Should.Yield(Apostrophes(6)));
end;
procedure StringInspectorSpec.SpecMultipleLowAsciiCharacters;
begin
SpecifyThatInspecting(#13#10, Should.Yield('#13#10'));
end;
procedure StringInspectorSpec.SpecMultipleNormalCharacters;
begin
SpecifyThatInspecting('ab', Should.Yield(Apostrophe + 'ab' + Apostrophe));
end;
procedure StringInspectorSpec.SpecNormalCharactersThenLowAscii;
begin
SpecifyThatInspecting('ab'#13#10, Should.Yield(Apostrophe + 'ab' + Apostrophe + '#13#10'));
end;
procedure StringInspectorSpec.SpecSingleApostrophe;
begin
SpecifyThatInspecting(Apostrophe, Should.Yield(Apostrophes(4)));
end;
procedure StringInspectorSpec.SpecSingleLowAsciiCharacter;
begin
SpecifyThatInspecting(#0, Should.Yield('#0'));
end;
procedure StringInspectorSpec.SpecSingleNormalCharacter;
begin
SpecifyThatInspecting('a', Should.Yield(Apostrophe + 'a' + Apostrophe));
end;
{ StringInspectorSubstringSpec }
procedure StringInspectorSubstringSpec.SpecEntireString;
begin
SpecifyThatInspectingSubstring('abc', 1, 3, Should.Yield('''abc'''));
end;
procedure StringInspectorSubstringSpec.SpecMiddleOfString;
begin
SpecifyThatInspectingSubstring('abc', 2, 1, Should.Yield('...''b''...'));
end;
procedure StringInspectorSubstringSpec.SpecOffBeginningOfString;
begin
SpecifyThatInspectingSubstring('abc', 0, 2, Should.Yield('''ab''...'));
end;
procedure StringInspectorSubstringSpec.SpecOffEndOfString;
begin
SpecifyThatInspectingSubstring('abc', 2, 99, Should.Yield('...''bc'''));
end;
procedure StringInspectorSubstringSpec.SpecSkipFirstCharacter;
begin
SpecifyThatInspectingSubstring('abc', 2, 2, Should.Yield('...''bc'''));
end;
procedure StringInspectorSubstringSpec.SpecSkipLastCharacter;
begin
SpecifyThatInspectingSubstring('abc', 1, 2, Should.Yield('''ab''...'));
end;
initialization
StringInspectorSpec.Register;
StringInspectorSubstringSpec.Register;
end.
|
unit CashFactory;
interface
uses CashInterface;
type
TCashFactory = class
class function GetCash(CashType: string): ICash;
end;
implementation
uses Cash_FP3530T, Cash_FP3530T_NEW, Cash_FP320, Cash_IKC_E810T, Cash_IKC_C651T,
Cash_MINI_FP54, Cash_Emulation, Cash_VchasnoKasa, SysUtils;
{ TCashFactory }
class function TCashFactory.GetCash(CashType: string): ICash;
begin
if CashType = 'FP3530T' then
result := TCashFP3530T.Create;
if CashType = 'FP3530T_NEW' then
result := TCashFP3530T_NEW.Create;
if CashType = 'FP320' then
result := TCashFP320.Create;
if CashType = 'IKC-E810T' then
result := TCashIKC_E810T.Create;
if CashType = 'IKC-C651T' then
result := TCashIKC_C651T.Create;
if CashType = 'MINI_FP54' then
result := TCashMINI_FP54.Create;
if CashType = 'Emulation' then
result := TCashEmulation.Create;
if CashType = 'VchasnoKasa' then
result := TCashVchasnoKasa.Create;
if not Assigned(Result) then
raise Exception.Create('Не правильно указан тип кассы в Ini файле');
(*CashSamsung:=TCashSamsung.Create(GetDefaultValue_fromFile(ifDefaults,Self.ClassName,'ComPort','COM2:'));
with CashSamsung do begin
test:=GetDefaultValue_fromFile(ifDefaults,Self.ClassName,'Cashtest','1')='0';
DelayForSoldPC:=StrToInt(GetDefaultValue_fromFile(ifDefaults,Self.ClassName,'DelayForSoldPC','20'));
DelayBetweenLine:=StrToInt(GetDefaultValue_fromFile(ifDefaults,Self.ClassName,'DelayBetweenLine','500'));
SoldInEightReg:=SoldEightReg;
end;*)
end;
end.
|
{$MODESWITCH RESULT+}
{$GOTO ON}
(*************************************************************************
Cephes Math Library Release 2.8: June, 2000
Copyright by Stephen L. Moshier
Contributors:
* Sergey Bochkanov (ALGLIB project). Translation from C to
pseudocode.
See subroutines comments for additional copyrights.
>>> SOURCE LICENSE >>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation (www.fsf.org); either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************)
unit igammaf;
interface
uses Math, Sysutils, Ap, gammafunc, normaldistr;
function IncompleteGamma(a : Double; x : Double):Double;
function IncompleteGammaC(a : Double; x : Double):Double;
function InvIncompleteGammaC(a : Double; y0 : Double):Double;
implementation
(*************************************************************************
Incomplete gamma integral
The function is defined by
x
-
1 | | -t a-1
igam(a,x) = ----- | e t dt.
- | |
| (a) -
0
In this implementation both arguments must be positive.
The integral is evaluated by either a power series or
continued fraction expansion, depending on the relative
values of a and x.
ACCURACY:
Relative error:
arithmetic domain # trials peak rms
IEEE 0,30 200000 3.6e-14 2.9e-15
IEEE 0,100 300000 9.9e-14 1.5e-14
Cephes Math Library Release 2.8: June, 2000
Copyright 1985, 1987, 2000 by Stephen L. Moshier
*************************************************************************)
function IncompleteGamma(a : Double; x : Double):Double;
var
IGammaEpsilon : Double;
ans : Double;
ax : Double;
c : Double;
r : Double;
Tmp : Double;
begin
IGammaEpsilon := Double(0.000000000000001);
if AP_FP_Less_Eq(x,0) or AP_FP_Less_Eq(a,0) then
begin
Result := 0;
Exit;
end;
if AP_FP_Greater(x,1) and AP_FP_Greater(x,a) then
begin
Result := 1-IncompleteGammaC(a, x);
Exit;
end;
ax := a*Ln(x)-x-LnGamma(a, Tmp);
if AP_FP_Less(ax,-Double(709.78271289338399)) then
begin
Result := 0;
Exit;
end;
ax := Exp(ax);
r := a;
c := 1;
ans := 1;
repeat
r := r+1;
c := c*x/r;
ans := ans+c;
until AP_FP_Less_Eq(c/ans,IGammaEpsilon);
Result := ans*ax/a;
end;
(*************************************************************************
Complemented incomplete gamma integral
The function is defined by
igamc(a,x) = 1 - igam(a,x)
inf.
-
1 | | -t a-1
= ----- | e t dt.
- | |
| (a) -
x
In this implementation both arguments must be positive.
The integral is evaluated by either a power series or
continued fraction expansion, depending on the relative
values of a and x.
ACCURACY:
Tested at random a, x.
a x Relative error:
arithmetic domain domain # trials peak rms
IEEE 0.5,100 0,100 200000 1.9e-14 1.7e-15
IEEE 0.01,0.5 0,100 200000 1.4e-13 1.6e-15
Cephes Math Library Release 2.8: June, 2000
Copyright 1985, 1987, 2000 by Stephen L. Moshier
*************************************************************************)
function IncompleteGammaC(a : Double; x : Double):Double;
var
IGammaEpsilon : Double;
IGammaBigNumber : Double;
IGammaBigNumberInv : Double;
ans : Double;
ax : Double;
c : Double;
yc : Double;
r : Double;
t : Double;
y : Double;
z : Double;
pk : Double;
pkm1 : Double;
pkm2 : Double;
qk : Double;
qkm1 : Double;
qkm2 : Double;
Tmp : Double;
begin
IGammaEpsilon := Double(0.000000000000001);
IGammaBigNumber := Double(4503599627370496.0);
IGammaBigNumberInv := Double(2.22044604925031308085)*Double(0.0000000000000001);
if AP_FP_Less_Eq(x,0) or AP_FP_Less_Eq(a,0) then
begin
Result := 1;
Exit;
end;
if AP_FP_Less(x,1) or AP_FP_Less(x,a) then
begin
Result := 1-IncompleteGamma(a, x);
Exit;
end;
ax := a*Ln(x)-x-LnGamma(a, Tmp);
if AP_FP_Less(ax,-Double(709.78271289338399)) then
begin
Result := 0;
Exit;
end;
ax := Exp(ax);
y := 1-a;
z := x+y+1;
c := 0;
pkm2 := 1;
qkm2 := x;
pkm1 := x+1;
qkm1 := z*x;
ans := pkm1/qkm1;
repeat
c := c+1;
y := y+1;
z := z+2;
yc := y*c;
pk := pkm1*z-pkm2*yc;
qk := qkm1*z-qkm2*yc;
if AP_FP_Neq(qk,0) then
begin
r := pk/qk;
t := AbsReal((ans-r)/r);
ans := r;
end
else
begin
t := 1;
end;
pkm2 := pkm1;
pkm1 := pk;
qkm2 := qkm1;
qkm1 := qk;
if AP_FP_Greater(AbsReal(pk),IGammaBigNumber) then
begin
pkm2 := pkm2*IGammaBigNumberInv;
pkm1 := pkm1*IGammaBigNumberInv;
qkm2 := qkm2*IGammaBigNumberInv;
qkm1 := qkm1*IGammaBigNumberInv;
end;
until AP_FP_Less_Eq(t,IGammaEpsilon);
Result := ans*ax;
end;
(*************************************************************************
Inverse of complemented imcomplete gamma integral
Given p, the function finds x such that
igamc( a, x ) = p.
Starting with the approximate value
3
x = a t
where
t = 1 - d - ndtri(p) sqrt(d)
and
d = 1/9a,
the routine performs up to 10 Newton iterations to find the
root of igamc(a,x) - p = 0.
ACCURACY:
Tested at random a, p in the intervals indicated.
a p Relative error:
arithmetic domain domain # trials peak rms
IEEE 0.5,100 0,0.5 100000 1.0e-14 1.7e-15
IEEE 0.01,0.5 0,0.5 100000 9.0e-14 3.4e-15
IEEE 0.5,10000 0,0.5 20000 2.3e-13 3.8e-14
Cephes Math Library Release 2.8: June, 2000
Copyright 1984, 1987, 1995, 2000 by Stephen L. Moshier
*************************************************************************)
function InvIncompleteGammaC(a : Double; y0 : Double):Double;
var
IGammaEpsilon : Double;
IInvGammaBigNumber : Double;
x0 : Double;
x1 : Double;
x : Double;
yl : Double;
yh : Double;
y : Double;
d : Double;
lgm : Double;
dithresh : Double;
i : AlglibInteger;
dir : AlglibInteger;
Tmp : Double;
begin
IGammaEpsilon := Double(0.000000000000001);
IInvGammaBigNumber := Double(4503599627370496.0);
x0 := IInvGammaBigNumber;
yl := 0;
x1 := 0;
yh := 1;
dithresh := 5*IGammaEpsilon;
d := 1/(9*a);
y := 1-d-InvNormalDistribution(y0)*Sqrt(d);
x := a*y*y*y;
lgm := LnGamma(a, Tmp);
i := 0;
while i<10 do
begin
if AP_FP_Greater(x,x0) or AP_FP_Less(x,x1) then
begin
d := Double(0.0625);
Break;
end;
y := IncompleteGammaC(a, x);
if AP_FP_Less(y,yl) or AP_FP_Greater(y,yh) then
begin
d := Double(0.0625);
Break;
end;
if AP_FP_Less(y,y0) then
begin
x0 := x;
yl := y;
end
else
begin
x1 := x;
yh := y;
end;
d := (a-1)*Ln(x)-x-lgm;
if AP_FP_Less(d,-Double(709.78271289338399)) then
begin
d := Double(0.0625);
Break;
end;
d := -Exp(d);
d := (y-y0)/d;
if AP_FP_Less(AbsReal(d/x),IGammaEpsilon) then
begin
Result := x;
Exit;
end;
x := x-d;
i := i+1;
end;
if AP_FP_Eq(x0,IInvGammaBigNumber) then
begin
if AP_FP_Less_Eq(x,0) then
begin
x := 1;
end;
while AP_FP_Eq(x0,IInvGammaBigNumber) do
begin
x := (1+d)*x;
y := IncompleteGammaC(a, x);
if AP_FP_Less(y,y0) then
begin
x0 := x;
yl := y;
Break;
end;
d := d+d;
end;
end;
d := Double(0.5);
dir := 0;
i := 0;
while i<400 do
begin
x := x1+d*(x0-x1);
y := IncompleteGammaC(a, x);
lgm := (x0-x1)/(x1+x0);
if AP_FP_Less(AbsReal(lgm),dithresh) then
begin
Break;
end;
lgm := (y-y0)/y0;
if AP_FP_Less(AbsReal(lgm),dithresh) then
begin
Break;
end;
if AP_FP_Less_Eq(x,Double(0.0)) then
begin
Break;
end;
if AP_FP_Greater_Eq(y,y0) then
begin
x1 := x;
yh := y;
if dir<0 then
begin
dir := 0;
d := Double(0.5);
end
else
begin
if dir>1 then
begin
d := Double(0.5)*d+Double(0.5);
end
else
begin
d := (y0-yl)/(yh-yl);
end;
end;
dir := dir+1;
end
else
begin
x0 := x;
yl := y;
if dir>0 then
begin
dir := 0;
d := Double(0.5);
end
else
begin
if dir<-1 then
begin
d := Double(0.5)*d;
end
else
begin
d := (y0-yl)/(yh-yl);
end;
end;
dir := dir-1;
end;
i := i+1;
end;
Result := x;
end;
end. |
unit mhstring;
interface
procedure eliminlitera(var s: string;poz: longint);
{elimina un caracter dintr-un string la pozitia specificata}
procedure inserezlitera(var s: string;c: char;poz: longint);
{adauga un caracter intr-un string la pozitia specificata}
function nrtost0(nr: longint;nrd: byte): string;
{converteste un numar intreg intr-un string care are la inceput zerouri
atatea cate e nevoie ca sa ajunga la lungimea nrd}
function longtost(l: longint): string;
{converteste un longint intr-un string (hexazecimal)}
function wordtost(w: word): string;
{converteste un word intr-un string (hexazecimal)}
function bytetost(b: byte): string;
{converteste un byte intr-un string (hexazecimal)}
function downcase(c: char): char;
{daca c este 'A'..'Z', atunci il transforma in litera mica}
function upcase(c: char): char;
{daca c este 'a'..'a', atunci il transforma in litera mare}
function downstring(s: string): string;
{transforma tot string-ul in litere mici}
function upstring(s: string): string;
{transforma tot string-ul in litere mari}
function longtozerost(l: longint): string;
{transforma un longint in string cu zerouri in fata ('0000000021')}
function wordtozerost(w: word): string;
{transforma un word in string cu zerouri in fata ('00021','00003')}
function bytetozerost(b: byte): string;
{transforma un byte in string cu zerouri in fata ('001','002')}
function fullstring(nume,ext: string): string;
{transforma numele si extensia intr-un singur string (cu sau fara punct)}
implementation
procedure eliminlitera(var s: string;poz: longint);
var x: integer;
begin
if (poz<1)or(poz>length(s)) then exit;
for x:=poz to length(s)-1 do
s[x]:=s[x+1];
s[0]:=chr(length(s)-1)
end;
procedure inserezlitera(var s: string;c: char;poz: longint);
var x: integer;
begin
if (poz<1)or(poz>length(s)+1)or(length(s)>=sizeof(s)) then exit;
for x:=length(s) downto poz do
s[x+1]:=s[x];
s[poz]:=c;
s[0]:=chr(length(s)+1)
end;
function nrtost0(nr: longint;nrd: byte): string;
var st: string;
x: integer;
begin
str(nr:nrd,st);
for x:=1 to length(st) do
if st[x]=' ' then st[x]:='0';
nrtost0:=st;
end;
function longtost(l: longint): string;
const hexchars: array[0..$F]of char='0123456789ABCDEF';
begin
longtost[1]:=hexchars[hi(l shr 16) shr 4];
longtost[2]:=hexchars[hi(l shr 16) and $F];
longtost[3]:=hexchars[lo(l shr 16) shr 4];
longtost[4]:=hexchars[lo(l shr 16) and $F];
longtost[5]:=hexchars[hi(l shr 0) shr 4];
longtost[6]:=hexchars[hi(l shr 0) and $F];
longtost[7]:=hexchars[lo(l shr 0) shr 4];
longtost[8]:=hexchars[lo(l shr 0) and $F];
longtost[0]:=#8;
end;
function wordtost(w: word): string;
const hexchars: array[0..$F]of char='0123456789ABCDEF';
begin
wordtost[1]:=hexchars[hi(w)shr 4];
wordtost[2]:=hexchars[hi(w)and $F];
wordtost[3]:=hexchars[lo(w)shr 4];
wordtost[4]:=hexchars[lo(w)and $F];
wordtost[0]:=#4;
end;
function bytetost(b: byte): string;
const hexchars: array[0..$F]of char='0123456789ABCDEF';
begin
bytetost[1]:=hexchars[b shr 4];
bytetost[2]:=hexchars[b and $F];
bytetost[0]:=#2;
end;
function downcase(c: char): char;
var x: integer;
begin
x:=ord(c);
if (x<ord('A'))or(x>ord('Z')) then downcase:=c else
begin
x:=x-ord('A');
downcase:=chr(x+ord('a'));
end;
end;
function upcase(c: char): char;
var x: integer;
begin
x:=ord(c);
if (x<ord('a'))or(x>ord('z')) then upcase:=c else
begin
x:=x-ord('a');
upcase:=chr(x+ord('A'));
end;
end;
function downstring(s: string): string;
var x: integer;
begin
for x:=1 to length(s) do
downstring[x]:=downcase(s[x]);
downstring[0]:=s[0];
end;
function upstring(s: string): string;
var x: integer;
begin
for x:=1 to length(s) do
upstring[x]:=upcase(s[x]);
upstring[0]:=s[0];
end;
function longtozerost(l: longint): string;
var s: string[10];
x: byte;
begin
str(l:10,s);
for x:=1 to 10 do
if s[x]=' ' then s[x]:='0';
longtozerost:=s;
end;
function wordtozerost(w: word): string;
var s: string[5];
x: byte;
begin
str(w:5,s);
for x:=1 to 5 do
if s[x]=' ' then s[x]:='0';
wordtozerost:=s;
end;
function bytetozerost(b: byte): string;
var s: string[3];
x: byte;
begin
str(b:3,s);
for x:=1 to 3 do
if s[x]=' ' then s[x]:='0';
bytetozerost:=s;
end;
function fullstring(nume,ext: string): string;
begin
if ext<>'' then nume:=nume+'.'+ext;
fullstring:=nume;
end;
begin
end. |
unit UALLJAScore;
interface
uses
Windows, SysUtils, Classes, Graphics, Controls, Forms,
UBasicScore, Grids, StdCtrls, ExtCtrls, Buttons, Math,
UzLogConst, UzLogGlobal, UzLogQSO, Vcl.Menus;
type
TBandPointArray = array[b19..HiBand] of Integer;
TALLJAScore = class(TBasicScore)
Grid: TStringGrid;
procedure FormShow(Sender: TObject);
procedure GridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
protected
function GetFontSize(): Integer; override;
procedure SetFontSize(v: Integer); override;
private
{ Private declarations }
FLowBand: TBand;
FHighBand: TBand;
FPointTable: TBandPointArray;
function GetPointTable(Index: TBand): Integer;
procedure SetPointTable(Index: TBand; v: Integer);
public
{ Public declarations }
constructor Create(AOwner: TComponent; LowBand: TBand; HighBand: TBand); reintroduce;
procedure AddNoUpdate(var aQSO : TQSO); override;
procedure UpdateData; override;
procedure Reset; override;
procedure Add(var aQSO : TQSO); override;
property FontSize: Integer read GetFontSize write SetFontSize;
property PointTable[Index: TBand]: Integer read GetPointTable write SetPointTable;
end;
implementation
{$R *.DFM}
constructor TALLJAScore.Create(AOwner: TComponent; LowBand: TBand; HighBand: TBand);
begin
Inherited Create(AOwner);
FLowBand := LowBand;
FHighBand := HighBand;
FPointTable[b19] := 1;
FPointTable[b35] := 1;
FPointTable[b7] := 1;
FPointTable[b10] := 1;
FPointTable[b14] := 1;
FPointTable[b18] := 1;
FPointTable[b21] := 1;
FPointTable[b24] := 1;
FPointTable[b28] := 1;
FPointTable[b50] := 1;
FPointTable[b144] := 1;
FPointTable[b430] := 1;
FPointTable[b1200] := 1;
FPointTable[b2400] := 1;
FPointTable[b5600] := 1;
FPointTable[b10g] := 1;
end;
procedure TALLJAScore.FormShow(Sender: TObject);
begin
inherited;
Button1.SetFocus;
Grid.Col := 1;
Grid.Row := 1;
end;
procedure TALLJAScore.GridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
begin
inherited;
Draw_GridCell(TStringGrid(Sender), ACol, ARow, Rect);
end;
procedure TALLJAScore.AddNoUpdate(var aQSO: TQSO);
var
band: TBand;
begin
inherited;
if aQSO.Dupe then begin
Exit;
end;
band := aQSO.band;
aQSO.points := FPointTable[band];
Inc(Points[band], aQSO.points);
end;
procedure TALLJAScore.UpdateData;
var
band: TBand;
TotQSO, TotPoints, TotMulti: Integer;
row: Integer;
w: Integer;
strScore: string;
DispColCount: Integer;
strExtraInfo: string;
begin
Inherited;
TotQSO := 0;
TotPoints := 0;
TotMulti := 0;
row := 1;
// 見出し行
Grid.Cells[0,0] := 'MHz';
Grid.Cells[1,0] := 'QSOs';
Grid.Cells[2,0] := 'Points';
Grid.Cells[3,0] := 'Multi';
Grid.Cells[4,0] := EXTRAINFO_CAPTION[FExtraInfo];
if ShowCWRatio then begin
Grid.Cells[5,0] := 'CW Q''s';
Grid.Cells[6,0] := 'CW %';
DispColCount := 7;
end
else begin
Grid.Cells[5,0] := '';
Grid.Cells[6,0] := '';
DispColCount := 5;
end;
// バンド別スコア行
for band := FLowBand to FHighBand do begin
// WARC除外
if IsWARC(band) = True then begin
Continue;
end;
// QRVできないバンドは除外
if dmZlogGlobal.Settings._activebands[band] = False then begin
Continue;
end;
TotPoints := TotPoints + Points[band];
TotMulti := TotMulti + Multi[band];
TotQSO := TotQSO + QSO[band];
// バンド別スコア
Grid.Cells[0, row] := '*' + MHzString[band];
Grid.Cells[1, row] := IntToStr3(QSO[band]);
Grid.Cells[2, row] := IntToStr3(Points[band]);
Grid.Cells[3, row] := IntToStr3(Multi[band]);
// Multi率
strExtraInfo := '';
case FExtraInfo of
0: begin
if QSO[band] > 0 then begin
strExtraInfo := FloatToStrF((Multi[band] / QSO[band] * 100), ffFixed, 1000, 1);
end;
end;
1: begin
if Multi[band] > 0 then begin
strExtraInfo := FloatToStrF((Points[band] / Multi[band]), ffFixed, 1000, 1);
end;
end;
2: begin
if QSO[band] > 0 then begin
strExtraInfo := FloatToStrF((Points[band] * Multi[band] / QSO[band]), ffFixed, 1000, 1);
end;
end;
end;
Grid.Cells[4, row] := strExtraInfo;
// CW率
if ShowCWRatio then begin
Grid.Cells[5, row] := IntToStr3(CWQSO[band]);
if QSO[band] > 0 then begin
Grid.Cells[6, row] := FloatToStrF(100 * (CWQSO[band] / QSO[band]), ffFixed, 1000, 1);
end
else begin
Grid.Cells[6, row] := '-';
end;
end
else begin
Grid.Cells[5, row] := '';
Grid.Cells[6, row] := '';
end;
Inc(row);
end;
// 合計行
Grid.Cells[0, row] := 'Total';
Grid.Cells[1, row] := IntToStr3(TotQSO);
Grid.Cells[2, row] := IntToStr3(TotPoints);
Grid.Cells[3, row] := IntToStr3(TotMulti);
// Multi率
strExtraInfo := '';
case FExtraInfo of
0: begin
if TotQSO > 0 then begin
strExtraInfo := FloatToStrF((TotMulti / TotQSO * 100), ffFixed, 1000, 1);
end;
end;
1: begin
if TotMulti > 0 then begin
strExtraInfo := FloatToStrF((TotPoints / TotMulti), ffFixed, 1000, 1);
end;
end;
2: begin
if TotQSO > 0 then begin
strExtraInfo := FloatToStrF((TotPoints * TotMulti / TotQSO), ffFixed, 1000, 1);
end;
end;
end;
Grid.Cells[4, row] := strExtraInfo;
// CW率
if ShowCWRatio then begin
Grid.Cells[5, row] := IntToStr3(TotalCWQSOs);
if TotPoints > 0 then begin
Grid.Cells[6, row] := FloatToStrF(100 * (TotalCWQSOs / TotalQSOs), ffFixed, 1000, 1);
end
else begin
Grid.Cells[6, row] := '-';
end;
end
else begin
Grid.Cells[5, row] := '';
Grid.Cells[6, row] := '';
end;
Inc(row);
// スコア行
strScore := IntToStr3(TotPoints * TotMulti);
Grid.Cells[0, row] := 'Score';
Grid.Cells[1, row] := '';
Grid.Cells[2, row] := '';
Grid.Cells[3, row] := strScore;
Grid.Cells[4, row] := '';
Grid.Cells[5, row] := '';
Grid.Cells[6, row] := '';
Inc(row);
// 行数をセット
Grid.RowCount := row;
// カラム幅をセット
w := Grid.Canvas.TextWidth('9');
Grid.ColWidths[0] := w * 6;
Grid.ColWidths[1] := w * 7;
Grid.ColWidths[2] := w * 7;
Grid.ColWidths[3] := w * Max(8, Length(strScore)+1);
Grid.ColWidths[4] := w * 7;
Grid.ColWidths[5] := w * 7;
Grid.ColWidths[6] := w * 7;
// グリッドサイズ調整
AdjustGridSize(Grid, DispColCount, Grid.RowCount);
end;
procedure TALLJAScore.Reset;
begin
inherited;
end;
procedure TALLJAScore.Add(var aQSO: TQSO);
begin
inherited;
end;
function TALLJAScore.GetFontSize(): Integer;
begin
Result := Grid.Font.Size;
end;
procedure TALLJAScore.SetFontSize(v: Integer);
begin
Inherited;
SetGridFontSize(Grid, v);
UpdateData();
end;
function TALLJAScore.GetPointTable(Index: TBand): Integer;
begin
Result := FPointTable[Index];
end;
procedure TALLJAScore.SetPointTable(Index: TBand; v: Integer);
begin
FPointTable[Index] := v;
end;
end.
|
{
mteElements
Component of mteFunctions for handling IwbElements.
See http://github.com/matortheeternal/mteFunctions
}
unit mteElements;
const
// VARIANT TYPES
varInteger = 3;
varDouble = 5;
varShortInt = 16;
varString = 256; { Pascal string }
varUString = 258; { Unicode string }
{ SEE http://stackoverflow.com/questions/24731098/ for more }
{****************************************************}
{ ELEMENT COMPARISON
Methods for comparing or evaluating elements.
- IsValue
- ElementMatches
- StructMatches
}
{****************************************************}
function IsValue(element: IInterface): Boolean;
var
dt: Integer;
begin
dt := DefType(element);
Result := (dt = dtString)
or (dt = dtLString)
or (dt = dtLenString)
or (dt = dtByteArray)
or (dt = dtInteger)
or (dt = dtFloat);
end;
function ElementMatches(element: IInterface; value: Variant): Boolean;
var
vt: Integer;
rec: IInterface;
begin
Result := False;
// raise exception if input element is not a value element
if not IsValue(element) then
raise Exception.Create('ElementMatches: Input element is not a value element');
vt := VarType(value);
case vt of
varInteger, varDouble, varShortInt:
Result := (value = GetNativeValue(element));
varString, varUString: begin
Result := (value = GetEditValue(element));
// Check value matches linked EDID - EditorID or NAME - Base
if not Result then try
rec := LinksTo(element);
// exit if element doesn't link to anything
if not Assigned(rec) then
exit;
// else check EDID and NAME for match
if ElementExists(rec, 'EDID') then
Result := GetElementEditValues(rec, 'EDID') = value
else if ElementExists(rec, 'NAME') then
Result := GetElementEditValues(rec, 'NAME') = value;
except
on x: Exception do begin
// nothing
end;
end;
end;
end;
end;
function StructMatches(container, struct: IInterface; path: String; value: Variant): Boolean;
var
element: IInterface;
vt: Integer;
key: String;
begin
Result := false;
// raise exception if input element is not a struct element
if IsValue(element) then
raise Exception.Create('StructMatches: Input element is not a struct element');
vt := VarType(value);
// if path is empty, compare struct directly to value
if (path = '') then begin
// if value isn't a string, raise exception because comparison will fail
if (vt <> vtString) and (vt <> vtUString) then
raise Exception.Create(Format('StructMatches: Unable to compare value at path '+
'"%s" against variant of type %d', [Path(struct), vt]);
// get key for struct - use SortKey if container is sorted else use GetAllValues
if IsSorted(container) then
key := SortKey(struct)
else
key := GetAllValues(struct);
// Result is whether or not the key matches the value
Result := key = value;
end
// else get element at path
else begin
element := ElementByPath(struct, path);
// if the element holds a value, compare using ElementMatches
if IsValue(element) then
Result := ElementMatches(element, value)
// else compare structs by calling StructMatches again
else
Result := StructMatches(GetContainer(element), element, '', value);
end;
end;
{****************************************************}
{ TYPE HELPERS
Methods for converting xEdit types.
- etToString
- dtToString
- ctToString
- caToString
}
{****************************************************}
{
etToString:
Converst a TwbElementType to a string.
Example usage:
element := ElementByPath(e, 'KWDA');
AddMessage(etToString(ElementType(element)));
}
function etToString(et: TwbElementType): string;
begin
case Ord(et) of
Ord(etFile): Result := 'etFile';
Ord(etMainRecord): Result := 'etMainRecord';
Ord(etGroupRecord): Result := 'etGroupRecord';
Ord(etSubRecord): Result := 'etSubRecord';
Ord(etSubRecordStruct): Result := 'etSubRecordStruct';
Ord(etSubRecordArray): Result := 'etSubRecordArray';
Ord(etSubRecordUnion): Result := 'etSubRecordUnion';
Ord(etArray): Result := 'etArray';
Ord(etStruct): Result := 'etStruct';
Ord(etValue): Result := 'etValue';
Ord(etFlag): Result := 'etFlag';
Ord(etStringListTerminator): Result := 'etStringListTerminator';
Ord(etUnion): Result := 'etUnion';
end;
end;
{
dtToString:
Converts a TwbDefType to a string.
Example usage:
element := ElementByPath(e, 'KWDA');
AddMessage(dtToString(DefType(element)));
}
function dtToString(dt: TwbDefType): string;
begin
case Ord(dt) of
Ord(dtRecord): Result := 'dtRecord';
Ord(dtSubRecord): Result := 'dtSubRecord';
Ord(dtSubRecordArray): Result := 'dtSubRecordArray';
Ord(dtSubRecordStruct): Result := 'dtSubRecordStruct';
Ord(dtSubRecordUnion): Result := 'dtSubRecordUnion';
Ord(dtString): Result := 'dtString';
Ord(dtLString): Result := 'dtLString';
Ord(dtLenString): Result := 'dtLenString';
Ord(dtByteArray): Result := 'dtByteArray';
Ord(dtInteger): Result := 'dtInteger';
Ord(dtIntegerFormater): Result := 'dtIntegerFormatter';
Ord(dtFloat): Result := 'dtFloat';
Ord(dtArray): Result := 'dtArray';
Ord(dtStruct): Result := 'dtStruct';
Ord(dtUnion): Result := 'dtUnion';
Ord(dtEmpty): Result := 'dtEmpty';
end;
end;
{
ctToString:
Converts a TConflictThis to a string.
Example usage:
AddMessage(ctToString(ctNotDefined));
}
function ctToString(ct: TConflictThis): string;
begin
case Ord(ct) of
Ord(ctUnknown): Result := 'ctUnknown';
Ord(ctIgnored): Result := 'ctIgnored';
Ord(ctNotDefined): Result := 'ctNotDefined';
Ord(ctIdenticalToMaster): Result := 'ctIdenticalToMaster';
Ord(ctOnlyOne): Result := 'ctOnlyOne';
Ord(ctHiddenByModGroup): Result := 'ctHiddenByModGroup';
Ord(ctMaster): Result := 'ctMaster';
Ord(ctConflictBenign): Result := 'ctConflictBenign';
Ord(ctOverride): Result := 'ctOverride';
Ord(ctIdenticalToMasterWinsConflict): Result := 'ctIdenticalToMasterWinsConflict';
Ord(ctConflictWins): Result := 'ctConflictWins';
Ord(ctConflictLoses): Result := 'ctConflictLoses';
end;
end;
{
caToString:
Converts a TConflictAll to a string.
Example usage:
e := RecordByIndex(FileByIndex(0), 1);
AddMessage(caToString(ConflictAllForMainRecord(e)));
}
function caToString(ca: TConflictAll): string;
begin
case Ord(ca) of
Ord(caUnknown): Result := 'caUnknown';
Ord(caOnlyOne): Result := 'caOnlyOne';
Ord(caConflict): Result := 'caConflict';
Ord(caNoConflict): Result := 'caNoConflict';
Ord(caConflictBenign): Result := 'caConflictBenign';
Ord(caOverride): Result := 'caOverride';
Ord(caConflictCritical): Result := 'caConflictCritical';
end;
end;
{****************************************************}
{ ELEMENT HELPERS
Helper methods for dealing with arbitrary elements.
- ConflictThis
- ConflictAll
- ElementPath
- IndexedPath
- MoveElementToIndex
}
{****************************************************}
{
ConflictThis:
Gets the ConflictThis of a node or of a main record.
}
function ConflictThis(e: IInterface): TConflictThis;
var
et: TwbElementType;
begin
// raise exception if input element is not assigned
if not Assigned(e) then
raise Exception.Create('ConflictThis: Input element is not assigned');
et := ElementType(e);
case Ord(et) of
Ord(etFile): raise Exception.Create('ConflictThis: etFile does not have a ConflictThis');
Ord(etMainRecord): Result := ConflictThisForMainRecord(e);
Ord(etGroupRecord): raise Exception.Create('ConflictThis: etGroupRecord does not have a ConflictThis');
else Result := ConflictThisForNode(e);
end;
end;
{
ConflictAll:
Gets the ConflictAll of a node or of a main record.
}
function ConflictAll(e: IInterface): TConflictAll;
var
et: TwbElementType;
begin
// raise exception if input element is not assigned
if not Assigned(e) then
raise Exception.Create('ConflictAll: Input element is not assigned');
et := ElementType(e);
case Ord(et) of
Ord(etFile): raise Exception.Create('ConflictAll: etFile does not have a ConflictAll');
Ord(etMainRecord): Result := ConflictAllForMainRecord(e);
Ord(etGroupRecord): raise Exception.Create('ConflictAll: etGroupRecord does not have a ConflictAll');
else Result := ConflictAllForNode(e);
end;
end;
{
ElementPath:
Gets the path of an element.
Example usage:
element := ElementByPath(e, 'Model\MODL');
AddMessage(ElementPath(element)); //Model\MODL - Model Filename
}
function ElementPath(e: IInterface): string;
var
c: IInterface;
et: TwbElementType;
begin
// raise exception if user input an etFile, etMainRecord, or etGroupRecord
et := ElementType(e);
case Ord(et) of
Ord(etFile): raise Exception.Create('ElementPath: Cannot call ElementPath on a file');
Ord(etMainRecord): raise Exception.Create('ElementPath: Cannot call ElementPath on a main record');
Ord(etGroupRecord): raise Exception.Create('ElementPath: Cannot call ElementPath on a group record');
end;
// calculate element path
c := GetContainer(e);
while (ElementType(e) <> etMainRecord) do begin
// append to result
if Result <> '' then
Result := Name(e) + '\' + Result
else
Result := Name(e);
// recurse upwards
e := c;
c := GetContainer(e);
end;
end;
{
IndexedPath:
Gets the indexed path of an element.
Example usage:
element := ElementByIP(e, 'Conditions\[3]\CTDA - \Comparison Value');
AddMessage(IndexedPath(element)); //Conditions\[3]\CTDA - \Comparison Value
}
function IndexedPath(e: IInterface): string;
var
c: IInterface;
a: string;
et: TwbElementType;
begin
// raise exception if user input an etFile, etMainRecord, or etGroupRecord
et := ElementType(e);
case Ord(et) of
Ord(etFile): raise Exception.Create('IndexedPath: Cannot call IndexedPath on a file');
Ord(etMainRecord): raise Exception.Create('IndexedPath: Cannot call IndexedPath on a main record');
Ord(etGroupRecord): raise Exception.Create('IndexedPath: Cannot call IndexedPath on a group record');
end;
// calculate indexed path
c := GetContainer(e);
while (ElementType(e) <> etMainRecord) do begin
// do index if we're in an array, else do name
if ElementType(c) = etSubRecordArray then
a := '['+IntToStr(IndexOf(c, e))+']'
else
a := Name(e);
// append to result
if Result <> '' then
Result := a + '\' + Result
else
Result := a;
// recurse upwards
e := c;
c := GetContainer(e);
end;
end;
{
MoveElementToIndex:
Moves an element in an array to the specified index,
if possible.
Example usage:
element := ElementByIP(e, 'Effects\[1]');
MoveElementToIndex(element, 3); // moves element down twice
}
procedure MoveElementToIndex(e: IInterface; index: Integer);
var
container: IInterface;
currentIndex, newIndex: Integer;
et: TwbElementType;
begin
// raise exception if user input an etFile, etMainRecord, or etGroupRecord
et := ElementType(e);
case Ord(et) of
Ord(etFile): raise Exception.Create('MoveElementToIndex: Cannot call MoveElementToIndex on a file');
Ord(etMainRecord): raise Exception.Create('MoveElementToIndex: Cannot call MoveElementToIndex on a main record');
Ord(etGroupRecord): raise Exception.Create('MoveElementToIndex: Cannot call MoveElementToIndex on a group record');
end;
// move element
container := GetContainer(e);
currentIndex := IndexOf(container, e);
// move up if currentIndex < index
while (currentIndex > index) do begin
MoveUp(e);
newIndex := IndexOf(container, e);
if newIndex < currentIndex then
currentIndex := newIndex
else
break;
end;
// move down if currentIndex < index
while (currentIndex < index) do begin
MoveDown(e);
newIndex := IndexOf(container, e);
if newIndex > currentIndex then
currentIndex := newIndex
else
break;
end;
end;
{****************************************************}
{ ELEMENT GETTERS
Methods for getting elements.
- ElementByIP
- ebip
- ElementsByMIP
- ebmip
}
{****************************************************}
{
ElementByIP:
Element by Indexed Path
This is a function to help with getting at elements that are inside
lists. It allows you to use an "indexed path" to get at these elements
that would otherwise be inaccessible without multiple lines of code.
Example usage:
element0 := ElementByIP(e, 'Conditions\[0]\CTDA - \Function');
element1 := ElementByIP(e, 'Conditions\[1]\CTDA - \Function');
}
function ElementByIP(e: IInterface; ip: string): IInterface;
var
i, index: integer;
path: TStringList;
begin
// raise exception if input element is not assigned
if not Assigned(e) then
raise Exception.Create('ElementByIP: Input element not assigned');
// replace forward slashes with backslashes
ip := StringReplace(ip, '/', '\', [rfReplaceAll]);
// prepare path stringlist delimited by backslashes
path := TStringList.Create;
path.Delimiter := '\';
path.StrictDelimiter := true;
path.DelimitedText := ip;
// traverse path
for i := 0 to Pred(path.count) do begin
if Pos('[', path[i]) > 0 then begin
index := StrToInt(GetTextIn(path[i], '[', ']'));
e := ElementByIndex(e, index);
end
else
e := ElementByPath(e, path[i]);
end;
// set result
Result := e;
end;
function ebip(e: IInterface; ip: string): IInterface;
begin
Result := ElementByIP(e, ip);
end;
{
ElementsByMIP
This is a function that builds on ElementByIP by allowing the usage of the mult *
character as a placeholder representing any valid index. It returns through @lst
a list of all elements in @e that match the input path @ip.
Example usage:
lst := TList.Create;
ElementsByMIP(lst, e, 'Items\[*]\CNTO - Item\Item');
for i := 0 to Pred(lst.Count) do begin
AddMessage(GetEditValue(ObjectToElement(lst[i])));
end;
lst.Free;
}
procedure ElementsByMIP(var lst: TList; e: IInterface; ip: string);
var
xstr: string;
i, j, index: integer;
path: TStringList;
bMult: boolean;
begin
// replace forward slashes with backslashes
ip := StringReplace(ip, '/', '\', [rfReplaceAll]);
// prepare path stringlist delimited by backslashes
path := TStringList.Create;
path.Delimiter := '\';
path.StrictDelimiter := true;
path.DelimitedText := ip;
// traverse path
bMult := false;
for i := 0 to Pred(path.count) do begin
if Pos('[', path[i]) > 0 then begin
xstr := GetTextIn(path[i], '[', ']');
if xstr = '*' then begin
for j := 0 to Pred(ElementCount(e)) do
ElementsByMIP(lst, ElementByIndex(e, j), DelimitedTextBetween(path, i + 1, Pred(path.count)));
bMult := true;
break;
end
else
e := ElementByIndex(e, index);
end
else
e := ElementByPath(e, path[i]);
end;
if not bMult then lst.Add(TObject(e));
end;
procedure ebmip(var lst: TList; e: IInterface; ip: string);
begin
ElementByMIP(lst, e, ip);
end;
{****************************************************}
{ ELEMENT VALUE GETTERS AND SETTERS
Methods for getting and setting element values.
- SetListEditValues
- slev
- SetListNativeValues
- slnv
- GetElementListEditValues
- gelev
- GetElementListNativeValues
- gelnv
- SetElementListEditValues
- selev
- SetElementListNativeValues
- selnv
- GetElementEditValuesEx
- geevx
- GetElementNativeValuesEx
- genvx
- SetElementEditValuesEx
- seevx
- SetElementNativeValuesEx
- senvx
- GetAllValues
- gav
}
{****************************************************}
{
SetListEditValues:
Sets the values of elements in a list to values stored in a stringlist.
Example usage:
SetListEditValues(e, 'Additional Races', slAdditionalRaces);
}
procedure SetListEditValues(e: IInterface; ip: string; values: TStringList);
var
i: integer;
list, newelement: IInterface;
begin
// exit if values is empty
if values.Count = 0 then exit;
list := ElementByIP(e, ip);
// clear element list except for one element
While ElementCount(list) > 1 do
RemoveByIndex(list, 0, true);
// create elements and populate the list
for i := 0 to values.Count - 1 do begin
newelement := ElementAssign(list, HighInteger, nil, False);
try
SetEditValue(newelement, values[i]);
except on Exception do
Remove(newelement); // remove the invalid/failed element
end;
end;
Remove(ElementByIndex(list, 0));
end;
procedure slev(e: IInterface; ip: string; values: TStringList);
begin
SetListEditValues(e, ip, values);
end;
{
SetListNativeValues:
Sets the native values of elements in a list to the values stored in a Tlist.
Example usage:
SetListNativeValues(e, 'KWDA', lstKeywords);
}
procedure SetListNativeValues(e: IInterface; ip: string; values: TList);
var
i: integer;
list, newelement: IInterface;
begin
// exit if values is empty
if values.Count = 0 then exit;
list := ElementByIP(e, ip);
// clear element list except for one element
While ElementCount(list) > 1 do
RemoveByIndex(list, 0);
// set element[0] to values[0]
SetNativeValue(ElementByIndex(list, 0), values[0]);
// create elements for the rest of the list
for i := 1 to values.Count - 1 do begin
newelement := ElementAssign(list, HighInteger, nil, False);
SetNativeValue(newelement, values[i]);
end;
end;
procedure slnv(e: IInterface; ip: string; values: TList);
begin
SetListNativeValues(e, ip, values);
end;
{
GetElementListEditValues:
Uses GetEditValues on each element in a list of elements to
produce a stringlist of element edit values. Use with ElementsByMIP.
Example usage:
elements := TList.Create;
// setup an arrray in elements with ElementsByMIP
values := TStringList.Create;
GetElementListEditValues(values, elements);
}
procedure GetElementListEditValues(var values: TStringList; var elements: TList);
var
i: integer;
e: IInterface;
begin
for i := 0 to Pred(elements.Count) do begin
e := ObjectToElement(elements[i]);
if Assigned(e) then
values.Add(GetEditValue(e))
else
values.Add('');
end;
end;
procedure gelev(var values: TStringList; var elements: TList);
begin
GetElementListEditValues(values, elements);
end;
{
GetElementListNativeValues:
Uses GetNativeValues on each element in a list of elements to
produce a list of element native values. Use with ElementsByMIP.
Example usage:
elements := TList.Create;
// setup an arrray in elements with ElementsByMIP
values := TList.Create;
GetElementListNativeValues(values, elements);
}
procedure GetElementListNativeValues(var values: TList; var elements: TList);
var
i: integer;
e: IInterface;
begin
for i := 0 to Pred(elements.Count) do begin
e := ObjectToElement(elements[i]);
if Assigned(e) then
values.Add(TObject(GetNativeValue(e)))
else
values.Add(TObject(nil));
end;
end;
procedure gelnv(var values: TList; var elements: TList);
begin
GetElementListNativeValues(sl, elements);
end;
{
SetElementListEditValues:
Uses SetEditValue on each element in a list of elements to
Use with ElementsByMIP and GetElementListEditValues.
Example usage:
elements := TList.Create;
// setup an arrray in elements with ElementsByMIP
values := TStringList.Create;
GetElementListEditValues(values, elements);
values[0] := 'Test';
SetElementListEditValues(values, elements);
}
procedure SetElementListEditValues(var values: TStringList; var elements: TList);
var
i: Integer;
e: IInterface;
begin
for i := 0 to Pred(elements.Count) do begin
e := ObjectToElement(elements[i]);
if Assigned(e) then
SetEditValue(e, values[i]);
end;
end;
procedure selev(var values: TStringList; var elements: TList);
begin
SetElementListEditValues(values, elements);
end;
{
SetElementListNativeValues:
Uses SetNativeValue on each element in a list of elements to
Use with ElementsByMIP and GetElementListNativeValues.
Example usage:
elements := TList.Create;
// setup an arrray in elements with ElementsByMIP
values := TList.Create;
GetElementListNativeValues(values, elements);
values[0] := -20;
SetElementListNativeValues(values, elements);
}
procedure SetElementListNativeValues(var values: TList; var elements: TList);
var
i: Integer;
e: IInterface;
begin
for i := 0 to Pred(elements.Count) do begin
e := ObjectToElement(elements[i]);
if Assigned(e) then
SetNativeValue(e, values[i]);
end;
end;
procedure selnv(var values: TList; var elements: TList);
begin
SetElementListNativeValues(values, elements);
end;
{
GetElementEditValuesEx:
GetElementEditValues, extended with ElementByIP.
Example usage:
s1 := GetElementEditValuesEx(e, 'Conditions\[3]\CTDA - \Function');
s2 := GetElementEditValuesEx(e, 'KWDA\[2]');
}
function GetElementEditValuesEx(e: IInterface; ip: string): string;
begin
Result := GetEditValue(ElementByIP(e, ip));
end;
function geevx(e: IInterface; ip: string): string;
begin
Result := GetElementEditValuesEx(e, ip);
end;
{
GetElementNativeValuesEx:
GetElementNativeValues, extended with ElementByIP.
Example usage:
f1 := genv(e, 'KWDA\[3]');
f2 := genv(e, 'Armature\[2]');
}
function GetElementNativeValuesEx(e: IInterface; ip: string): variant;
begin
Result := GetNativeValue(ElementByIP(e, ip));
end;
function genvx(e: IInterface; ip: string): variant;
begin
Result := GetElementNativeValuesEx(e, ip);
end;
{
SetElementEditValuesEx:
SetElementEditValuesEx, extended with ElementByIP.
Example usage:
SetElementEditValuesEx(e, 'Conditions\[2]\CTDA - \Type', '10000000');
SetElementEditValuesEx(e, 'KWDA\[0]'),
}
procedure SetElementEditValuesEx(e: IInterface; ip: string; val: string);
begin
SetEditValue(ElementByIP(e, ip), val);
end;
procedure seevx(e: IInterface; ip: string; val: string);
begin
SetElementEditValuesEx(e, ip, val);
end;
{
SetElementNativeValuesEx:
SetElementNativeValues, extended with ElementByIP.
Example usage:
SetElementNativeValuesEx(e, 'KWDA\[1]', $0006C0EE); // $0006C0EE is ArmorHelmet keyword
}
procedure SetElementNativeValuesEx(e: IInterface; ip: string; val: Variant);
begin
SetNativeValue(ElementByIP(e, ip), val);
end;
procedure senvx(e: IInterface; ip: string; val: Variant);
begin
SetElementNativeValuesEx(e, ip, val);
end;
{
GetAllValues:
Returns a semicolon-separated string hash of an element's
value, and the value of all of its children.
Example usage:
AddMessage(GetAllValues(e));
}
function GetAllValues(e: IInterface): string;
var
i: integer;
begin
Result := GetEditValue(e);
for i := 0 to ElementCount(e) - 1 do
if (Result <> '') then Result := Result + ';' + GetAllValues(ElementByIndex(e, i))
else Result := GetAllValues(ElementByIndex(e, i));
end;
function gav(e: IInterface): string;
begin
Result := GetAllValues(e);
end;
{****************************************************}
{ VANILLA ALIASES
Aliases for vanilla xEdit scripting functions.
- ebn
- ebp
- ebi
- geev
- genv
- seev
- senv
}
{****************************************************}
{
ebn:
Alias for ElementByName.
}
function ebn(e: IInterface; n: string): IInterface;
begin
Result := ElementByName(e, n);
end;
{
ebp:
Alias for ElementByPath.
}
function ebp(e: IInterface; p: string): IInterface;
begin
Result := ElementByPath(e, p);
end;
{
ebi:
Alias for ElementByIndex.
}
function ebi(e: IInterface; i: integer): IInterface;
begin
Result := ElementByIndex(e, i);
end;
{
geev:
Alias for GetElementEditValues.
}
function geev(e: IInterface; path: string): string;
begin
Result := GetElementEditValues(e, path);
end;
{
genv:
Alias for GetElementNativeValues.
}
function genv(e: IInterface; path: string): Variant;
begin
Result := GetElementNativeValues(e, path);
end;
{
seev:
Alias for SetElementEditValues.
}
procedure seev(e: IInterface; path: string; value: string);
begin
SetElementEditValues(e, path, value);
end;
{
senv:
Alias for SetElementNativeValues.
}
procedure senv(e: IInterface; path: string; value: Variant);
begin
SetElementNativeValues(e, path, value);
end;
{****************************************************}
{ FLAG METHODS
Generic methods for handling flags.
List of functions:
- SetFlag
- GetFlag
- GetFlagOrdinal
- ToggleFlag
- GetEnabledFlags
}
{****************************************************}
procedure SetFlag(element: IInterface; index: Integer; state: boolean);
var
mask: Integer;
begin
mask := 1 shl index;
if state then
SetNativeValue(element, GetNativeValue(element) or mask)
else
SetNativeValue(element, GetNativeValue(element) and not mask);
end;
function GetFlag(element: IInterface; index: Integer): boolean;
var
mask: Integer;
begin
mask := 1 shl index;
Result := (GetNativeValue(element) and mask) > 0;
end;
function GetFlagOrdinal(element: IInterface; name: string): Integer;
var
i, iRestore: Integer;
flag: IInterface;
begin
Result := -1;
iRestore := GetNativeValue(element);
// set all flags on so we can find the user-specified flag
SetNativeValue(element, $FFFFFFFF);
for i := 0 to Pred(ElementCount(element)) do begin
flag := ElementByIndex(element, i);
if Name(flag) = name then begin
Result := i;
break;
end;
end;
// restore value
SetNativeValue(element, iRestore);
end;
procedure SetFlagByName(element: IInterface; name: string; state: boolean);
var
index: Integer;
begin
index := GetFlagOrdinal(element, name);
SetFlag(element, index, state);
end;
function GetFlagByName(element: IInterface; name: string): boolean;
var
index: Integer;
begin
index := GetFlagOrdinal(element, name);
Result := GetFlag(element, index);
end;
{****************************************************}
{ ARRAY VALUE METHODS
Generic methods for handling array value elements.
List of functions:
- HasArrayValue
- GetArrayValue
- AddArrayValue
- DeleteArrayValue
}
{****************************************************}
function HasArrayValue(a: IInterface; value: Variant): Boolean;
var
i: Integer;
element: IInterface;
begin
Result := false;
// throw exception if array is not given
if not Assigned(a) then
raise Exception.Create('HasArrayValue: Input array not assigned');
// throw exception if value is not given
if not Assigned(value) then
raise Exception.Create('HasArrayValue: Input value not assigned');
// loop through array elements
for i := 0 to Pred(ElementCount(a)) do begin
element := ElementByIndex(a, i);
// if element matches value, set result to true and break
if ElementMatches(element, value) then begin
Result := true;
Break;
end;
end;
end;
function GetArrayValue(a: IInterface; value: Variant): IInterface;
var
i: Integer;
element: IInterface;
begin
Result := nil;
// throw exception if array is not given
if not Assigned(a) then
raise Exception.Create('GetArrayValue: Input array not assigned');
// throw exception if value is not given
if not Assigned(value) then
raise Exception.Create('GetArrayValue: Input value not assigned');
// loop through array elements
for i := 0 to Pred(ElementCount(a)) do begin
element := ElementByIndex(a, i);
// if element matches value, set it to result and break
if ElementMatches(element, value) then begin
Result := element;
Break;
end;
end;
end;
function AddArrayValue(a: IInterface; value: Variant): IInterface;
var
i, vt: Integer;
begin
Result := nil;
// throw exception if array is not given
if not Assigned(a) then
raise Exception.Create('AddArrayValue: Input array not assigned');
// throw exception if value is not given
if not Assigned(value) then
raise Exception.Create('AddArrayValue: Input value not assigned');
// add the element to the array
Result := ElementAssign(a, HighInteger, nil, false);
// if assigned element is not a value element, remove it and raise an exception
if not IsValue(Result) then begin
Remove(Result);
Result := nil;
raise Exception.Create('AddArrayValue: Array does not support value elements');
end;
// set value to new element
vt := VarType(value);
case vt of
// native value if integer or floating point
varInteger, varDouble, varShortInt:
SetNativeValue(Result, value);
// edit value if string or unicode string
varString, varUString:
SetEditValue(Result, value);
end;
end;
procedure DeleteArrayValue(a: IInterface; value: Variant);
var
i: Integer;
element: IInterface;
begin
// throw exception if array is not given
if not Assigned(a) then
raise Exception.Create('DeleteArrayValue: Input array not assigned');
// throw exception if value is not given
if not Assigned(value) then
raise Exception.Create('DeleteArrayValue: Input value not assigned');
// loop through array elements
for i := Pred(ElementCount(a)) downto 0 do begin
element := ElementByIndex(a, i);
// if element matches value, delete it and break
if ElementMatches(element, value) then begin
RemoveElement(a, element);
Break;
end;
end;
end;
{****************************************************}
{ ARRAY STRUCT FUNCTIONS
Generic methods for handling array structs.
List of functions:
- HasArrayStruct
- GetArrayStruct
- AddArrayStruct
- DeleteArrayStruct
}
{****************************************************}
function HasArrayStruct(a: IInterface; path: String; value: Variant): Boolean;
var
i: Integer;
struct: IInterface;
begin
Result := false;
// loop through array elements
for i := 0 to Pred(ElementCount(a)) do begin
struct := ElementByIndex(a, i);
// if struct matches value, set result to true and break
if StructMatches(a, struct, path, value) then begin
Result := true;
Break;
end;
end;
end;
function GetArrayStruct(a: IInterface; path: String; value: Variant): IInterface;
var
i: Integer;
struct: IInterface;
begin
Result := nil;
// loop through array elements
for i := 0 to Pred(ElementCount(a)) do begin
struct := ElementByIndex(a, i);
// if struct matches value, set result to true and break
if StructMatches(a, struct, path, value) then begin
Result := struct;
Break;
end;
end;
end;
// TODO: Support setting value of added array struct
function AddArrayStruct(a: IInterface): IInterface;
begin
Result := nil;
// add the struct to the array
Result := ElementAssign(a, HighInteger, nil, false);
end;
procedure DeleteArrayStruct(a: IInterface; path: String; value: Variant);
var
i: Integer;
struct: IInterface;
begin
// loop through array elements
for i := Pred(ElementCount(a)) downto 0 do begin
struct := ElementByIndex(a, i);
// if struct matches value, set result to true and break
if StructMatches(a, struct, path, value) then begin
RemoveElement(a, struct);
Break;
end;
end;
end;
end. |
unit GraficoPositionLayer;
interface
uses GR32_Layers, Contnrs, Graphics, Windows, GR32, Grafico, Controls,
Classes, Syncobjs;
const
POSICION_INDEFINIDA: integer = low(integer);
type
MessageGraficoPositionChange = class(TMessageGrafico);
TGraficoPositionLayer = class;
TGraficoPositionLayer = class(TGraficoDatosLayer)
private
FPosition: integer;
FHelpPointSize: integer;
FHelpPointActive: boolean;
HelpPointActualSize: integer;
FColorPosition: TColor32;
FColorPositionText: TColor;
pintarCuadro: boolean;
FActive: boolean;
OldActive: Boolean;
FEnabled: boolean;
CanPaintActualPosition: boolean;
PositionBeforeZoom: integer;
isOnTick: boolean;
procedure SetColorPosition(const Value: TColor);
function GetPointRect(const x,y: integer; const HelpPointActual: boolean): TRect;
procedure SetHelpPointActive(const Value: boolean);
procedure SetPosition(const Value: integer);
function GetPositionFecha: TDate;
procedure SetPositionFecha(const Value: TDate);
procedure OnBeforeZoomScroll;
procedure OnAfterZoomScroll;
procedure OnBeforeSetData;
procedure OnAfterSetData;
function GetColorPosition: TColor;
procedure SetActive(const Value: boolean);
property HelpPointActive: boolean read FHelpPointActive write SetHelpPointActive;
protected
function isInZoomZone: boolean;
procedure UpdateAll;
procedure PositionChange; virtual;
procedure InvalidatePosition(x, y: integer; const pintarCuadro: boolean);
procedure MoveXToScreenX(const X: integer);
procedure Paint(Buffer: TBitmap32); override;
procedure OnMessageTick;
procedure OnMessageTick2;
procedure OnTick;
procedure DoKeyUp(var Key: Word; Shift: TShiftState); override;
procedure RecalculateTransformados(const fromPos, toPos: integer); 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;
function DoHitTest(X, Y: Integer): Boolean; override;
function GetPosicion(const Fecha: TDate): integer;
public
constructor Create(Grafico: TGrafico); override;
destructor Destroy; override;
procedure HelpPoint;
procedure Siguiente;
procedure Anterior;
procedure Primero(const considerarZoom: boolean);
procedure Ultimo(const considerarZoom: boolean);
property Position: integer read FPosition write SetPosition;
property PositionFecha: TDate read GetPositionFecha write SetPositionFecha;
property HelpPointSize: integer read FHelpPointSize write FHelpPointSize default 32;
property ColorPosition: TColor read GetColorPosition write SetColorPosition;
property Active: boolean read FActive write SetActive;
property Enabled: boolean read FEnabled write FEnabled;
end;
TDefaultGraficoPositionLayer = class(TGraficoPositionLayer)
protected
procedure PositionChange; override;
end;
implementation
uses Types, SysUtils, Tipos, GraficoZoom, uTickService, uServices,
BusCommunication, dmData, DatosGrafico;
resourcestring
SESION_SIN_COTIZAR = 'Sesión sin cotizar';
const
HELP_POINT_SIZE: integer = 32;
POSICION_PRIMERO_CON_CAMBIOS = -1;
{ TGraficoPositionLayer }
procedure TGraficoPositionLayer.Anterior;
begin
if FPosition > 0 then
Position := Position - 1;
end;
procedure TGraficoPositionLayer.OnBeforeZoomScroll;
begin
PositionBeforeZoom := FPosition;
end;
constructor TGraficoPositionLayer.Create(Grafico: TGrafico);
begin
inherited Create(Grafico);
FColorPosition := clWhite32;
FColorPositionText := clWhite;
FHelpPointActive := false;
FHelpPointSize := HELP_POINT_SIZE;
Location := FloatRect(0, 0, Grafico.Width, Grafico.Height);
FPosition := POSICION_INDEFINIDA;
FActive := false;
FEnabled := true;
CanPaintActualPosition := false;
Grafico.RegisterEvent(MessageGraficoBeforeSetData, OnBeforeSetData);
Grafico.RegisterEvent(MessageGraficoAfterSetData, OnAfterSetData);
Grafico.RegisterEvent(MessageGraficoAfterZoom, OnAfterZoomScroll);
Grafico.RegisterEvent(MessageGraficoBeforeZoom, OnBeforeZoomScroll);
Grafico.RegisterEvent(MessageGraficoAfterScroll, OnAfterZoomScroll);
Grafico.RegisterEvent(MessageGraficoBeforeScroll, OnBeforeZoomScroll);
Bus.RegisterEvent(MessageTick, OnMessageTick);
Bus.RegisterEvent(MessageTick2, OnMessageTick2);
end;
destructor TGraficoPositionLayer.Destroy;
begin
Bus.UnregisterEvent(MessageTick, OnMessageTick);
Bus.UnregisterEvent(MessageTick2, OnMessageTick2);
Grafico.UnregisterEvent(MessageGraficoBeforeSetData, OnBeforeSetData);
Grafico.UnregisterEvent(MessageGraficoAfterSetData, OnAfterSetData);
Grafico.UnregisterEvent(MessageGraficoAfterZoom, OnAfterZoomScroll);
Grafico.UnregisterEvent(MessageGraficoBeforeZoom, OnBeforeZoomScroll);
Grafico.UnregisterEvent(MessageGraficoAfterScroll, OnAfterZoomScroll);
Grafico.UnregisterEvent(MessageGraficoBeforeScroll, OnBeforeZoomScroll);
inherited Destroy;
end;
function TGraficoPositionLayer.DoHitTest(X, Y: Integer): Boolean;
begin
result := FEnabled and FActive;
end;
procedure TGraficoPositionLayer.DoKeyUp(var Key: Word; Shift: TShiftState);
begin
case Key of
VK_LEFT, VK_DOWN : begin
Anterior;
Key := 0;
end;
VK_RIGHT, VK_UP : begin
Siguiente;
Key := 0;
end;
VK_END: begin
Ultimo(true);
Key := 0;
end;
VK_HOME: begin
Primero(true);
Key := 0;
end;
end;
end;
function TGraficoPositionLayer.GetColorPosition: TColor;
begin
result := FColorPositionText;
end;
function TGraficoPositionLayer.GetPointRect(const x, y: integer;
const HelpPointActual: boolean): TRect;
begin
if HelpPointActive then begin
if HelpPointActual then
result := Rect(x-HelpPointActualSize-2, y-HelpPointActualSize-2,
x+HelpPointActualSize+2, y+HelpPointActualSize+2)
else
result := Rect(x-FHelpPointSize-2, y-FHelpPointSize-2,
x+FHelpPointSize+2, y+FHelpPointSize+2);
end
else
result := Rect(x-2, y-2, x+2, y+2);
end;
function TGraficoPositionLayer.GetPosicion(const Fecha: TDate): integer;
var i, num: integer;
begin
num := Datos.DataCount - 1;
for i := num downto 0 do begin
if not Datos.IsSinCambio[i] then
if Datos.Fechas[i] <= Fecha then begin
result := i;
exit;
end;
end;
result := -1;
end;
function TGraficoPositionLayer.GetPositionFecha: TDate;
begin
if FPosition <> POSICION_INDEFINIDA then
result := Datos.Fechas[FPosition]
else
result := 0;
end;
procedure TGraficoPositionLayer.HelpPoint;
var zoom: TZoom;
begin
if not HelpPointActive then begin
zoom := TZoomGrafico(Grafico).ZoomInterval;
if FPosition > zoom.ZoomTo then begin
TZoomGrafico(Grafico).Scroll(FPosition - zoom.ZoomTo);
end
else begin
if FPosition < zoom.ZoomFrom then
TZoomGrafico(Grafico).Scroll(FPosition - zoom.ZoomFrom);
end;
HelpPointActive := true;
HelpPointActualSize := FHelpPointSize;
end;
end;
procedure TGraficoPositionLayer.InvalidatePosition(x, y: integer; const pintarCuadro: boolean);
var r: TRect;
anchoTexto: integer;
begin
if not FActive then
Exit;
if Datos.IsDataNull[FPosition] then begin
// Al arrancar se hace un HelpPointActive.
// Si la posición donde se está no hay cotización, se queda el
// HelpPointActive activo porque nunca se pasa por el else de abajo y no
// se llama a getPointRect, que es la función que desactiva el HelpPoint
// cuando ha hecho todo el efecto.
// Como consecuencia se ve el "sin cotización" parpadeando muy rápido,
// a 100, que es la velocidad del HelpPoint
HelpPointActive := false;
r.Right := x;
r.Top := 0;
Grafico.Bitmap.Font.Size := 10;
anchoTexto := Grafico.Bitmap.TextWidth(SESION_SIN_COTIZAR);
r.Left := x - 4 - anchoTexto;
if r.Left <= 1 then begin
r.Left := x + 4;
r.Right := x + 4 + anchoTexto;
end;
r.Bottom := Grafico.Height;
Update(r);
end
else begin
if CanPaintActualPosition then begin
UpdateAll;
end
else begin
r := getPointRect(x + 1, y, false);
Update(r);
end;
end;
end;
function TGraficoPositionLayer.isInZoomZone: boolean;
var zoom: TZoom;
begin
if Grafico is TZoomGrafico then begin
zoom := TZoomGrafico(Grafico).ZoomInterval;
result := (not TZoomGrafico(Grafico).IsZommed) or
((zoom.ZoomFrom <= FPosition) and (zoom.ZoomTo >= FPosition));
end
else
result := true;
end;
procedure TGraficoPositionLayer.MoveXToScreenX(const X: integer);
var i, iFrom, iTo, beginPos: integer;
zoom: TZoom;
begin
if Grafico is TZoomGrafico then begin
if TZoomGrafico(Grafico).IsZommed then begin
zoom := TZoomGrafico(Grafico).ZoomInterval;
if X >= Grafico.Width then begin
Position := zoom.ZoomTo + 1;
exit;
end
else begin
if X <= 0 then begin
Position := zoom.ZoomFrom - 1;
exit;
end
else begin
iTo := zoom.ZoomTo;
iFrom := 0;
end;
end;
end
else begin
iTo := Datos.DataCount - 1;
iFrom := 0;
end;
end
else begin
iTo := Datos.DataCount - 1;
iFrom := 0;
end;
i := iTo;
if X >= Grafico.Width then
Ultimo(true)
else begin
if X <= 0 then
Primero(true)
else begin
while i >= iFrom do begin
if Datos.XTransformados[i] <= X then begin
if Datos.IsSinCambio[i] then begin
beginPos := i;
// Vamos hacia la izquierda hasta encontrar un cambio
dec(i);
while i >= iFrom do begin
if not Datos.IsSinCambio[i] then begin
Position := i;
exit;
end;
dec(i);
end;
// Hacia la izquierda no hemos encontrado nada, vamos hacia la derecha
i := beginPos + 1;
while i <= iTo do begin
if not Datos.IsSinCambio[i] then begin
Position := i;
exit;
end;
inc(i);
end;
end
else
Position := i;
exit;
end;
dec(i);
end;
end;
end;
end;
procedure TGraficoPositionLayer.MouseDown(
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then begin
if Grafico is TZoomGrafico then begin
if not TZoomGrafico(Grafico).ZoomActive then begin
CanPaintActualPosition := true;
MoveXToScreenX(X);
end;
end
else begin
CanPaintActualPosition := true;
MoveXToScreenX(X);
end;
end;
end;
procedure TGraficoPositionLayer.MouseMove(Shift: TShiftState;
X, Y: Integer);
begin
if Shift = [ssLeft] then begin
if Grafico is TZoomGrafico then begin
if not TZoomGrafico(Grafico).ZoomActive then begin
CanPaintActualPosition := true;
MoveXToScreenX(X);
end;
end
else begin
CanPaintActualPosition := true;
MoveXToScreenX(X);
end;
end;
end;
procedure TGraficoPositionLayer.MouseUp(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then begin
if Grafico is TZoomGrafico then begin
if not TZoomGrafico(Grafico).ZoomActive then begin
CanPaintActualPosition := false;
MoveXToScreenX(X);
end;
end
else begin
CanPaintActualPosition := false;
MoveXToScreenX(X);
end;
pintarCuadro := true;
UpdateAll;
end;
end;
procedure TGraficoPositionLayer.OnBeforeSetData;
begin
OldActive := FActive;
FPosition := POSICION_INDEFINIDA;
FActive := False;
end;
procedure TGraficoPositionLayer.OnMessageTick;
begin
pintarCuadro := true;
OnTick;
end;
procedure TGraficoPositionLayer.OnMessageTick2;
begin
pintarCuadro := false;
OnTick;
end;
procedure TGraficoPositionLayer.OnTick;
var x, y: integer;
begin
isOnTick := true;
try
if (FActive) and (FPosition <> POSICION_INDEFINIDA) and (FPosition < Datos.DataCount) and
(isInZoomZone) then begin
if HelpPointActive then begin
HelpPointActive := HelpPointActualSize > 0;
HelpPointActualSize := HelpPointActualSize - 4;
end;
x := Datos.XTransformados[FPosition];
y := Datos.YTransformados[FPosition];
if y <> SIN_CAMBIO_TRANSFORMADO then
InvalidatePosition(x, y, pintarCuadro);
end;
finally
isOnTick := false;
end;
end;
procedure TGraficoPositionLayer.OnAfterSetData;
begin
FActive := OldActive;
end;
procedure TGraficoPositionLayer.OnAfterZoomScroll;
begin
// MUY IMPORTANTE: Debe asignarse a FPosition, no a Position, ya que asignar
// a Position significa que si la posición no está visible se ará scroll y lo
// único que necesitamos es retablecer la posición porque al hacer Zoom se hace
// un Recalculate y la posición pasa a indefinida.
FPosition := PositionBeforeZoom;
end;
procedure TGraficoPositionLayer.Paint(Buffer: TBitmap32);
var x, y, anchoTexto: integer;
r: TRect;
procedure ShowPositionEjeY;
var x, decimals: integer;
begin
x := Grafico.Width - Grafico.AnchoEjeY;
Buffer.FillRectS(x, y - 6, Grafico.Width - 1, y + 6, clPurple32);
if Grafico.ShowDecimals then begin
if Grafico.IsManualDecimals then
decimals := Grafico.ManualDecimals
else
decimals := CurrencyDecimals;
end
else
decimals := 0;
Buffer.Textout(x + 3, y - 7, CurrToStrF(Datos.Cambio[FPosition], ffCurrency, decimals));
end;
procedure ShowPositionEjeX;
var x, y, anchoText: integer;
text: string;
begin
y := Grafico.Height - 13;
text := DateToStr(Datos.Fechas[FPosition]);
anchoText := Buffer.TextWidth(text);
x := Datos.XTransformados[FPosition] - (anchoText div 2);
if x < 2 then
x := 2;
Buffer.FillRectS(x - 4, y + 2, x + anchoText + 4, y + 13, clPurple32);
Buffer.Textout(x, y, text);
end;
procedure ShowPositionEjes(showY: boolean);
begin
Buffer.Font.Size := 8;
if (Grafico.ShowY) and (showY) then
ShowPositionEjeY;
if Grafico.ShowX then
ShowPositionEjeX;
end;
begin
if (FActive) and (FPosition <> POSICION_INDEFINIDA) and (isInZoomZone) then begin
Buffer.Font.Color := clWhite;
if Datos.IsCambio[FPosition] then begin
x := Datos.XTransformados[FPosition];
y := Datos.YTransformados[FPosition];
if CanPaintActualPosition then begin
Buffer.SetStipple([FColorPosition, FColorPosition, FColorPosition, 0, 0, 0]);
Buffer.HorzLineTSP(0, y, Grafico.Width);
Buffer.VertLineTSP(x, 0, Grafico.Height);
end;
ShowPositionEjes(true);
if pintarCuadro then begin
// El punto indicando la posición
r := getPointRect(x + 1, y, true);
Buffer.FillRectS(r.Left, r.Top, r.Right, r.Bottom, FColorPosition);
end;
end
else begin
if Datos.IsDataNull[FPosition] then begin
x := Datos.XTransformados[FPosition];
y := Datos.YTransformados[FPosition];
ShowPositionEjes(False);
Buffer.Font.Color := FColorPositionText;
Buffer.Font.Size := 10;
Buffer.VertLineS(x, 0, Grafico.Alto, FColorPosition);
anchoTexto := Grafico.Bitmap.TextWidth(SESION_SIN_COTIZAR);
if x - anchoTexto <= 1 then
x := x + 4
else
x := x - 4 - anchoTexto;
Buffer.Textout(x, 10, SESION_SIN_COTIZAR);
end;
end;
end;
end;
procedure TGraficoPositionLayer.PositionChange;
begin
UpdateAll;
SendEvent(MessageGraficoPositionChange);
end;
procedure TGraficoPositionLayer.Primero(const considerarZoom: boolean);
var from: integer;
begin
if Datos.DataCount > 0 then begin
if considerarZoom then begin
from := TZoomGrafico(Grafico).ZoomInterval.ZoomFrom;
if Position = from then
Position := POSICION_PRIMERO_CON_CAMBIOS
else
Position := from;
end
else
Position := POSICION_PRIMERO_CON_CAMBIOS;
end
else
Position := POSICION_INDEFINIDA;
end;
procedure TGraficoPositionLayer.RecalculateTransformados(const fromPos,
toPos: integer);
begin
end;
procedure TGraficoPositionLayer.SetActive(const Value: boolean);
begin
FActive := Value;
//Si esta en el tick, debemos esperar a que acabe, sino podría pasar que
//se modifiquen los datos en medio de un tick, por lo que daría access violation
while isOnTick do;
end;
procedure TGraficoPositionLayer.SetColorPosition(const Value: TColor);
begin
FColorPositionText := Value;
FColorPosition := Color32(Value);
end;
procedure TGraficoPositionLayer.SetHelpPointActive(const Value: boolean);
var TickService: TTickService;
begin
if FHelpPointActive <> Value then begin
FHelpPointActive := Value;
TickService := TTickService(Services.GetService(TTickService));
if FHelpPointActive then
TickService.Interval := 100
else
TickService.Interval := DEFAULT_FLASH_INTERVAL;
end;
end;
procedure TGraficoPositionLayer.SetPosition(const Value: integer);
var zoom: TZoom;
i, num: integer;
begin
if FPosition <> Value then begin
if (FPosition <> POSICION_INDEFINIDA) and (FActive) and (FPosition < Datos.DataCount) then
//Invalidate previous position
InvalidatePosition(Datos.XTransformados[FPosition], Datos.YTransformados[FPosition], false);
// New position
if Value < 0 then begin
i := 0;
while Datos.IsSinCambio[i] do
inc(i);
FPosition := i;
end
else begin
num := Datos.DataCount - 1;
if Value > num then begin
i := num;
while Datos.IsSinCambio[i] do
dec(i);
FPosition := i;
end
else begin
i := Value;
while (i < num) and (Datos.IsSinCambio[i]) do
inc(i);
if Datos.IsSinCambio[i] then begin
while (i > 0) and (Datos.IsSinCambio[i]) do
dec(i);
end;
if Datos.IsSinCambio[i] then
FPosition := POSICION_INDEFINIDA
else
FPosition := i;
end;
end;
if Grafico is TZoomGrafico then begin
zoom := TZoomGrafico(Grafico).ZoomInterval;
if not TZoomGrafico(Grafico).IsZommed then
InvalidatePosition(Datos.XTransformados[FPosition], Datos.YTransformados[FPosition], true)
else begin
if zoom.ZoomTo < FPosition then
TZoomGrafico(Grafico).Scroll(FPosition - zoom.ZoomTo)
else
if zoom.ZoomFrom > FPosition then
TZoomGrafico(Grafico).Scroll(FPosition - zoom.ZoomFrom)
else
InvalidatePosition(Datos.XTransformados[FPosition], Datos.YTransformados[FPosition], true);
end;
end
else
InvalidatePosition(Datos.XTransformados[FPosition], Datos.YTransformados[FPosition], true);
PositionChange;
end;
end;
procedure TGraficoPositionLayer.SetPositionFecha(const Value: TDate);
var i: integer;
begin
i := GetPosicion(Value);
if i <> -1 then
Position := i;
end;
procedure TGraficoPositionLayer.Siguiente;
begin
if FPosition < Datos.DataCount - 1 then
Position := Position + 1;
end;
procedure TGraficoPositionLayer.Ultimo(const considerarZoom: boolean);
var from: integer;
begin
if Datos.DataCount > 0 then begin
if considerarZoom then begin
from := TZoomGrafico(Grafico).ZoomInterval.ZoomTo;
if Position = from then
Position := Datos.DataCount - 1
else
Position := from;
end
else
Position := Datos.DataCount - 1;
end
else
Position := POSICION_INDEFINIDA;
end;
procedure TGraficoPositionLayer.UpdateAll;
begin
Update(Rect(0, 0, Grafico.Width, Grafico.Height));
end;
{ TDefaultGraficoPositionLayer }
procedure TDefaultGraficoPositionLayer.PositionChange;
begin
if (Position <> POSICION_INDEFINIDA) and (Position < Datos.DataCount) then
Data.IrACotizacionConFecha(Datos.Fechas[Position]);
inherited PositionChange;
end;
end.
|
unit uPrincipal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
FormColor: TColor;
procedure TForm1.FormCreate(Sender: TObject);
begin
KeyPreview := true;
FormColor := Form1.Color;
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_F1) AND (Shift = [ssShift]) then
begin
Form1.Color := clRed;
end;
end;
procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_F1 then
begin
Form1.Color := FormColor;
end;
end;
end.
|
unit Samples.Main;
interface
uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.ExtCtrls, Vcl.ComCtrls,
Vcl.Imaging.pngimage, Vcl.Mask;
type
TMyCompletionHandlerWithError = TProc<TObject>;
TFrmMain = class(TForm)
Panel1: TPanel;
Image1: TImage;
Panel2: TPanel;
Panel3: TPanel;
Splitter1: TSplitter;
Panel4: TPanel;
Panel5: TPanel;
Panel6: TPanel;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
PageControl2: TPageControl;
TabSheet6: TTabSheet;
edtBaseURL: TLabeledEdit;
edtAccept: TLabeledEdit;
Label1: TLabel;
mmCustomBody: TMemo;
btnDELETE: TButton;
btnPUT: TButton;
btnPOST: TButton;
btnGET: TButton;
mmBody: TMemo;
lblStatusCode: TLabel;
Label3: TLabel;
TabSheet2: TTabSheet;
Panel7: TPanel;
Label2: TLabel;
imgMultipartFormDataStream: TImage;
Label4: TLabel;
edtMultipartFormDataText: TEdit;
Label5: TLabel;
lblMultipartFormDataFile: TLabel;
Panel9: TPanel;
Panel10: TPanel;
btnMultipartFormDataPost: TButton;
edtMultipartFormDataBaseURL: TLabeledEdit;
Panel8: TPanel;
lblRESTRequest4DelphiComponent: TLabel;
btnMultipartFormDataPut: TButton;
FDMemTable1: TFDMemTable;
procedure btnGETClick(Sender: TObject);
procedure btnPOSTClick(Sender: TObject);
procedure btnPUTClick(Sender: TObject);
procedure btnDELETEClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnMultipartFormDataPostClick(Sender: TObject);
procedure btnMultipartFormDataPutClick(Sender: TObject);
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses RESTRequest4D;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
PageControl1.ActivePage := TabSheet1;
lblMultipartFormDataFile.Caption := (ExtractFilePath(ParamStr(0)) + 'RESTRequest4Delphi.pdf');
{$IF DEFINED(FPC) and (not DEFINED(RR4D_INDY)) and (not DEFINED(RR4D_SYNAPSE))}
RESTRequest4D.Request.FPHTTPClient;
lblRESTRequest4DelphiComponent.Caption := 'RESTRequest4Delphi: RR4D_FPHTTPCLIENT';
{$ELSEIF DEFINED(RR4D_INDY)}
lblRESTRequest4DelphiComponent.Caption := 'RESTRequest4Delphi: RR4D_INDY';
{$ELSEIF DEFINED(RR4D_NETHTTP)}
lblRESTRequest4DelphiComponent.Caption := 'RESTRequest4Delphi: RR4D_NETHTTP';
{$ELSEIF DEFINED(RR4D_SYNAPSE)}
lblRESTRequest4DelphiComponent.Caption := 'RESTRequest4Delphi: RR4D_SYNAPSE';
{$ELSE}
lblRESTRequest4DelphiComponent.Caption := 'RESTRequest4Delphi: RR4D_RESTCLIENT';
{$ENDIF}
end;
procedure TFrmMain.btnDELETEClick(Sender: TObject);
var
LResponse: IResponse;
begin
LResponse := TRequest.New.BaseURL(edtBaseURL.Text)
.Accept(edtAccept.Text)
.Delete;
mmBody.Lines.Text := LResponse.Content;
lblStatusCode.Caption := LResponse.StatusCode.ToString;
end;
procedure TFrmMain.btnGETClick(Sender: TObject);
var
LResponse: IResponse;
begin
LResponse := TRequest.New.BaseURL(edtBaseURL.Text)
.Accept(edtAccept.Text)
.Get;
mmBody.Lines.Text := LResponse.Content;
lblStatusCode.Caption := LResponse.StatusCode.ToString;
end;
procedure TFrmMain.btnMultipartFormDataPostClick(Sender: TObject);
var
LStream: TMemoryStream;
LResponse: IResponse;
begin
LStream := TMemoryStream.Create;
try
{$IF COMPILERVERSION <= 31.0}
imgMultipartFormDataStream.Picture.Graphic.SaveToStream(LStream);
{$ELSE}
imgMultipartFormDataStream.Picture.SaveToStream(LStream);
{$ENDIF}
LResponse := TRequest.New.BaseURL(edtMultipartFormDataBaseURL.Text)
.AddField('text', edtMultipartFormDataText.Text)
.AddFile('file', lblMultipartFormDataFile.Caption)
.AddFile('stream', LStream)
.Post;
finally
LStream.Free;
end;
mmBody.Lines.Text := LResponse.Content;
lblStatusCode.Caption := LResponse.StatusCode.ToString;
end;
procedure TFrmMain.btnMultipartFormDataPutClick(Sender: TObject);
var
LStream: TMemoryStream;
LResponse: IResponse;
begin
LStream := TMemoryStream.Create;
try
{$IF COMPILERVERSION <= 31.0}
imgMultipartFormDataStream.Picture.Graphic.SaveToStream(LStream);
{$ELSE}
imgMultipartFormDataStream.Picture.SaveToStream(LStream);
{$ENDIF}
LResponse := TRequest.New.BaseURL(edtMultipartFormDataBaseURL.Text)
.AddField('text', edtMultipartFormDataText.Text)
.AddFile('file', lblMultipartFormDataFile.Caption)
.AddFile('stream', LStream)
.Put;
finally
LStream.Free;
end;
mmBody.Lines.Text := LResponse.Content;
lblStatusCode.Caption := LResponse.StatusCode.ToString;
end;
procedure TFrmMain.btnPOSTClick(Sender: TObject);
var
LResponse: IResponse;
begin
LResponse := TRequest.New.BaseURL(edtBaseURL.Text)
.Accept(edtAccept.Text)
.AddBody(mmCustomBody.Lines.Text)
.Post;
mmBody.Lines.Text := LResponse.Content;
lblStatusCode.Caption := LResponse.StatusCode.ToString;
end;
procedure TFrmMain.btnPUTClick(Sender: TObject);
var
LResponse: IResponse;
begin
LResponse := TRequest.New.BaseURL(edtBaseURL.Text)
.Accept(edtAccept.Text)
.AddBody(mmCustomBody.Lines.Text)
.Put;
mmBody.Lines.Text := LResponse.Content;
lblStatusCode.Caption := LResponse.StatusCode.ToString;
end;
end.
|
unit shellcommand;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, AndroidWidget;
type
TOnCommandExecuted = procedure(Sender: TObject; cmdResult: string) of Object;
{Draft Component code by "Lazarus Android Module Wizard" [5/8/2015 20:50:05]}
{https://github.com/jmpessoa/lazandroidmodulewizard}
{jControl template}
jShellCommand = class(jControl)
private
FOnCommandExecuted: TOnCommandExecuted;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Init; override;
function jCreate(): jObject;
procedure jFree();
procedure ExecuteAsync(_shellCmd: string);
procedure GenEvent_OnShellCommandExecuted(Obj: TObject; cmdResult: string);
published
property OnExecuted: TOnCommandExecuted read FOnCommandExecuted write FOnCommandExecuted;
end;
function jShellCommand_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
procedure jShellCommand_jFree(env: PJNIEnv; _jshellcommand: JObject);
procedure jShellCommand_Execute(env: PJNIEnv; _jshellcommand: JObject; _shellCmd: string);
implementation
{--------- jShellCommand --------------}
constructor jShellCommand.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//your code here....
end;
destructor jShellCommand.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if FjObject <> nil then
begin
jFree();
FjObject:= nil;
end;
end;
//you others free code here...'
inherited Destroy;
end;
procedure jShellCommand.Init;
begin
if FInitialized then Exit;
inherited Init; //set default ViewParent/FjPRLayout as jForm.View!
//your code here: set/initialize create params....
FjObject := jCreate(); if FjObject = nil then exit;
FInitialized:= True;
end;
function jShellCommand.jCreate(): jObject;
begin
Result:= jShellCommand_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis);
end;
procedure jShellCommand.jFree();
begin
//in designing component state: set value here...
if FInitialized then
jShellCommand_jFree(gApp.jni.jEnv, FjObject);
end;
procedure jShellCommand.ExecuteAsync(_shellCmd: string);
begin
//in designing component state: set value here...
if FInitialized then
jShellCommand_Execute(gApp.jni.jEnv, FjObject, _shellCmd);
end;
procedure jShellCommand.GenEvent_OnShellCommandExecuted(Obj: TObject; cmdResult: string);
begin
if Assigned(FOnCommandExecuted) then FOnCommandExecuted(Obj, cmdResult);
end;
{-------- jShellCommand_JNI_Bridge ----------}
function jShellCommand_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject;
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].j:= _Self;
jCls:= Get_gjClass(env);
jMethod:= env^.GetMethodID(env, jCls, 'jShellCommand_jCreate', '(J)Ljava/lang/Object;');
Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams);
Result:= env^.NewGlobalRef(env, Result);
end;
(*
//Please, you need insert:
public java.lang.Object jShellCommand_jCreate(long _Self) {
return (java.lang.Object)(new jShellCommand(this,_Self));
}
//to end of "public class Controls" in "Controls.java"
*)
procedure jShellCommand_jFree(env: PJNIEnv; _jshellcommand: JObject);
var
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jCls:= env^.GetObjectClass(env, _jshellcommand);
jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V');
env^.CallVoidMethod(env, _jshellcommand, jMethod);
env^.DeleteLocalRef(env, jCls);
end;
procedure jShellCommand_Execute(env: PJNIEnv; _jshellcommand: JObject; _shellCmd: string);
var
jParams: array[0..0] of jValue;
jMethod: jMethodID=nil;
jCls: jClass=nil;
begin
jParams[0].l:= env^.NewStringUTF(env, PChar(_shellCmd));
jCls:= env^.GetObjectClass(env, _jshellcommand);
jMethod:= env^.GetMethodID(env, jCls, 'Execute', '(Ljava/lang/String;)V');
env^.CallVoidMethodA(env, _jshellcommand, jMethod, @jParams);
env^.DeleteLocalRef(env,jParams[0].l);
env^.DeleteLocalRef(env, jCls);
end;
end.
|
(* ENUNCIADO
Faça um programa em Free Pascal que leia um número natural 0 < n ≤ 100 e em seguida leia uma sequência de n números
também naturais. Seu programa deve verificar se existem duas subsequências iguais nesta sequência com tamanho pelo menos 2.
O tamanho da sequência encontrada deverá ser máximo, se ela existir.
Caso exista, seu programa deve imprimir o valor do ı́ndice i e do tamanho máximo da sequência m, nesta ordem,
onde i é a primeira ocorrência da sequência que possui uma cópia na sequência original e m é o tamanho desta
sequência que se repete. Caso contrário seu programa deve imprimir "nenhuma".
Os casos de teste não conterão entradas com mais de uma subsequência igual.
Exemplo de entrada 1:
87 9 5 4 5 5 4 6
Saı́da esperada para a entrada acima:
3 2
Exemplo de entrada 2:
12
2 7 9 5 2 5 4 8 6 2 5 4
Saı́da esperada para a entrada acima:
5 3
Sugestão:
Use como base para sua implementação a seguinte estrutura inicial de programa, que contém o programa principal e
algumas funções e procedimentos que visam facilitar o seu trabalho. Evidentemente você pode ignorar esta sugestão.
Caso aceite, você deve implementar as funções e procedimentos, o programa principal não deveria ter que ser alterado,
a princı́pio. Você pode também decidir usar mais funções e procedimentos caso perceba que seu programa ficará mais legı́vel.
*)
(*
program escolha_um_nome_bom;
const MAX = 100;
type vetor = array [1..MAX] of longint;
var
v : vetor;
n, pos, tamanho_subsequencia: longint;
procedure ler_vetor (var v: vetor; n: longint);
(* procedure para ler um vetor "v" de "n" inteiros *)
(*
function tem_subsequencia_iguais (var v: vetor; n, tam_seg: longint): longint;
(*
recebe uma subsequencia "v" que em tamanho "n" e procura por subsequencias
iguais de tamanho "tam_seg". A funcao devolve zero se nao encontrou
subsequencias iguais ou devolve a posicao do inicio da primeira subsequencia
que encontrou.
*)
(* programa principal *)
(*
begin
read (n);
// tamanho da subsequencia a ser lido
ler_vetor (v,n);
pos:= 0;
tamanho_subsequencia:= n div 2; // inicia com maior valor possivel
while (pos = 0) and (tamanho_subsequencia >= 2) do
begin
pos:= tem_subsequencia_iguais (v,n,tamanho_subsequencia);
tamanho_subsequencia:= tamanho_subsequencia - 1;
end;
if pos > 0 then
writeln (pos,’ ’,tamanho_subsequencia+1)
else
writeln ('nenhuma');
end.
*)
program 3subsequencias;
const
MAX = 100;
type
vetor = array [1..MAX] of longint;
var
v : vetor;
n, pos, tamanho_subsequencia: longint;
procedure ler_vetor(var v: vetor; n: longint);
var
cont: longint;
begin
for cont:=1 to n do
read(v[cont]);
end;
function tem_subsequencia_iguais (var v: vetor; n, tam_seg: longint): longint;
var
aux:vetor;
diferente,igual,naocont,cont,posi,cont2,tam_seg_original,auxtam_seg:longint;
begin
auxtam_seg:=tam_seg;
if n mod 2 = 0 then
tam_seg_original:=n div 2
else
tam_seg_original:=(n div 2)+1;
if tam_seg_original>tam_seg then
auxtam_seg:=(tam_seg_original-tam_seg)*2+tam_seg;
naocont:=0;
tem_subsequencia_iguais:=0;
cont:=0;
igual:=0;
diferente:=0;
while (cont<auxtam_seg)and(igual=0) do
begin
cont:=cont+1;
for posi:=cont to (tam_seg+cont-1) do
begin
aux[posi-naocont]:=v[posi];
end;
posi:=0;
repeat
posi:=posi+1;
cont2:=0; igual:=1;
repeat
cont2:=cont2+1;diferente:=0;
if aux[cont2]<>v[posi+cont2+naocont] then
begin
diferente:=1;
igual:=0;
end;
until ((cont2 = tam_seg)and(igual=1))or(diferente=1);
until (posi =(auxtam_seg-cont+1))or(igual=1);
naocont:=naocont+1;
end;
if igual=1 then
tem_subsequencia_iguais:=cont;
end;
(* programa principal *)
begin
read (n); // tamanho da subsequencia a ser lido
ler_vetor (v,n);
pos:= 0;
if n mod 2 = 0 then
tamanho_subsequencia:= n div 2
else
tamanho_subsequencia:= (n div 2)+1;
; // inicia com maior valor possivel
while (pos = 0) and (tamanho_subsequencia >= 2) do
begin
pos:= tem_subsequencia_iguais (v,n,tamanho_subsequencia);
tamanho_subsequencia:= tamanho_subsequencia - 1;
end;
if pos > 0 then
writeln (pos,' ',tamanho_subsequencia+1)
else
writeln ('nenhuma');
end.
|
unit CCDBv2;
interface
uses
SysUtils, Classes, pngimage, Dialog.Message;
const
CCDB_VERSION = '7B043E.1';
type
DATA_STRUCT_MOTHERBOARDS = record
CPU : Byte;
Socket : String[15];
Chipset : String[31];
FormFactor : Byte;
MemType : Byte;
MemChannels : Byte;
end;
PDataStructMotherboards = ^DATA_STRUCT_MOTHERBOARDS;
DATA_STRUCT_CPU = record
Architecture : String[31];
Socket : String[15];
Frequency : Word;
Cores : Byte;
Graphics : Byte;
end;
PDataStructCPU = ^DATA_STRUCT_CPU;
DATA_STRUCT_MEMORY = record
BankType : Byte;
Frequency : Byte;
Capacity : Word;
SupportsXMP : Boolean;
SupportsECC : Boolean;
Latency : Byte;
Voltage : Byte;
end;
PDataStructMemory = ^DATA_STRUCT_MEMORY;
DATA_STRUCT_HDD = record
MediaType : Byte;
FormFactor : Byte;
ConnInterface : Byte;
Capacity : Word;
BufferSize : Word;
FlashType : Byte;
end;
PDataStructHDD = ^DATA_STRUCT_HDD;
DATA_STRUCT_COOLANT = record
Purpose : Byte;
CoolantType : Byte;
Material : Byte;
Dissepation : Word;
Diameter : Byte;
NoiseLevel : Word;
SupDevices : String[255];
end;
PDataStructCoolant = ^DATA_STRUCT_COOLANT;
DATA_STRUCT_PWR_SUPPLY = record
Standard : Byte;
Scheme12V : Byte;
Watts : Word;
Efficiency : Word;
ActivePFC : Boolean;
Cert80 : Byte;
end;
PDataStructPwrSupply = ^DATA_STRUCT_PWR_SUPPLY;
DATA_STRUCT_GRAPHICS = record
GPU : String[31];
ConnInterface : Byte;
Cooling : Byte;
Width : Word;
GPUFreq : Word;
MemFreq : Word;
Bus : Byte;
MemType : Byte;
DirectX : Byte;
SLI : Boolean;
HDMI : Boolean;
end;
PDataStructGraphics = ^DATA_STRUCT_GRAPHICS;
DATA_STRUCT_AUDIO = record
Format : Byte;
ConnInterface : Byte;
Channels : Byte;
DAC_Freq : Byte;
DAC_Word : Byte;
ADC_Freq : Byte;
ADC_Word : Byte;
PhonesOut : Boolean;
MicIn : Boolean;
LineIn : Boolean;
Coaxical : Boolean;
HDMI : Boolean;
MIDI : Boolean;
Instrumental : Boolean;
end;
PDataStructAudio = ^DATA_STRUCT_AUDIO;
DATA_STRUCT_OPTICAL_DRIVE = record
Format : Byte;
ConnInterface : Byte;
SupprtMedia : Byte;
DiskFlashing : Byte;
ReadSpeed : Byte;
WriteSpeed : Byte;
end;
PDataStructODD = ^DATA_STRUCT_OPTICAL_DRIVE;
DATA_STRUCT_SYS_UNIT = record
Format : Byte;
FormFactor : Byte;
Material : Byte;
Color : Byte;
DustFilters : Boolean;
Display : Boolean;
USB30Support : Boolean;
AppleDock : Boolean;
end;
PDataStructSysUnit = ^DATA_STRUCT_SYS_UNIT;
const
DATA_TAG_MOTHERBOARDS = 0;
DATA_TAG_CPU = 1;
DATA_TAG_MEMORY = 2;
DATA_TAG_HDD = 3;
DATA_TAG_COOLANT = 4;
DATA_TAG_PWR_SUPPLY = 5;
DATA_TAG_GRAPHICS = 6;
DATA_TAG_AUDIO = 7;
DATA_TAG_OPTICAL_DRIVES = 8;
DATA_TAG_SYS_UNIT = 9;
type
TRecCommonData = record
DataTag : Byte; // Specifies data structure type [DATA_TAG_xxxx] (not data at all)
Vendor : String[31];
Model : String[63];
ProductID : String[31];
Notes : String[191];
ReleaseYear : Word;
ReleaseQuater : Byte;
MinPrice : Word;
MaxPrice : Word;
AttachSize : LongWord;
end;
PRecCommonData = ^TRecCommonData;
PCatalogRecord = ^TCatalogRecord;
TCatalogRecord = record
ID: Cardinal; // ID
Data: TRecCommonData; // Common data
LinkedData: Pointer; // Linked data pointer (extended)
Picture: TPngImage;
BytesAlloc: Cardinal; // Specifies number of bytes allocated for linked data structure
Changed: Boolean; // Specifies if record was changed after the last save\reset
Next: PCatalogRecord; // Next
Previous: PCatalogRecord; // Previous
end;
TSearchViewingField = (vfVendor, vfModel, vfProductID, vfNotes, vfPrice);
TSearchViewingFields = set of TSearchViewingField;
PSearchItem = ^TSearchItem;
TSearchItem = record
Item: PCatalogRecord;
MatchingFields: TSearchViewingFields;
Next: PSearchItem;
end;
TSearchQuery = record
{ Opts. }
Text: String; // Text to find
ViewingCats: array [0..9] of Boolean; // Viewing categories
ViewingFields: TSearchViewingFields; // Viewing fields
CaseSensitive: Boolean; // Defines if search is case sensitive
WholeMatch: Boolean; // Defines if search is only by the whole words
StartFromCursor: Boolean; //
{ Result }
Result: PSearchItem; // First search record
Count: Integer; // Total number of search records
end;
TCatalogFileHeader = record
Count: Word;
EditionDate: TDateTime;
end;
TSortingField = (sfNone, sfDataTag, sfName, sfPrice, sfReleaseDate);
ECurseCatalogEngine = class(Exception);
TCurseCatalogEngine = class(TPersistent)
private
FFirst: PCatalogRecord;
FLastAdded: PCatalogRecord;
FChanged: Boolean;
FCount: Integer;
FNextID: Cardinal;
FBytesAllocated: Cardinal;
FFileName: String;
FSearchQuery: TSearchQuery;
FSorted: Boolean;
private
FEditionDate: TDateTime;
{ *** }
function LocateStruct(const ID: Cardinal): PCatalogRecord;
procedure SetSearchQuery(const Value: TSearchQuery);
public
constructor Create(const AFileName: String);
destructor Destroy; override;
{ *** }
procedure Append(const Data: PRecCommonData; const ExData: PDataStructMotherboards); overload;
procedure Append(const Data: PRecCommonData; const ExData: PDataStructCPU); overload;
procedure Append(const Data: PRecCommonData; const ExData: PDataStructMemory); overload;
procedure Append(const Data: PRecCommonData; const ExData: PDataStructHDD); overload;
procedure Append(const Data: PRecCommonData; const ExData: PDataStructCoolant); overload;
procedure Append(const Data: PRecCommonData; const ExData: PDataStructPwrSupply); overload;
procedure Append(const Data: PRecCommonData; const ExData: PDataStructGraphics); overload;
procedure Append(const Data: PRecCommonData; const ExData: PDataStructAudio); overload;
procedure Append(const Data: PRecCommonData; const ExData: PDataStructODD); overload;
procedure Append(const Data: PRecCommonData; const ExData: PDataStructSysUnit); overload;
{ *** }
procedure Insert(const ADataTag: Integer; const AData: PRecCommonData;
const AExData: Pointer; const Size: Cardinal);
{ *** }
procedure Change(const ID: Cardinal; const AData: PRecCommonData;
const AExData: Pointer); overload;
procedure Change(const Rec: PCatalogRecord; const AData: PRecCommonData;
const AExData: Pointer); overload;
{ *** }
procedure Delete(const ID: Cardinal); overload;
procedure Delete(const Rec: PCatalogRecord; const OnlyDispose: Boolean = False); overload;
procedure EraseAll;
{ *** }
procedure RestoreFromFile;
procedure FlushToFile;
{ *** }
procedure Search;
function RecExists(const Rec: PCatalogRecord): Boolean;
{ *** }
procedure Sort(const SortByField: TSortingField);
{ *** }
property First: PCatalogRecord read FFirst;
property LastAdded: PCatalogRecord read FLastAdded;
property Changed: Boolean read FChanged;
property Count: Integer read FCount;
property FileName: String read FFileName write FFileName;
property Sorted: Boolean read FSorted;
property EditionDate: TDateTime read FEditionDate;
{ *** }
property SearchQuery: TSearchQuery read FSearchQuery write SetSearchQuery;
end;
{ Safely removes search result & ptrs. }
procedure ClearSearchResults(var Query: TSearchQuery);
implementation
procedure ClearSearchResults(var Query: TSearchQuery);
var
Q, P: PSearchItem;
begin
P := Query.Result;
while P <> nil do
begin
Q := P;
Dispose(Q);
P := P^.Next;
end;
Query.Count := 0;
end;
{ TCurseCatalogEngine }
procedure TCurseCatalogEngine.Append(const Data: PRecCommonData;
const ExData: PDataStructMotherboards);
begin
Insert(DATA_TAG_MOTHERBOARDS, Data, ExData, Sizeof(DATA_STRUCT_MOTHERBOARDS));
end;
procedure TCurseCatalogEngine.Append(const Data: PRecCommonData;
const ExData: PDataStructCPU);
begin
Insert(DATA_TAG_CPU, Data, ExData, Sizeof(DATA_STRUCT_CPU));
end;
procedure TCurseCatalogEngine.Append(const Data: PRecCommonData;
const ExData: PDataStructMemory);
begin
Insert(DATA_TAG_MEMORY, Data, ExData, Sizeof(DATA_STRUCT_MEMORY));
end;
procedure TCurseCatalogEngine.Delete(const ID: Cardinal);
const
ERR_BAD_ID = 'Method DELETE was called with invalid arguments: ID does not exists!';
var
Rec: PCatalogRecord;
begin
Rec := LocateStruct(ID);
if not Assigned(Rec) then
raise ECurseCatalogEngine.Create(ERR_BAD_ID);
Delete(Rec);
end;
procedure TCurseCatalogEngine.Append(const Data: PRecCommonData;
const ExData: PDataStructPwrSupply);
begin
Insert(DATA_TAG_PWR_SUPPLY, Data, ExData, Sizeof(DATA_STRUCT_PWR_SUPPLY));
end;
procedure TCurseCatalogEngine.Append(const Data: PRecCommonData;
const ExData: PDataStructCoolant);
begin
Insert(DATA_TAG_COOLANT, Data, ExData, Sizeof(DATA_STRUCT_COOLANT));
end;
procedure TCurseCatalogEngine.Append(const Data: PRecCommonData;
const ExData: PDataStructHDD);
begin
Insert(DATA_TAG_HDD, Data, ExData, Sizeof(DATA_STRUCT_HDD));
end;
procedure TCurseCatalogEngine.Append(const Data: PRecCommonData;
const ExData: PDataStructGraphics);
begin
Insert(DATA_TAG_GRAPHICS, Data, ExData, Sizeof(DATA_STRUCT_GRAPHICS));
end;
procedure TCurseCatalogEngine.Append(const Data: PRecCommonData;
const ExData: PDataStructSysUnit);
begin
Insert(DATA_TAG_SYS_UNIT, Data, ExData, Sizeof(DATA_STRUCT_SYS_UNIT));
end;
procedure TCurseCatalogEngine.Change(const ID: Cardinal; const AData: PRecCommonData;
const AExData: Pointer);
const
ERR_BAD_ID = 'Method CHANGE was called with invalid arguments: ID does not exists!';
var
Rec: PCatalogRecord;
begin
Rec := LocateStruct(ID);
if not Assigned(Rec) then
raise ECurseCatalogEngine.Create(ERR_BAD_ID);
Change(Rec, AData, AExData);
end;
procedure TCurseCatalogEngine.Change(const Rec: PCatalogRecord; const AData: PRecCommonData;
const AExData: Pointer);
const
ERR_INVALID_PTR = 'Method CHANGE was called, but no pointer was specified.';
begin
if not Assigned(Rec) or not Assigned(AExData) then
raise ECurseCatalogEngine.Create(ERR_INVALID_PTR);
AData^.DataTag := Rec^.Data.DataTag;
AData^.AttachSize := Rec^.Data.AttachSize;
Rec^.Data := AData^;
Rec^.Changed := True;
{ Previously delete old data }
case Rec^.Data.DataTag of
DATA_TAG_MOTHERBOARDS: Dispose(PDataStructMotherboards(Rec^.LinkedData));
DATA_TAG_CPU: Dispose(PDataStructCPU(Rec^.LinkedData));
DATA_TAG_MEMORY: Dispose(PDataStructMemory(Rec^.LinkedData));
DATA_TAG_HDD: Dispose(PDataStructHDD(Rec^.LinkedData));
DATA_TAG_COOLANT: Dispose(PDataStructCoolant(Rec^.LinkedData));
DATA_TAG_PWR_SUPPLY: Dispose(PDataStructPwrSupply(Rec^.LinkedData));
DATA_TAG_GRAPHICS: Dispose(PDataStructGraphics(Rec^.LinkedData));
DATA_TAG_AUDIO: Dispose(PDataStructAudio(Rec^.LinkedData));
DATA_TAG_OPTICAL_DRIVES: Dispose(PDataStructODD(Rec^.LinkedData));
DATA_TAG_SYS_UNIT: Dispose(PDataStructSysUnit(Rec^.LinkedData));
end;
Rec^.LinkedData := AExData;
FChanged := True;
FSorted := False;
end;
constructor TCurseCatalogEngine.Create(const AFileName: String);
begin
inherited Create;
FNextID := 0;
FFirst := nil;
FLastAdded := nil;
FCount := 0;
FChanged := False;
FBytesAllocated := 0;
FFileName := AFileName;
FSorted := True;
FEditionDate := Now;
end;
procedure TCurseCatalogEngine.Append(const Data: PRecCommonData;
const ExData: PDataStructODD);
begin
Insert(DATA_TAG_OPTICAL_DRIVES, Data, ExData, Sizeof(DATA_STRUCT_OPTICAL_DRIVE));
end;
procedure TCurseCatalogEngine.Append(const Data: PRecCommonData;
const ExData: PDataStructAudio);
begin
Insert(DATA_TAG_AUDIO, Data, ExData, Sizeof(DATA_STRUCT_AUDIO));
end;
procedure TCurseCatalogEngine.Delete(const Rec: PCatalogRecord; const OnlyDispose: Boolean = False);
const
ERR_INVALID_PTR = 'Method DELETE was called, but no pointer was specified.';
begin
if not Assigned(Rec) then
raise ECurseCatalogEngine.Create(ERR_INVALID_PTR);
if not OnlyDispose then
begin
if Rec^.Next <> nil then
Rec^.Next^.Previous := Rec^.Previous;
if Rec^.Previous <> nil then
Rec^.Previous^.Next := Rec^.Next;
if Rec = FFirst then
FFirst := Rec^.Next;
if Rec = FLastAdded then
FLastAdded := Rec^.Previous;
end;
case Rec^.Data.DataTag of
DATA_TAG_MOTHERBOARDS: Dispose(PDataStructMotherboards(Rec^.LinkedData));
DATA_TAG_CPU: Dispose(PDataStructCPU(Rec^.LinkedData));
DATA_TAG_MEMORY: Dispose(PDataStructMemory(Rec^.LinkedData));
DATA_TAG_HDD: Dispose(PDataStructHDD(Rec^.LinkedData));
DATA_TAG_COOLANT: Dispose(PDataStructCoolant(Rec^.LinkedData));
DATA_TAG_PWR_SUPPLY: Dispose(PDataStructPwrSupply(Rec^.LinkedData));
DATA_TAG_GRAPHICS: Dispose(PDataStructGraphics(Rec^.LinkedData));
DATA_TAG_AUDIO: Dispose(PDataStructAudio(Rec^.LinkedData));
DATA_TAG_OPTICAL_DRIVES: Dispose(PDataStructODD(Rec^.LinkedData));
DATA_TAG_SYS_UNIT: Dispose(PDataStructSysUnit(Rec^.LinkedData));
end;
FreeAndNil(Rec^.Picture);
Dispose(Rec);
if not OnlyDispose then
begin
Dec(FCount);
Dec(FBytesAllocated, Rec^.BytesAlloc);
FChanged := True;
end;
end;
destructor TCurseCatalogEngine.Destroy;
begin
EraseAll;
inherited;
end;
procedure TCurseCatalogEngine.EraseAll;
var
Current, P: PCatalogRecord;
begin
Current := FFirst;
while Current <> nil do
begin
P := Current;
Current := Current^.Next;
Delete(P, True);
end;
ClearSearchResults(FSearchQuery);
FFirst := nil;
FLastAdded := nil;
FCount := 0;
FChanged := True;
FBytesAllocated := 0;
FSorted := True;
end;
procedure TCurseCatalogEngine.FlushToFile;
var
Stream: TFileStream;
PicStream: TMemoryStream;
BufferID: array [0..4] of Char;
Header: TCatalogFileHeader;
P: PCatalogRecord;
Size: Cardinal;
begin
Stream := TFileStream.Create(FFileName, fmCreate);
try
Stream.Size := 0;
BufferID[0] := 'C';
BufferID[1] := 'C';
BufferID[2] := 'D';
BufferID[3] := 'B';
BufferID[4] := 'F';
Stream.WriteBuffer(BufferID, Sizeof(BufferID)); // Write file identification chars
with Header do
begin
Count := FCount;
EditionDate := Now;
end;
Stream.WriteBuffer(Header, Sizeof(TCatalogFileHeader)); // Write file header
P := FFirst;
while P <> nil do
begin
{ Check for attached resource }
if P^.Picture <> nil then
begin
PicStream := TMemoryStream.Create;
try
P^.Picture.SaveToStream(PicStream);
if PicStream.Size > High(Word) then
begin
ShowWarning('Resource is invalid.', Format('The attached resource size' + #32 +
'must be less that 65535 bytes. Attachment will be not saved. Item [ID:%d]: %s %s.',
[P^.ID, P^.Data.Vendor, P^.Data.Model]));
P^.Data.AttachSize := 0;
end
else
P^.Data.AttachSize := PicStream.Size;
finally
FreeAndNil(PicStream);
end;
end
else
P^.Data.AttachSize := 0;
{ Saving data }
Stream.WriteBuffer(P^.Data, Sizeof(TRecCommonData));
case P^.Data.DataTag of
DATA_TAG_MOTHERBOARDS: Size := Sizeof(DATA_STRUCT_MOTHERBOARDS);
DATA_TAG_CPU: Size := Sizeof(DATA_STRUCT_CPU);
DATA_TAG_MEMORY: Size := Sizeof(DATA_STRUCT_MEMORY);
DATA_TAG_HDD: Size := Sizeof(DATA_STRUCT_HDD);
DATA_TAG_COOLANT: Size := Sizeof(DATA_STRUCT_COOLANT);
DATA_TAG_PWR_SUPPLY: Size := Sizeof(DATA_STRUCT_PWR_SUPPLY);
DATA_TAG_GRAPHICS: Size := Sizeof(DATA_STRUCT_GRAPHICS);
DATA_TAG_AUDIO: Size := Sizeof(DATA_STRUCT_AUDIO);
DATA_TAG_OPTICAL_DRIVES: Size := Sizeof(DATA_STRUCT_OPTICAL_DRIVE);
DATA_TAG_SYS_UNIT: Size := Sizeof(DATA_STRUCT_SYS_UNIT);
else
Size := 0;
end;
Stream.WriteBuffer(P^.LinkedData^, Size);
{ Saving attached resource }
if P^.Picture <> nil then P^.Picture.SaveToStream(Stream);
P^.Changed := False;
P := P^.Next;
end;
FChanged := False;
finally
Stream.Free;
end;
end;
procedure TCurseCatalogEngine.Insert(const ADataTag: Integer; const AData: PRecCommonData;
const AExData: Pointer; const Size: Cardinal);
var
P: PCatalogRecord;
begin
New(P);
with P^ do
begin
ID := FNextID;
Data := AData^;
LinkedData := AExData;
Data.DataTag := ADataTag;
Changed := True;
Next := nil;
Previous := nil;
end;
if FFirst <> nil then
begin
FLastAdded^.Next := P;
P^.Previous := FLastAdded;
end
else
FFirst := P;
FLastAdded := P;
Inc(FNextID);
Inc(FCount);
Inc(FBytesAllocated, Size);
FChanged := True;
FSorted := False;
end;
function TCurseCatalogEngine.LocateStruct(const ID: Cardinal): PCatalogRecord;
begin
Result := FFirst;
while Result <> nil do
begin
if Result^.ID = ID then
Exit
else
Result := Result^.Next;
end;
Result := nil;
end;
function TCurseCatalogEngine.RecExists(const Rec: PCatalogRecord): Boolean;
var
P: PCatalogRecord;
begin
Result := True;
P := FFirst;
while P <> nil do
begin
if P = Rec then
Exit;
P := P^.Next;
end;
Result := False;
end;
procedure TCurseCatalogEngine.RestoreFromFile;
var
Stream: TFileStream;
PicStream: TMemoryStream;
BufferID: array [0..4] of Char;
Header: TCatalogFileHeader;
i: Integer;
Data: TRecCommonData;
ExData: Pointer;
begin
if not FileExists(FFileName) then Exit;
Stream := TFileStream.Create(FFileName, fmOpenRead);
try
Stream.Position := 0;
Stream.ReadBuffer(BufferID, Sizeof(BufferID));
if (BufferID[0] <> 'C') or (BufferID[1] <> 'C') or (BufferID[2] <> 'D') or
(BufferID[3] <> 'B') or (BufferID[4] <> 'F') then
begin
raise ECurseCatalogEngine.CreateFmt('Could not load file.' + #13#10 +
'File is not native: %s.', [FFileName]);
Exit;
end;
EraseAll;
Stream.ReadBuffer(Header, Sizeof(TCatalogFileHeader));
FEditionDate := Header.EditionDate;
for i := 1 to Header.Count do
begin
// ExData := nil;
Stream.ReadBuffer(Data, Sizeof(TRecCommonData));
case Data.DataTag of
DATA_TAG_MOTHERBOARDS:
begin
New(PDataStructMotherboards(ExData));
Stream.ReadBuffer(ExData^, Sizeof(DATA_STRUCT_MOTHERBOARDS));
Append(@Data, PDataStructMotherboards(ExData));
end;
DATA_TAG_CPU:
begin
New(PDataStructCPU(ExData));
Stream.ReadBuffer(ExData^, Sizeof(DATA_STRUCT_CPU));
Append(@Data, PDataStructCPU(ExData));
end;
DATA_TAG_MEMORY:
begin
New(PDataStructMemory(ExData));
Stream.ReadBuffer(ExData^, Sizeof(DATA_STRUCT_MEMORY));
Append(@Data, PDataStructMemory(ExData));
end;
DATA_TAG_HDD:
begin
New(PDataStructHDD(ExData));
Stream.ReadBuffer(ExData^, Sizeof(DATA_STRUCT_HDD));
Append(@Data, PDataStructHDD(ExData));
end;
DATA_TAG_COOLANT:
begin
New(PDataStructCoolant(ExData));
Stream.ReadBuffer(ExData^, Sizeof(DATA_STRUCT_COOLANT));
Append(@Data, PDataStructCoolant(ExData));
end;
DATA_TAG_PWR_SUPPLY:
begin
New(PDataStructPwrSupply(ExData));
Stream.ReadBuffer(ExData^, Sizeof(DATA_STRUCT_PWR_SUPPLY));
Append(@Data, PDataStructPwrSupply(ExData));
end;
DATA_TAG_GRAPHICS:
begin
New(PDataStructGraphics(ExData));
Stream.ReadBuffer(ExData^, Sizeof(DATA_STRUCT_GRAPHICS));
Append(@Data, PDataStructGraphics(ExData));
end;
DATA_TAG_AUDIO:
begin
New(PDataStructAudio(ExData));
Stream.ReadBuffer(ExData^, Sizeof(DATA_STRUCT_AUDIO));
Append(@Data, PDataStructAudio(ExData));
end;
DATA_TAG_OPTICAL_DRIVES:
begin
New(PDataStructODD(ExData));
Stream.ReadBuffer(ExData^, Sizeof(DATA_STRUCT_OPTICAL_DRIVE));
Append(@Data, PDataStructODD(ExData));
end;
DATA_TAG_SYS_UNIT:
begin
New(PDataStructSysUnit(ExData));
Stream.ReadBuffer(ExData^, Sizeof(DATA_STRUCT_SYS_UNIT));
Append(@Data, PDataStructSysUnit(ExData));
end;
else
raise ECurseCatalogEngine.Create('Oops! Invalid data tag. Terminated.');
end;
{ Load attached resource }
if Data.AttachSize > 0 then
begin
FLastAdded^.Picture := TPngImage.Create;
try
PicStream := TMemoryStream.Create;
try
PicStream.CopyFrom(Stream, Data.AttachSize);
PicStream.Position := 0;
FLastAdded^.Picture.LoadFromStream(PicStream);
finally
PicStream.Free;
end;
except
FreeAndNil(FLastAdded^.Picture);
EraseAll;
ShowError('Invalid resource.', Format('An exception has raised when loading' + #32 +
'catalog "%s". Invalid PNG resource attached to record [%d].', [FFileName, i]));
Exit;
end;
end;
end;
FChanged := False;
FSorted := False;
finally
Stream.Free;
end;
end;
procedure TCurseCatalogEngine.Search;
procedure _AppendList(const ASI: TSearchItem; var ASQ: TSearchQuery);
var
P,Q: PSearchItem;
begin
P := ASQ.Result;
if P <> nil then
begin
while P^.Next <> nil do
P := P^.Next;
end;
New(Q);
Q^ := ASI;
Q^.Next := nil;
if P <> nil then
P^.Next := Q
else
ASQ.Result := Q;
Inc(ASQ.Count);
end;
var
SQ: ^TSearchQuery;
SI: TSearchItem;
S1, S2: String;
Matching: Boolean;
P: PCatalogRecord;
F: TSearchViewingField;
Price: Integer;
begin
SQ := @FSearchQuery;
ClearSearchResults(FSearchQuery);
if not SQ^.CaseSensitive then
S1 := AnsiUpperCase(SQ^.Text)
else
S1 := SQ^.Text;
if vfPrice in SQ^.ViewingFields then
if not TryStrToInt(SQ^.Text, Price) then
raise ECurseCatalogEngine.Create('Oops! Price is not valid in search query. Canceled.');
P := FFirst;
while P <> nil do
begin
Matching := False;
SI.Item := P;
SI.MatchingFields := [];
if not (vfPrice in SQ^.ViewingFields) then
begin
for F := vfVendor to vfNotes do
begin
{$WARNINGS OFF}
case F of
vfVendor: S2 := P^.Data.Vendor;
vfModel: S2 := P^.Data.Model;
vfProductID: S2 := P^.Data.ProductID;
vfNotes: S2 := P^.Data.Notes;
end;
{$WARNINGS ON}
if not SQ^.CaseSensitive then
S2 := AnsiUpperCase(S2);
if SQ^.WholeMatch then
Matching := Matching or (S1 = S2)
else
Matching := Matching or (Pos(S1,S2) > 0);
if Matching then
SI.MatchingFields := SI.MatchingFields + [F];
end;
end
else
if (StrToInt(SQ^.Text) >= P^.Data.MinPrice) and
(StrToInt(SQ^.Text) <= P^.Data.MaxPrice) then
Matching := True;
if Matching then _AppendList(SI, FSearchQuery);
P := P^.Next;
end;
end;
procedure TCurseCatalogEngine.SetSearchQuery(const Value: TSearchQuery);
begin
ClearSearchResults(FSearchQuery);
FSearchQuery := Value;
end;
procedure TCurseCatalogEngine.Sort(const SortByField: TSortingField);
var
Current: PCatalogRecord;
Ptrs: array of PCatalogRecord;
Index: Integer;
{ Sort }
K: Integer;
J: Integer;
Temp: PCatalogRecord;
S1, S2: String;
W: Boolean;
begin
FSorted := True;
if FCount = 0 then Exit;
SetLength(Ptrs, FCount);
{ Filling the array with pointers }
Current := FFirst;
for Index := Low(Ptrs) to High(Ptrs) do
begin
Ptrs[Index] := Current;
Current := Current^.Next;
end;
{ Sorting array with "floating" bubble sort }
{$WARNINGS OFF}
Index := Low(Ptrs) + 1;
while Index <= High(Ptrs) do
begin
K := Index;
J := High(Ptrs);
while J >= Index do
begin
W := False;
case SortByField of
sfNone:
begin
W := Ptrs[J]^.ID < Ptrs[J-1]^.ID;
end;
sfDataTag: // Sorting by data tag and name
begin
S1 := Ptrs[J]^.Data.Vendor + #32 + Ptrs[J]^.Data.Model;
S2 := Ptrs[J-1]^.Data.Vendor + #32 + Ptrs[J-1]^.Data.Model;
W := Ptrs[J]^.Data.DataTag < Ptrs[J-1]^.Data.DataTag;
W := W and not (CompareText(S1, S2) < 0);
end;
sfName:
begin
S1 := Ptrs[J]^.Data.Vendor + #32 + Ptrs[J]^.Data.Model;
S2 := Ptrs[J-1]^.Data.Vendor + #32 + Ptrs[J-1]^.Data.Model;
W := CompareText(S1, S2) < 0;
end;
sfPrice:
begin
W := Ptrs[J]^.Data.MinPrice < Ptrs[J-1]^.Data.MinPrice;
S1 := Ptrs[J]^.Data.Vendor + #32 + Ptrs[J]^.Data.Model;
S2 := Ptrs[J-1]^.Data.Vendor + #32 + Ptrs[J-1]^.Data.Model;
W := W and not (CompareText(S1, S2) < 0);
end;
sfReleaseDate:
begin
W := Ptrs[J]^.Data.ReleaseYear < Ptrs[J-1]^.Data.ReleaseYear;
W := W and (Ptrs[J]^.Data.ReleaseQuater < Ptrs[J-1]^.Data.ReleaseQuater);
S1 := Ptrs[J]^.Data.Vendor + #32 + Ptrs[J]^.Data.Model;
S2 := Ptrs[J-1]^.Data.Vendor + #32 + Ptrs[J-1]^.Data.Model;
W := W and not (CompareText(S1, S2) < 0);
end;
end;
if W then
begin
Temp := Ptrs[J-1];
Ptrs[J-1] := Ptrs[J];
Ptrs[J] := Temp;
K := J;
end;
Dec(J);
end;
Index := K + 1;
end;
{$WARNINGS ON}
{ Reassigning pointers }
for Index := Low(Ptrs) to High(Ptrs) do
begin
if Index <> Low(Ptrs) then
Ptrs[Index]^.Previous := Ptrs[Index-1]
else
Ptrs[Index]^.Previous := nil;
if Index <> High(Ptrs) then
Ptrs[Index]^.Next := Ptrs[Index+1]
else
Ptrs[Index]^.Next := nil;
end;
FFirst := Ptrs[Low(Ptrs)];
FLastAdded := Ptrs[High(Ptrs)];
SetLength(Ptrs, 0);
FChanged := True;
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2017 Vincent Parrett }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.Tests.Assert;
interface
{$I ..\Source\DUnitX.inc}
uses
DUnitX.TestFramework;
type
{$M+}
[TestFixture]
TTestsAssert = class
published
[Test]
procedure Pass_Throws_ETestPass_Exception;
[Test]
procedure Pass_Throws_ETestPass_Exception_With_Message;
[Test]
procedure Fail_Throws_ETestFailure_Exception;
[Test]
procedure Fail_Throws_ETestFailure_Exception_With_Message;
[Test]
procedure Fail_Throws_ETestFailure_Exception_With_Return_Address_Reference;
[Test]
procedure Fail_Throws_ETestFailure_Exception_With_Caller_Address_Reference;
[Test]
procedure AreEqual_String_Throws_No_Exception_When_Values_Are_Equal;
[Test]
procedure AreEqual_Integer_Throws_No_Exception_When_Values_Are_Equal;
[Test]
procedure AreEqual_Integer_Throws_ETestFailure_When_Values_Are_NotEqual;
[Test]
procedure AreEqual_Extended_Throws_No_Exception_When_Values_Are_Equal;
[Test]
procedure AreEqual_Extended_Throws_ETestFailure_When_Values_Are_NotEqual;
[Test]
procedure AreEqual_Double_Throws_No_Exception_When_Values_Are_Equal;
[Test]
procedure AreEqual_Double_Throws_ETestFailure_When_Values_Are_NotEqual;
[Test]
procedure AreEqual_Currency_Throws_ETestFailure_When_Values_Are_NotEqual;
[Test]
procedure AreEqual_GUID_Throws_No_Exception_When_Values_Are_Equal;
[Test]
procedure AreEqual_GUID_Throws_ETestFailure_When_Values_Are_NotEqual;
[Test]
procedure AreEqual_Stream_Throws_No_Exception_When_Values_Are_Equal;
[Test]
procedure AreEqual_Stream_Throws_ETestFailure_When_Values_Are_NotEqual;
[Test]
procedure AreEqual_TClass_Throws_No_Exception_When_Classes_Are_Equal;
[Test]
procedure AreEqual_TClass_Throws_ETestFailure_When_Classes_Are_NotEqual;
[Test]
[TestCase('Empty', ',')]
[TestCase('CR', #13','#13)]
[TestCase('Simple','abc,abc')]
[TestCase('Ignore case simple','abc,ABC,true')]
[TestCase('Ignore case complex','LoReM iPsUm DoLoR sIt AmEt,lOrEm IpSuM dOlOr SiT aMeT,true')]
procedure NoDiff_Throws_No_Exception_When_Strings_Are_Equal(const A, B: string; AIgnoreCase:boolean = false);
[TestCase('Length',
' '#8',' +
' ,' +
'Difference at position 2: ['' ''#8] does not match []',
',', false)]
[TestCase('First Char',
'Lorem ipsum,' +
'lorem ipsum,' +
'Difference at position 1: [''Lorem ipsu''] does not match [''lorem ipsu'']',
',', false)]
[TestCase('Last Char',
'Lorem ipsum,' +
'Lorem ipsuM,' +
'Difference at position 11: [''m''] does not match [''M'']',
',', false)]
[TestCase('A sub B',
'Lorem ip,' +
'Lorem ipsum,' +
'Difference at position 9: [] does not match [''sum'']',
',', false)]
[TestCase('B sub A',
'Lorem ipsum,' +
'Lorem ip,' +
'Difference at position 9: [''sum''] does not match []',
',', false)]
[TestCase('Tab vs Space',
'lorem ipsum,' +
'lorem'#9'ipsum,' +
'Difference at position 6: ['' ipsum''] does not match [#9''ipsum'']',
',', false)]
[TestCase('Different Spaces',
'lorem ipsum,' +
'lorem ipsum,' +
'Difference at position 7: [''ipsum''] does not match ['' ipsum'']',
',', false)]
[TestCase('Capitalization',
'lorem ipsum,'+
'lorem Ipsum,' +
'Difference at position 7: [''ipsum''] does not match [''Ipsum'']',
',', false)]
[TestCase('CR vs LF',
#13',' +
#10',' +
'Difference at position 1: [#13] does not match [#10] Linebreak style,Linebreak style',
',', false)]
[TestCase('TAB vs Space',
'lorem'#9'ipsum,' +
'lorem ipsum,' +
'Difference at position 6: [#9''ipsum''] does not match ['' ipsum'']',
',', false)]
procedure NoDiff_Throws_ETestFailure_When_Strings_Are_NotEqual(const A, B, AException, AMessage : string);
[Test]
procedure AreEqual_TStrings_Throws_No_Exception_When_Strings_Are_Equal;
[Test]
procedure AreEqual_TStrings_Throws_ETestFailure_When_Strings_Are_NotEqual;
{$IFNDEF DELPHI_XE_DOWN}
[Test]
procedure AreEqual_T_Throws_No_Exception_When_Interfaces_Are_Equal;
[Test]
procedure AreEqual_T_Throws_ETestFailure_When_Interfaces_Are_NotEqual;
[Test]
procedure AreEqual_T_Throws_ETestFailure_When_Interfaces_Are_Nil;
[Test]
procedure AreEqual_T_Throws_No_Exception_When_Objects_Are_Equal;
[Test]
procedure AreEqual_T_Throws_ETestFailure_When_Objects_Are_NotEqual;
[Test]
procedure AreEqual_T_Throws_ETestFailure_When_Objects_Are_Nil;
[Test]
procedure AreEqual_Array_T_Throws_No_Exception_When_Arrays_Are_Equal;
[Test]
procedure AreEqual_Array_T_Throws_ETestFailure_When_Arrays_Are_Not_Equal;
{$ENDIF}
[Test]
procedure AreEqualMemory_Throws_No_Exception_When_Pointers_Are_Equal;
[Test]
procedure AreEqualMemory_Throws_ETestFailure_When_Pointers_Are_NotEqual;
[Test]
procedure AreEqual_Throws_No_Exception_When_Values_Are_Exactly_Equal;
[Test]
procedure AreNotEqual_Integer_Throws_No_Exception_When_Values_Are_NotEqual;
[Test]
procedure AreNotEqual_Integer_Throws_Exception_When_Values_Are_Equal;
[Test]
procedure AreNotEqual_Currency_Throws_Exception_When_Values_Are_Equal;
[Test]
procedure AreNotEqual_GUID_Throws_No_Exception_When_Values_Are_NotEqual;
[Test]
procedure AreNotEqual_GUID_Throws_Exception_When_Values_Are_Equal;
[Test]
procedure WillRaise_Without_Exception_Class_Will_Capture_Any_Exception;
[Test]
procedure WillRaiseWithMessage_Exception_And_Message_Will_Check_ExceptionClass_And_Exception_Message;
[Test]
procedure WillRaiseWithMessage_Without_Exception_Class_And_Message_Will_Capture_Any_Exception;
[Test]
procedure WillRaiseWithMessage_Without_Exception_Class_With_Message_Will_Capture_Any_Exception_With_Message;
[Test]
procedure WillRaiseWithMessage_Exception_Not_Thrown_Throws_ETestFailure_Exception;
[Test]
procedure WillRaiseDescendant_With_NonDescendingClass;
[Test]
procedure WillRaiseDescendant_With_DescendingClass;
[Test]
procedure WillRaiseDescendant_With_ExactClass;
[Test]
procedure WillRaiseAny;
[Test]
procedure WillRaiseAny_NoExecption;
[Test]
procedure WillNotRaise_With_ExactClass_Positive;
[Test]
procedure WillNotRaise_With_ExactClass_Negative;
[Test]
procedure WillNotRaise_With_DescendingClass_Positive;
[Test]
procedure WillNotRaise_With_DescendingClass_Negative;
[Test]
procedure WillNotRaise_With_NoClass;
[Test]
procedure Test_Implements_Will_Fail_If_Not_Implemented;
[Test]
procedure Test_Implements_Will_Pass_If_Implemented;
[Test]
procedure Test_AreSameOnSameObjectWithDifferentInterfaces_No_Exception;
[Test]
procedure Test_AreNotSameOnSameObjectWithDifferentInterfaces_Throws_Exception;
{$IFDEF DELPHI_XE_UP}
[Test]
procedure Contains_ArrayOfT_Throws_No_Exception_When_Value_In_Array;
[Test]
procedure Contains_ArrayOfT_Throws_Exception_When_Value_Not_In_Array;
[Test]
procedure DoesNotContain_ArrayOfT_Throws_No_Exception_When_Value_Not_In_Array;
[Test]
procedure DoesNotContain_ArrayOfT_Throws_Exception_When_Value_In_Array;
{$ENDIF}
[Test]
[TestCase( 'substring', 'a str,a string,false' )]
[TestCase( 'substring - case sensitive', 'a str,a string,true' )]
procedure StartsWith_SubString_Is_At_The_Start_Of_String(const subString, theString: string; caseSensitive: boolean);
[Test]
[TestCase( 'empty substring', ',a string,false' )]
[TestCase( 'empty substring - case sensitive', ',a string,true' )]
[TestCase( 'empty string', 'substring,,false' )]
[TestCase( 'empty string - case sensitive', 'substring,,true' )]
[TestCase( 'at end of string', 'substring,at the end if the substring,false' )]
[TestCase( 'at end of string - case sensitive', 'substring,at the end if the substring,true' )]
[TestCase( 'in the middle of string', 'substring,the substring is in the middle,false' )]
[TestCase( 'in the middle of string - case sensitive', 'substring,the substring is in the middle,true' )]
[TestCase( 'not in the string', 'something else,the substring is not here,false' )]
[TestCase( 'not in the string - case sensitive', 'something else,the substring is not here,true' )]
procedure StartsWith_SubString_Is_Not_At_Start( const subString, theString: string; caseSensitive: boolean );
[Test]
[TestCase( 'substring', 'ing,a string,false' )]
[TestCase( 'substring - case sensitive', 'ing,a string,true' )]
procedure EndsWith_SubString_Is_At_The_End_Of_String( const subString, theString: string; caseSensitive: boolean );
[Test]
[TestCase( 'empty substring', ',a string,false' )]
[TestCase( 'empty substring - case sensitive', ',a string,true' )]
[TestCase( 'empty string', 'substring,,false' )]
[TestCase( 'empty string - case sensitive', 'substring,,true' )]
[TestCase( 'at start of string', 'at the,at the end if the substring,false' )]
[TestCase( 'at start of string - case sensitive', 'at the,at the end if the substring,true' )]
[TestCase( 'in the middle of string', 'substring,the substring is in the middle,false' )]
[TestCase( 'in the middle of string - case sensitive', 'substring,the substring is in the middle,true' )]
[TestCase( 'not in the string', 'something else,the substring is not here,false' )]
[TestCase( 'not in the string - case sensitive', 'something else,the substring is not here,true' )]
procedure EndsWith_SubString_Is_Not_At_End( const subString, theString: string; caseSensitive: boolean );
[Test]
procedure IgnoreCaseDefault;
{$IFDEF SUPPORTS_REGEX}
[Test]
[TestCase('GUID with dash', '[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12},C687683F-F25B-4F9A-A231-31C52253B6A1')]
[TestCase('GUID without dash', '[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12},C687683FF25B4F9AA23131C52253B6A1')]
procedure IsMatch_True_Will_Not_Raise(const regexPattern, theString: string);
[Test]
[TestCase('GUID with dash', '[0-9A-F]{8}[-]([0-9A-F]{4}[-]){3}[0-9A-F]{12},C687683F-F25B-4F9A-A231-31C52253B6A#')]
[TestCase('GUID without dash', '[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12},C687683FF25B4F9AA23131C52253B6A#')]
procedure IsMatch_False_Will_Raise_ETestFailure(const regexPattern, theString: string);
[Test]
procedure WillRaiseWithMessageRegex;
{$ENDIF}
procedure WillNotRaiseWithMessage_NilExceptionParam_NoExceptionMessage_WillRaise;
procedure WillNotRaiseWithMessage_MatchingExceptionParam_MatchingExceptionMessage_WillRaise;
procedure WillNotRaiseWithMessage_MatchingExceptionParam_NoExceptionMessage_WillRaise;
procedure WillNotRaiseWithMessage_MatchingExceptionParam_NonMatchingExceptionMessage_WillNotRaise;
procedure WillNotRaiseWithMessage_NilExceptionParam_MatchingExceptionMessage_WillRaise;
procedure WillNotRaiseWithMessage_NilExceptionParam_NonMatchingExceptionMessage_WillNotRaise;
procedure WillNotRaiseWithMessage_NonMatchingExceptionParam_MatchingExceptionMessage_WillNotRaise;
procedure WillNotRaiseWithMessage_NonMatchingExceptionParam_NoExceptionMessage_WillNotRaise;
procedure WillNotRaiseWithMessage_NonMatchingExceptionParam_NonMatchingExceptionMessage_WillNotRaise;
[Test]
procedure CheckExpectation_Not_Empty_String_Will_Raise;
end;
implementation
uses
{$IFDEF USE_NS}
System.SysUtils,
System.Classes,
{$ELSE}
SysUtils,
Classes,
{$ENDIF}
DUnitX.Exceptions,
DUnitX.Assert;
type
{$M+}
IMockInterface = interface
['{8DB1A216-0E95-4241-9522-C50DF99AFB71}']
procedure Stub;
end;
{$M-}
TMockClassOne = class(TObject)
end;
TMockClassTwo = class(TObject)
end;
IAmImplemented = interface
['{4B503CDD-6262-403C-BF68-5D5DE01C3B13}']
end;
TImplemented = class(TInterfacedObject,IAmImplemented)
end;
TestExceptionOne = class(Exception);
TestExceptionTwo = class(Exception);
//Mask to override the default AssertEx in DUnitX.TestFramework
Assert = class(DUnitX.Assert.Assert);
procedure TTestsAssert.Fail_Throws_ETestFailure_Exception;
begin
Assert.WillRaise(
procedure
begin
Assert.Fail
end, ETestFailure);
end;
procedure TTestsAssert.Fail_Throws_ETestFailure_Exception_With_Caller_Address_Reference;
var
MyProc : TTestLocalMethod;
begin
MyProc := procedure
begin
Assert.WillRaise(
procedure
begin
Assert.Fail;
//We will raise at this point, when we return.
end, ETestFailure);
end;
Assert.WillNotRaise(MyProc, ETestFailure);
end;
procedure TTestsAssert.Fail_Throws_ETestFailure_Exception_With_Message;
const
EXPECTED_EXCEPTION_MSG = 'Failed Message';
begin
Assert.WillRaise(
procedure
begin
Assert.Fail(EXPECTED_EXCEPTION_MSG);
end, ETestFailure, EXPECTED_EXCEPTION_MSG);
end;
procedure TTestsAssert.Fail_Throws_ETestFailure_Exception_With_Return_Address_Reference;
var
MyProc : TTestLocalMethod;
begin
MyProc := procedure
begin
Assert.WillNotRaise(
procedure
begin
Assert.Fail('', @MyProc);
//We will not raise internally, as we are passing the address of our caller
end, ETestFailure);
//We will raise it here, when MyProc returns.
end;
Assert.WillRaise(MyProc, ETestFailure);
MyProc := nil;
end;
procedure TTestsAssert.IgnoreCaseDefault;
const
cStr1 = 'String';
cStr2 = 'STRING';
var
OldVal: Boolean;
begin
//Don't assume start value
OldVal := Assert.IgnoreCaseDefault;
try
Assert.IgnoreCaseDefault := True;
Assert.WillNotRaiseAny(procedure begin Assert.AreEqual(cStr1, cStr2) end);
Assert.WillNotRaiseAny(procedure begin Assert.StartsWith(cStr1, cStr2) end);
Assert.WillNotRaiseAny(procedure begin Assert.EndsWith(cStr1, cStr2) end);
Assert.WillRaise(procedure begin Assert.AreNotEqual(cStr1, cStr2) end, ETestFailure);
Assert.IgnoreCaseDefault := False;
Assert.WillRaise(procedure begin Assert.AreEqual(cStr1, cStr2) end, ETestFailure);
Assert.WillRaise(procedure begin Assert.StartsWith(cStr1, cStr2) end, ETestFailure);
Assert.WillRaise(procedure begin Assert.EndsWith(cStr1, cStr2) end, ETestFailure);
Assert.WillNotRaiseAny(procedure begin Assert.AreNotEqual(cStr1, cStr2) end);
finally
Assert.IgnoreCaseDefault := OldVal;
end;
end;
procedure TTestsAssert.NoDiff_Throws_ETestFailure_When_Strings_Are_NotEqual(const A, B, AException, AMessage : string);
begin
Assert.WillRaiseWithMessage(procedure
begin
Assert.NoDiff(A, B, AMessage);
end, ETestFailure, AException);
end;
procedure TTestsAssert.NoDiff_Throws_No_Exception_When_Strings_Are_Equal(const A, B: string; AIgnoreCase:boolean = false);
begin
Assert.WillNotRaise(procedure
begin
Assert.NoDiff(A,B,AIgnoreCase);
end);
end;
procedure TTestsAssert.Pass_Throws_ETestPass_Exception;
begin
Assert.WillRaise(
procedure
begin
Assert.Pass;
end, ETestPass);
end;
procedure TTestsAssert.Pass_Throws_ETestPass_Exception_With_Message;
const
EXPECTED_EXCEPTION_MSG = 'Passing Message';
begin
Assert.WillRaise(
procedure
begin
Assert.Pass(EXPECTED_EXCEPTION_MSG);
end, ETestPass, EXPECTED_EXCEPTION_MSG);
end;
procedure TTestsAssert.Test_Implements_Will_Fail_If_Not_Implemented;
var
obj : IInterface;
res : IAmImplemented;
begin
obj := TInterfacedObject.Create;
Assert.WillRaise(
procedure
begin
res := Assert.Implements<IAmImplemented>(obj);
end,
ETestFailure);
end;
procedure TTestsAssert.Test_Implements_Will_Pass_If_Implemented;
var
obj : IInterface;
res : IAmImplemented;
begin
obj := TImplemented.Create;
Assert.WillNotRaiseAny(
procedure
begin
res := Assert.Implements<IAmImplemented>(obj);
end);
Assert.IsNotNull(res);
end;
procedure TTestsAssert.WillNotRaiseWithMessage_NilExceptionParam_NoExceptionMessage_WillRaise;
begin
Assert.WillRaise(
procedure
begin
Assert.WillNotRaiseWithMessage(
procedure
begin
raise Exception.Create('Test');
end);
end);
end;
procedure TTestsAssert.WillNotRaiseWithMessage_NilExceptionParam_MatchingExceptionMessage_WillRaise;
begin
Assert.WillRaise(
procedure
begin
Assert.WillNotRaiseWithMessage(
procedure
begin
raise Exception.Create('Test');
end, nil, 'Test');
end);
end;
procedure TTestsAssert.WillNotRaiseWithMessage_NilExceptionParam_NonMatchingExceptionMessage_WillNotRaise;
begin
Assert.WillNotRaise(
procedure
begin
Assert.WillNotRaiseWithMessage(
procedure
begin
raise Exception.Create('Test');
end, nil, 'Different Exception Message');
end);
end;
procedure TTestsAssert.WillNotRaiseWithMessage_MatchingExceptionParam_NoExceptionMessage_WillRaise;
begin
Assert.WillRaise(
procedure
begin
Assert.WillNotRaiseWithMessage(
procedure
begin
raise TestExceptionOne.Create('Test');
end, TestExceptionOne);
end);
end;
procedure TTestsAssert.WillNotRaiseWithMessage_MatchingExceptionParam_MatchingExceptionMessage_WillRaise;
begin
Assert.WillRaise(
procedure
begin
Assert.WillNotRaiseWithMessage(
procedure
begin
raise TestExceptionOne.Create('Test');
end, TestExceptionOne, 'Test');
end);
end;
procedure TTestsAssert.WillNotRaiseWithMessage_MatchingExceptionParam_NonMatchingExceptionMessage_WillNotRaise;
begin
Assert.WillNotRaise(
procedure
begin
Assert.WillNotRaiseWithMessage(
procedure
begin
raise TestExceptionOne.Create('Test');
end, TestExceptionOne, 'Different Exception Message');
end);
end;
procedure TTestsAssert.WillNotRaiseWithMessage_NonMatchingExceptionParam_NoExceptionMessage_WillNotRaise;
begin
Assert.WillNotRaise(
procedure
begin
Assert.WillNotRaiseWithMessage(
procedure
begin
raise TestExceptionOne.Create('Test');
end, TestExceptionTwo);
end);
end;
procedure TTestsAssert.WillNotRaiseWithMessage_NonMatchingExceptionParam_MatchingExceptionMessage_WillNotRaise;
begin
Assert.WillNotRaise(
procedure
begin
Assert.WillNotRaiseWithMessage(
procedure
begin
raise TestExceptionOne.Create('Test');
end, TestExceptionTwo, 'Test');
end);
end;
procedure TTestsAssert.WillNotRaiseWithMessage_NonMatchingExceptionParam_NonMatchingExceptionMessage_WillNotRaise;
begin
Assert.WillNotRaise(
procedure
begin
Assert.WillNotRaiseWithMessage(
procedure
begin
raise TestExceptionOne.Create('Test');
end, TestExceptionTwo, 'Different Exception Message');
end);
end;
procedure TTestsAssert.WillNotRaise_With_DescendingClass_Negative;
begin
Assert.WillRaise(
procedure
begin
Assert.WillNotRaiseDescendant(
procedure
begin
raise EFilerError.Create('Test');
end,
EStreamError);
end,
ETestFailure);
end;
procedure TTestsAssert.WillNotRaise_With_DescendingClass_Positive;
begin
Assert.WillNotRaiseDescendant(
procedure
begin
raise Exception.Create('Test');
end,
EStreamError);
end;
procedure TTestsAssert.WillNotRaise_With_ExactClass_Negative;
const
EXPECTED_EXCEPTION_MSG = 'Passing Message';
begin
Assert.WillRaise(
procedure
begin
Assert.WillNotRaise(
procedure
begin
raise EStreamError.Create('Error Message');
end,
EStreamError,EXPECTED_EXCEPTION_MSG);
end,
ETestFailure,
EXPECTED_EXCEPTION_MSG);
end;
procedure TTestsAssert.WillNotRaise_With_ExactClass_Positive;
begin
Assert.WillNotRaise(
procedure
begin
// Don't raise an exception we are looking for.
raise Exception.Create('Error Message');
end,
EStreamError,'');
end;
procedure TTestsAssert.WillNotRaise_With_NoClass;
const
EXPECTED_EXCEPTION_MSG = 'Passing Message';
begin
Assert.WillRaise(
procedure
begin
Assert.WillNotRaise(
procedure
begin
// Raise an exception
raise Exception.Create('Error Message');
end);
end,
ETestFailure,
EXPECTED_EXCEPTION_MSG);
end;
procedure TTestsAssert.WillRaiseAny;
begin
Assert.WillRaiseAny(
procedure
begin
raise EAbort.Create('Test');
end);
end;
procedure TTestsAssert.WillRaiseAny_NoExecption;
const
EXPECTED_EXCEPTION_MSG = 'Failed Message';
begin
Assert.WillRaise(
procedure
begin
Assert.WillRaiseAny(
procedure
begin
// Do nothing on purpose.
end
);
end, ETestFailure, EXPECTED_EXCEPTION_MSG);
end;
procedure TTestsAssert.WillRaiseDescendant_With_DescendingClass;
const
EXPECTED_EXCEPTION_MSG = 'Failed Message';
begin
Assert.WillRaiseDescendant(
procedure
begin
raise EFilerError.Create('Test');
end,
EStreamError,EXPECTED_EXCEPTION_MSG);
end;
procedure TTestsAssert.WillRaiseDescendant_With_ExactClass;
const
EXPECTED_EXCEPTION_MSG = 'Failed Message';
begin
Assert.WillRaiseDescendant(
procedure
begin
raise EFilerError.Create('Test');
end,
EFilerError,EXPECTED_EXCEPTION_MSG);
end;
procedure TTestsAssert.WillRaiseDescendant_With_NonDescendingClass;
const
EXPECTED_EXCEPTION_MSG = 'Failed Message';
begin
Assert.WillRaise(
procedure
begin
Assert.WillRaiseDescendant(
procedure
begin
raise Exception.Create('Test');
end,
EStreamError,EXPECTED_EXCEPTION_MSG);
end,
ETestFailure,EXPECTED_EXCEPTION_MSG);
end;
procedure TTestsAssert.WillRaiseWithMessage_Exception_And_Message_Will_Check_ExceptionClass_And_Exception_Message;
const
EXPECTED_EXCEPTION_MSG = 'Passing Message';
begin
Assert.WillRaiseWithMessage(
procedure
begin
Assert.Pass(EXPECTED_EXCEPTION_MSG);
end, ETestPass, EXPECTED_EXCEPTION_MSG);
end;
procedure TTestsAssert.WillRaiseWithMessage_Exception_Not_Thrown_Throws_ETestFailure_Exception;
const
EXPECTED_EXCEPTION_MSG = 'Failed Message';
begin
Assert.WillRaise(
procedure
begin
Assert.WillRaiseWithMessage(nil, ETestFailure);
end, ETestFailure, EXPECTED_EXCEPTION_MSG);
end;
procedure TTestsAssert.WillRaiseWithMessage_Without_Exception_Class_And_Message_Will_Capture_Any_Exception;
begin
Assert.WillRaiseWithMessage(
procedure
begin
raise Exception.Create('Pass');
end);
end;
procedure TTestsAssert.WillRaiseWithMessage_Without_Exception_Class_With_Message_Will_Capture_Any_Exception_With_Message;
const
EXPECTED_EXCEPTION_MSG = 'Passing Message';
begin
Assert.WillRaiseWithMessage(
procedure
begin
raise Exception.Create(EXPECTED_EXCEPTION_MSG);
end, nil, EXPECTED_EXCEPTION_MSG);
end;
procedure TTestsAssert.WillRaise_Without_Exception_Class_Will_Capture_Any_Exception;
begin
Assert.WillRaise(
procedure
begin
raise Exception.Create('Test')
end);
end;
procedure TTestsAssert.AreEqualMemory_Throws_ETestFailure_When_Pointers_Are_NotEqual;
begin
Assert.Pass;
end;
procedure TTestsAssert.AreEqualMemory_Throws_No_Exception_When_Pointers_Are_Equal;
var
mock : IInterface;
begin
mock := TInterfacedObject.Create();
Assert.WillNotRaise(
procedure
begin
Assert.AreEqualMemory(@mock, @mock, SizeOf(mock));
end, ETestFailure);
end;
procedure TTestsAssert.AreEqual_Double_Throws_ETestFailure_When_Values_Are_NotEqual;
const
ACTUAL_DOUBLE : double = 1.19E20;
EXPECTED_DOUBLE : double = 1.18E20;
TOLERANCE_DOUBLE : double = 0.001E20;
begin
Assert.WillRaise(
procedure
begin
Assert.AreEqual(ACTUAL_DOUBLE, EXPECTED_DOUBLE, TOLERANCE_DOUBLE);
end, ETestFailure, Format('[%e] with in [%e] from [%e]', [ACTUAL_DOUBLE, TOLERANCE_DOUBLE, EXPECTED_DOUBLE]));
end;
procedure TTestsAssert.AreEqual_Currency_Throws_ETestFailure_When_Values_Are_NotEqual;
const
ACTUAL_CURRENCY : Currency = 1.34;
EXPECTED_CURRENCY : Currency = 1.35;
begin
Assert.WillRaise(
procedure
begin
Assert.AreEqual(ACTUAL_CURRENCY, EXPECTED_CURRENCY);
end, ETestFailure, Format('[%e] not equal to [%e]', [ACTUAL_CURRENCY, EXPECTED_CURRENCY]));
end;
procedure TTestsAssert.AreEqual_Double_Throws_No_Exception_When_Values_Are_Equal;
const
ACTUAL_DOUBLE : double = 1.19E20;
EXPECTED_DOUBLE : double = 1.18E20;
TOLERANCE_DOUBLE : double = 0.011E20;
begin
Assert.WillNotRaise(
procedure
begin
Assert.AreEqual(ACTUAL_DOUBLE, EXPECTED_DOUBLE, TOLERANCE_DOUBLE);
end, Exception);
end;
procedure TTestsAssert.AreEqual_Extended_Throws_ETestFailure_When_Values_Are_NotEqual;
const
ACTUAL_EXTENDED : extended = 1.19E20;
EXPECTED_EXTENDED : extended = 1.18E20;
TOLERANCE_EXTENDED : extended = 0.001E20;
begin
Assert.WillRaise(
procedure
begin
Assert.AreEqual(ACTUAL_EXTENDED, EXPECTED_EXTENDED, TOLERANCE_EXTENDED);
end, ETestFailure, Format('[%e] with in [%e] from [%e]', [ACTUAL_EXTENDED, TOLERANCE_EXTENDED, EXPECTED_EXTENDED]));
end;
procedure TTestsAssert.AreEqual_Extended_Throws_No_Exception_When_Values_Are_Equal;
const
ACTUAL_EXTENDED : extended = 1.19E20;
EXPECTED_EXTENDED : extended = 1.18E20;
TOLERANCE_EXTENDED : extended = 0.011E20;
begin
Assert.WillNotRaise(
procedure
begin
Assert.AreEqual(ACTUAL_EXTENDED, EXPECTED_EXTENDED, TOLERANCE_EXTENDED);
end, Exception);
end;
procedure TTestsAssert.AreEqual_GUID_Throws_ETestFailure_When_Values_Are_NotEqual;
const
EXPECTED_GUID: TGUID = (D1: 0; D2: 0; D3: 0; D4: (0, 0, 0, 0, 0, 0, 0, 0));
ACTUAL_GUID: TGUID = (D1: 1; D2: 1; D3: 1; D4: (1, 1, 1, 1, 1, 1, 1, 1));
begin
Assert.WillRaise(
procedure
begin
Assert.AreEqual(EXPECTED_GUID, ACTUAL_GUID);
end, ETestFailure);
end;
procedure TTestsAssert.AreEqual_GUID_Throws_No_Exception_When_Values_Are_Equal;
const
EXPECTED_GUID: TGUID = (D1: 0; D2: 0; D3: 0; D4: (0, 0, 0, 0, 0, 0, 0, 0));
ACTUAL_GUID: TGUID = (D1: 1; D2: 1; D3: 1; D4: (1, 1, 1, 1, 1, 1, 1, 1));
begin
Assert.WillNotRaise(
procedure
begin
Assert.AreNotEqual(EXPECTED_GUID, ACTUAL_GUID);
end, Exception);
end;
procedure TTestsAssert.AreEqual_Integer_Throws_ETestFailure_When_Values_Are_NotEqual;
begin
Assert.WillRaise(
procedure
begin
Assert.AreEqual(1, 2);
end, ETestFailure, Format('[%d] is Not Equal to [%d] %s', [2, 1, '']));
end;
procedure TTestsAssert.AreEqual_Integer_Throws_No_Exception_When_Values_Are_Equal;
begin
Assert.WillNotRaise(
procedure
begin
Assert.AreEqual(1, 1);
end, Exception);
end;
procedure TTestsAssert.AreEqual_Stream_Throws_ETestFailure_When_Values_Are_NotEqual;
const
TESTSTR_STRING = 'This is a test';
var
Expected: TStringStream;
Actual: TStringStream;
begin
Expected := TStringStream.Create(TESTSTR_STRING);
Actual := TStringStream.Create('A different value');
try
Assert.WillRaise(
procedure
begin
Assert.AreEqual(Expected, Actual);
end, ETestFailure);
finally
Expected.Free();
Actual.Free();
end;
end;
procedure TTestsAssert.AreEqual_Stream_Throws_No_Exception_When_Values_Are_Equal;
const
TESTSTR_STRING = 'This is a test';
var
Expected: TStringStream;
Actual: TStringStream;
begin
Expected := TStringStream.Create(TESTSTR_STRING);
Actual := TStringStream.Create(TESTSTR_STRING);
try
Assert.WillNotRaise(
procedure
begin
Assert.AreEqual(Expected, Actual);
end, Exception);
finally
Expected.Free();
Actual.Free();
end;
end;
procedure TTestsAssert.AreEqual_String_Throws_No_Exception_When_Values_Are_Equal;
const
ACTUAL_AND_EXPECTED_STRING = 'the brown dog jumped something';
begin
Assert.WillNotRaise(
procedure
begin
Assert.AreEqual(ACTUAL_AND_EXPECTED_STRING, ACTUAL_AND_EXPECTED_STRING);
end, Exception);
end;
procedure TTestsAssert.AreEqual_TClass_Throws_ETestFailure_When_Classes_Are_NotEqual;
begin
Assert.WillRaise(
procedure
begin
Assert.AreEqual(TMockClassOne, TMockClassTwo);
end, ETestFailure);
end;
procedure TTestsAssert.AreEqual_TClass_Throws_No_Exception_When_Classes_Are_Equal;
begin
Assert.WillNotRaise(
procedure
begin
Assert.AreEqual(TMockClassOne, TMockClassOne);
end, ETestFailure);
end;
procedure TTestsAssert.AreEqual_Throws_No_Exception_When_Values_Are_Exactly_Equal;
var
actualAndExpected, tolerance : Extended;
begin
//Ensure they are the same value.
actualAndExpected := 1.1;
tolerance := 0;
Assert.WillNotRaise(
procedure
begin
Assert.AreEqual(actualAndExpected, actualAndExpected, tolerance);
end, Exception);
end;
procedure TTestsAssert.AreEqual_TStrings_Throws_ETestFailure_When_Strings_Are_NotEqual;
var
expected, actual: TStrings;
begin
expected := TStringList.Create;
actual := TStringList.Create;
try
expected.CommaText := '1,2,3';
actual.CommaText := '1,2,3,4';
Assert.WillRaiseWithMessage(procedure
begin
Assert.AreEqual(expected, actual);
end, ETestFailure, 'Number of strings is not equal: Expected [3] but got [4]');
expected.CommaText := '"Lorem ipsum dolor sit amet","consectetur adipisici elit","sed eiusmod tempor incidunt"';
actual.CommaText := '"Lorem ipsum dolor sit amet","consectetur adisipici elit","sed eiusmod tempor incidunt"';
Assert.WillRaiseWithMessage(procedure
begin
Assert.AreEqual(expected, actual);
end, ETestFailure,
'Difference at position 16: [''pisici eli''] does not match [''sipici eli''] at line 2');
finally
expected.Free;
actual.Free;
end;
end;
procedure TTestsAssert.AreEqual_TStrings_Throws_No_Exception_When_Strings_Are_Equal;
var
expected, actual: TStrings;
begin
expected := TStringList.Create;
actual := TStringList.Create;
try
Assert.WillNotRaise(procedure
begin
Assert.AreEqual(expected, actual);
end, Exception);
expected.CommaText := '1,2,3';
actual.CommaText := '1,2,3';
Assert.WillNotRaise(procedure
begin
Assert.AreEqual(expected, actual);
end, Exception);
expected.CommaText := '1,2,3';
actual.CommaText := '1,-,3';
Assert.WillNotRaise(procedure
begin
Assert.AreEqual(expected, actual, [2]);
end, Exception);
finally
expected.Free;
actual.Free;
end;
end;
{$IFNDEF DELPHI_XE_DOWN}
procedure TTestsAssert.AreEqual_T_Throws_ETestFailure_When_Interfaces_Are_NotEqual;
var
mock : IInterface;
mock2 : IInterface;
begin
mock := TInterfacedObject.Create();
mock2 := TInterfacedObject.Create();
Assert.WillRaise(
procedure
begin
Assert.AreEqual<IInterface>(mock, mock2);
end, ETestFailure);
end;
procedure TTestsAssert.AreEqual_T_Throws_ETestFailure_When_Objects_Are_Nil;
var
mock : TObject;
nilObject : TObject;
begin
mock := TObject.Create();
try
nilObject := nil;
Assert.WillRaise(
procedure
begin
Assert.AreEqual<TObject>(mock, nilObject);
end, ETestFailure);
Assert.WillRaise(
procedure
begin
Assert.AreEqual<TObject>(nilObject, mock);
end, ETestFailure);
finally
FreeAndNil(mock);
end;
end;
procedure TTestsAssert.AreEqual_T_Throws_ETestFailure_When_Objects_Are_NotEqual;
var
mock : TObject;
mock2 : TObject;
begin
mock := TObject.Create;
mock2 := TObject.Create;
try
Assert.WillRaise(
procedure
begin
Assert.AreEqual<TObject>(mock, mock2);
end, ETestFailure);
finally
FreeAndNil(mock);
FreeAndNil(mock2);
end;
end;
procedure TTestsAssert.AreEqual_T_Throws_ETestFailure_When_Interfaces_Are_Nil;
var
mock : IInterface;
begin
mock := TInterfacedObject.Create();
Assert.WillRaise(
procedure
begin
Assert.AreEqual<IInterface>(mock, nil);
end, ETestFailure);
Assert.WillRaise(
procedure
begin
Assert.AreEqual<IInterface>(nil, mock);
end, ETestFailure);
end;
procedure TTestsAssert.AreEqual_T_Throws_No_Exception_When_Interfaces_Are_Equal;
var
mock : IInterface;
begin
mock := TInterfacedObject.Create();
Assert.WillNotRaise(
procedure
begin
Assert.AreEqual<IInterface>(mock, mock);
end, ETestFailure);
end;
procedure TTestsAssert.AreEqual_T_Throws_No_Exception_When_Objects_Are_Equal;
var
mock : TObject;
begin
mock := TObject.Create;
try
Assert.WillNotRaise(
procedure
begin
Assert.AreEqual<TObject>(mock, mock);
end, ETestFailure);
finally
FreeAndNil(mock);
end;
end;
procedure TTestsAssert.AreEqual_Array_T_Throws_ETestFailure_When_Arrays_Are_Not_Equal;
begin
Assert.WillRaise(
procedure
begin
Assert.AreEqual<integer>(TArray<integer>.Create(1, 2, 3), TArray<integer>.Create(1, 2, 3, 4));
end, ETestFailure);
Assert.WillRaise(
procedure
begin
Assert.AreEqual<real>(TArray<real>.Create(3.14, 3.15), TArray<real>.Create(3.15, 3.14));
end, ETestFailure);
Assert.WillRaise(
procedure
begin
Assert.AreEqual<string>(TArray<string>.Create('a', 'b', 'c'), TArray<string>.Create('a', 'c', 'b'));
end, ETestFailure);
end;
procedure TTestsAssert.AreEqual_Array_T_Throws_No_Exception_When_Arrays_Are_Equal;
begin
Assert.WillNotRaise(
procedure
begin
Assert.AreEqual<string>(TArray<string>.Create('a', 'b', 'c'), TArray<string>.Create('a', 'b', 'c'));
end, ETestFailure);
Assert.WillNotRaise(
procedure
begin
Assert.AreEqual<real>(TArray<real>.Create(3.14, 3.15),TArray<real>.Create(3.14, 3.15));
end, ETestFailure);
end;
{$ENDIF}
procedure TTestsAssert.Test_AreSameOnSameObjectWithDifferentInterfaces_No_Exception;
var
myObject : IInterfaceList;
begin
myObject := TInterfaceList.Create;
Assert.WillNotRaise(
procedure
begin
Assert.AreSame(myObject, myObject as IInterface);
end, ETestFailure);
end;
procedure TTestsAssert.Test_AreNotSameOnSameObjectWithDifferentInterfaces_Throws_Exception;
var
myObject : IInterfaceList;
begin
myObject := TInterfaceList.Create;
Assert.WillRaise(
procedure
begin
Assert.AreNotSame(myObject, myObject as IInterface);
end, ETestFailure);
end;
procedure TTestsAssert.AreNotEqual_Integer_Throws_No_Exception_When_Values_Are_NotEqual;
begin
Assert.WillNotRaise(
procedure
begin
Assert.AreNotEqual(1, 2);
end, ETestFailure);
end;
procedure TTestsAssert.CheckExpectation_Not_Empty_String_Will_Raise;
begin
Assert.WillRaise(
procedure
begin
Assert.CheckExpectation('My expectation');
end, ETestFailure);
end;
procedure TTestsAssert.AreNotEqual_Currency_Throws_Exception_When_Values_Are_Equal;
const
expected : currency = 1.34;
actual : currency = 1.34;
begin
Assert.WillRaise(
procedure
begin
Assert.AreNotEqual(expected, actual);
end, ETestFailure);
end;
procedure TTestsAssert.AreNotEqual_GUID_Throws_Exception_When_Values_Are_Equal;
const
EXPECTED_GUID: TGUID = (D1: 0; D2: 0; D3: 0; D4: (0, 0, 0, 0, 0, 0, 0, 0));
ACTUAL_GUID: TGUID = (D1: 0; D2: 0; D3: 0; D4: (0, 0, 0, 0, 0, 0, 0, 0));
begin
Assert.WillRaise(
procedure
begin
Assert.AreNotEqual(EXPECTED_GUID, ACTUAL_GUID);
end, ETestFailure);
end;
procedure TTestsAssert.AreNotEqual_GUID_Throws_No_Exception_When_Values_Are_NotEqual;
const
EXPECTED_GUID: TGUID = (D1: 0; D2: 0; D3: 0; D4: (0, 0, 0, 0, 0, 0, 0, 0));
ACTUAL_GUID: TGUID = (D1: 1; D2: 1; D3: 1; D4: (1, 1, 1, 1, 1, 1, 1, 1));
begin
Assert.WillNotRaise(
procedure
begin
Assert.AreNotEqual(EXPECTED_GUID, ACTUAL_GUID);
end, ETestFailure);
end;
procedure TTestsAssert.AreNotEqual_Integer_Throws_Exception_When_Values_Are_Equal;
begin
Assert.WillRaise(
procedure
begin
Assert.AreNotEqual(1, 1);
end, ETestFailure);
end;
{$IFDEF DELPHI_XE_UP}
procedure TTestsAssert.Contains_ArrayOfT_Throws_No_Exception_When_Value_In_Array;
begin
Assert.WillNotRaise(
procedure
begin
Assert.Contains<string>(['x', 'y', 'z'], 'x');
end, ETestFailure);
end;
procedure TTestsAssert.Contains_ArrayOfT_Throws_Exception_When_Value_Not_In_Array;
begin
Assert.WillRaise(
procedure
begin
Assert.Contains<string>(['x', 'y', 'z'], 'a');
end, ETestFailure);
end;
procedure TTestsAssert.DoesNotContain_ArrayOfT_Throws_No_Exception_When_Value_Not_In_Array;
begin
Assert.WillNotRaise(
procedure
begin
Assert.DoesNotContain<string>(['x', 'y', 'z'], 'a');
end, ETestFailure);
end;
procedure TTestsAssert.DoesNotContain_ArrayOfT_Throws_Exception_When_Value_In_Array;
begin
Assert.WillRaise(
procedure
begin
Assert.DoesNotContain<string>(['x', 'y', 'z'], 'x');
end, ETestFailure);
end;
{$ENDIF}
procedure TTestsAssert.StartsWith_SubString_Is_At_The_Start_Of_String(const subString, theString: string; caseSensitive: boolean);
begin
Assert.WillNotRaise(
procedure
begin
Assert.StartsWith( subString, theString, caseSensitive );
end, ETestFailure);
end;
procedure TTestsAssert.StartsWith_SubString_Is_Not_At_Start( const subString, theString: string; caseSensitive: boolean );
begin
Assert.WillRaise(
procedure
begin
Assert.StartsWith( subString, theString, caseSensitive );
end, ETestFailure);
end;
procedure TTestsAssert.EndsWith_SubString_Is_At_The_End_Of_String(const subString, theString: string; caseSensitive: boolean);
begin
Assert.WillNotRaise(
procedure
begin
Assert.EndsWith( subString, theString, caseSensitive );
end, ETestFailure);
end;
procedure TTestsAssert.EndsWith_SubString_Is_Not_At_End( const subString, theString: string; caseSensitive: boolean );
begin
Assert.WillRaise(
procedure
begin
Assert.EndsWith( subString, theString, caseSensitive );
end, ETestFailure);
end;
{$IFDEF SUPPORTS_REGEX}
procedure TTestsAssert.IsMatch_True_Will_Not_Raise(const regexPattern, theString: string);
begin
Assert.WillNotRaiseAny(
procedure
begin
Assert.IsMatch(regexPattern, theString);
end
);
end;
procedure TTestsAssert.IsMatch_False_Will_Raise_ETestFailure(const regexPattern, theString: string);
begin
Assert.WillRaise(
procedure
begin
Assert.IsMatch(regexPattern, theString);
end, ETestFailure);
end;
procedure TTestsAssert.WillRaiseWithMessageRegex;
const
EXCEPTION_MSG_PATT = 'Exception on "%s" doing "%s"';
EXCEPTION_RE_MATCH = 'Exception on ".+?" doing ".+?"';
EXCEPTION_RE_NOT_MATCH = 'Exception on something doing anything';
begin
Assert.WillNotRaiseAny(
procedure
begin
Assert.WillRaiseWithMessageRegex(
procedure
begin
raise Exception.CreateFmt(EXCEPTION_MSG_PATT, ['this', 'that']);
end,
nil,
EXCEPTION_RE_MATCH
);
end
);
Assert.WillRaise(
procedure
begin
Assert.WillRaiseWithMessageRegex(
procedure
begin
raise Exception.CreateFmt(EXCEPTION_MSG_PATT, ['this', 'that']);
end,
nil,
EXCEPTION_RE_NOT_MATCH
);
end,
ETestFailure);
end;
{$ENDIF}
initialization
TDUnitX.RegisterTestFixture(TTestsAssert);
end.
|
PROGRAM HelloDear(INPUT, OUTPUT);
USES
DOS;
VAR
Name: STRING;
FUNCTION GetQueryStringParameter(Key: STRING): STRING;
VAR
QueryString, KeyString: STRING;
Index, Len: BYTE;
BEGIN
KeyString := Key + '=';
QueryString := GetEnv('QUERY_STRING');
Len := length(QueryString);
IF Len = 0
THEN
GetQueryStringParameter := ''
ELSE
BEGIN
Index := pos(KeyString, QueryString);
IF Index = 0
THEN
GetQueryStringParameter := ''
ELSE
BEGIN
QueryString := copy(QueryString, Index + length(KeyString), Len - Index);
IF pos('&', QueryString) = 0
THEN
QueryString := copy(QueryString, 1, length(QueryString));
GetQueryStringParameter := QueryString
END
END
END;
BEGIN {HelloDear}
WRITELN('Content-Type: text/plain');
WRITELN;
Name := GetQueryStringParameter('name');
IF length(Name) = 0
THEN
WRITELN('Hello Anonymous!')
ELSE
WRITELN('Hello dear, ', Name, '!')
END. {HelloDear}
|
unit aIni;
interface
uses System.SysUtils, System.IniFiles, System.IOUtils, System.Classes;
const
DEFAULT_SECTION_NAME = 'CFG';
STR_NAMES : array[1..1] of string = ('DBPath');
STR_DEF : array[1..1] of string = ('');
{INT_NAMES : array[1..1] of string = ('');
INT_DEFAULTS : array[1..1] of integer = (0);
BOOL_NAMES : array[1..1] of string = ('');
BOOL_DEFAULTS : array[1..1] of boolean = (true);}
type
TAppIni = class(TIniFile)
private
function GetString(const Index: Integer): string;
procedure SetString(const Index: Integer; const Value: string);
{function GetInteger(const Index: integer): integer;
procedure SetInteger(const Index, Value: integer);
function GetBoolean(const Index: integer): boolean;
procedure SetBoolean(const Index: integer; Value: boolean);}
public
property DBPath: string index 1 read GetString write SetString;
end;
implementation
{ TAppIni }
function TAppIni.GetString(const Index: Integer): string;
begin
result:= ReadString(DEFAULT_SECTION_NAME, STR_NAMES[Index], STR_DEF[Index]);
end;
procedure TAppIni.SetString(const Index: Integer; const Value: string);
begin
WriteString(DEFAULT_SECTION_NAME, STR_NAMES[Index], Value);
end;
{function TAppIni.GetBoolean(const Index: integer): boolean;
begin
result:= ReadBool(DEFAULT_SECTION_NAME, BOOL_NAMES[index], BOOL_DEFAULTS[index]);
end;
procedure TAppIni.SetBoolean(const Index: integer; Value: boolean);
begin
WriteBool(DEFAULT_SECTION_NAME, BOOL_NAMES[index], Value);
end;
function TAppIni.GetInteger(const Index: integer): integer;
begin
result:= ReadInteger(DEFAULT_SECTION_NAME, INT_NAMES[index], INT_DEFAULTS[index]);
end;
procedure TAppIni.SetInteger(const Index, Value: integer);
begin
WriteInteger(DEFAULT_SECTION_NAME, INT_NAMES[index], Value);
end;
}
end.
|
unit WiRL.Tests.Framework.HeaderParser;
interface
uses
System.Classes, System.SysUtils, System.StrUtils, System.JSON,
System.NetEncoding,
DUnitX.TestFramework,
WiRL.http.Server,
WiRL.Core.Engine,
WiRL.http.Accept.MediaType,
WiRL.http.Accept.Parser,
WiRL.http.Accept.Charset,
WiRL.Tests.Mock.Server;
type
TMyHeader = class(THeaderItem)
end;
[TestFixture]
TTestHeaderParser = class(TObject)
public
[Test]
procedure TestBasicParsing;
[Test]
procedure TestAcceptCharsetHeader;
end;
implementation
{ TTestHeaderParser }
procedure TTestHeaderParser.TestAcceptCharsetHeader;
var
AcceptCharset: TAcceptCharset;
begin
AcceptCharset := TAcceptCharset.Create('Test; q=1; p=2');
try
Assert.AreEqual('Test', AcceptCharset.AcceptItemOnly);
Assert.AreEqual(Double(1), AcceptCharset.QFactor);
//Assert.AreEqual(2, AcceptCharset.PFactor);
finally
AcceptCharset.Free;
end;
end;
procedure TTestHeaderParser.TestBasicParsing;
var
MyHeader: TMyHeader;
begin
MyHeader := TMyHeader.Create('Test; key=value');
try
Assert.AreEqual('Test', MyHeader.Value);
Assert.AreEqual(1, MyHeader.Parameters.Count);
finally
MyHeader.Free;
end;
end;
initialization
TDUnitX.RegisterTestFixture(TTestHeaderParser);
end.
|
unit TrakceGUI;
{
Trida TTrkGUI vytvari pomyslne 'graficke rozhrani' tridy TTrakce pro zbytek
programu. Ve skutecnosti se nejedna o GUI, ale o funkce tridy TTrakce upravene
tak, aby sly v programu pouzit co nejsnaze.
Zapouzdreni abstraktni tridy TTrakce, resp. konkretni tridy TXPressNet (ktera
ji dedi) spociva v implemenatci callbackovych funkci v tride TTrkGUI, ktera
napriklad chyby promita primo do realneho GUI aplikace.
}
interface
uses
SysUtils, Classes, StrUtils, CPort, Trakce, ComCtrls, Graphics, Forms, Windows,
THnaciVozidlo, Generics.Collections, Contnrs;
const
// maximalni rychlost pro rychlostni tabulku
_MAX_SPEED = 28;
// tato rychlostni tabulka je pouzita v pripade, kdy selze nacitani
// souboru s rychlostni tabulkou:
_DEFAULT_SPEED_TABLE : array [0.._MAX_SPEED] of Integer = (
0,
1,
2,
4,
6,
8,
10,
12,
15,
17,
20,
22,
25,
30,
35,
40,
45,
50,
55,
60,
65,
70,
75,
80,
85,
90,
100,
110,
120
);
type
TLogEvent = procedure(Sender:TObject; lvl:Integer; msg:string; var handled:boolean) of object;
TGetSpInfoEvent = procedure(Sender: TObject; Slot:TSlot; var handled:boolean) of object;
TGetFInfoEvent = procedure(Sender: TObject; Addr:Integer; func:TFunkce; var handled:boolean) of object;
ENotOpenned = class(Exception);
TTrkLogLevel = (tllNo = 0, tllErrors = 1, tllCommands = 2, tllData = 3, tllChanges = 4, tllDetail = 5);
// pri programovani POMu se do callbacku predavaji tato data
TPOMCallback = record
addr:Word; // adresa programovane lokomotivy
list:TList<THVPomCV>; // kompletni nemenny seznam CV k programovani
index:Integer; // index prave progamovaneho CV
callback_ok, callback_err:TCommandCallback; // callbacky pri kompletnim ukonceni programovani, resp. vyskytu chyby v libovolnem kroku
new:TPomStatus; // status, jaky ma nabyt POM hnaciho vozidla po ukonceni programovaani (zpravidla PC, nebo RELEASED)
// pokud dojde pri programovani POMu k chybe, je do HV.Slot.pom ulozeno TPomStatus.error
end;
{
Pri prebirani lokomotivy se do callbacku jednotlivych cinnosti ukladaji tato data:
prebirani lokomotivy =
1) prevzit loko z centraly
2) nastavit funkce na pozadovane hodnoty
3) naprogarmovat POM
4) zavolat OK callback
- Pokud v libovolne casti procesu nastane chyba, je vyvolan Error callback.
- Chyba pri nastavovani funkci je oznamena pouze jako WARNING (error callback neni volan).
}
TPrevzitCallback = record
addr:Word; // adresa lokomotivy
callback_ok, callback_err:TCommandCallback; // globalni callbacky
end;
// pri hromadnem nastavovani funkci dle vyznamu (napr. vypnout vsechna "svetla") se do callbacku predavaji tato data
TFuncsCallback = record
addr:Word; // adresa lokomotivy
vyznam:string; // vyznam funkce, kterou nastavujeme
state:boolean; // novy stav funkce
callback_ok, callback_err:TCommandCallback; // globalni callbacky
end;
// reprezenatce jedne funkci sady
TFuncCBSada = record
func:array[0..15] of boolean; // funkce v sade
index:Integer; // index sady (pro xpressnet: 0:F0-F4, 1:F5-F8, 2:F9-12)
end;
// pri programovani funkci si udrzuji nasledujici data (v callback datech jednotlivych procesu)
TFuncCallback = record
addr:Word; // adresa lokomotivy
callback_ok, callback_err:TCommandCallback; // globalni callbacky
sady:TList<TFuncCBSada>; // seznam jednotlivych sad, kazda sada obsahuje funkce k naprogramovani
end;
// zaznam toggleQueue
THVFunc = record
HV:THV;
fIndex:Cardinal;
time:TDateTime;
end;
// ------- trida TTrkGUI --------
TTrkGUI = class
private const
_DEF_LOGLEVEL = TTrkLogLevel.tllCommands; // default loglevel
_DEF_BAUDRATE = br9600; // default serial baudrate
_DEF_STOPBITS = sbOneStopBit; // default serial stopbits
_DEF_DATABITS = dbEight; // default serial databits
_DEF_FLOWCONTROL = fcHardware; // default serial flow control
private
Trakce:TTrakce; // reference na tridu TTrakce
// Ttrakce je abstarktni, zde se ve skutecnosti nachazi konkretni trida protokolu (zatim jen TXpressNET, v pripade potreby napriklad i TLocoNET)
LogObj:TListView; // Logovaci objekt - obvykle obsahuje refenreci na logovaci tabulku ve F_Main (je inicializovano v kontruktoru)
fTrkSystem:Ttrk_system; // aktualni trakcni system; koresponduje se vytvorenou instanci v .Trakce
SpeedTable:array [0.._MAX_SPEED] of Integer; // rychlostni tabulka
// index = jizdni stupen, .SpeedTable[index] = rychlost v km/h
// napr. SpeedTable[15] = 40 <-> rychlostni stupen 15: 40 km/h
turnoff_callback:TNotifyEvent; // callback volany po prikazu TurnOff
// Prikaz TurnOff zapina F0 a vypina vsechny vyssi funkce
// pouziva se pri vypinani systemu (pro vypnuti otravnych zvuku zvukovych dekoderu)
//events definition
FOnLog: TLogEvent; // log event
flogfile : TTrkLogLevel; // loglevel souboru
flogtable: TTrkLogLevel; // loglevel tabulky
finitok : boolean; // je true, pokud po otevreni seriaku centrala zakomujikovala (tj. odpovedela na prikaz)
// pri .Open se nastavuje na false
{
Info: Samotna komponenta serioveho portu je ulozena v .Trakce.ComPort.CPort.
Tato komponenta je pri uzavrenem seriaku znicena.
Pred otevrenim je volna konstruktor, po uzavreni destruktor!
}
CPortData : record // data pro nastaveni serioveho portu
br:TBaudRate; // baudrate
com:string; // com port ve formatu "COM1", "COM8" ...
sb:TStopBits; // stop bits
db:TDataBits; // data bits
FlowControl:TFlowControl;
end;
toggleQueue:TQueue<THVFunc>;
function GetOpenned():boolean; // je seriak otevreny ?
procedure TrkLog(Sender:TObject; lvl:Integer; msg:string); // logovaci event z .Trakce
procedure WriteLog(lvl:Integer; msg:string); // zaloguje data (at uz do souboru, ci do tabulky)
// eventy serioveho portu:
procedure OnComError(Sender: TObject; Errors: TComErrors);
procedure OnComException(Sender: TObject;
TComException: TComExceptions; ComportMessage: string; WinError: Int64;
WinMessage: string);
procedure OnComWriteError(Sender:TObject); // tento event je volan z .Trakce pri vyvolani vyjimky pri zapisu do ComPortu
// to nastava napriklad, pokud ComPort najednou zmizi z pocitace (nekdo odpoji USB)
function GettSpeed(kmph:Integer):Integer; // vrati rchlostni stupen pri zadane rychlosti v km/h
// eventy z komponenty seriaku:
procedure BeforeOpen(Sender:TObject);
procedure AfterOpen(Sender:TObject);
procedure BeforeClose(Sender:TObject);
procedure AfterClose(Sender:TObject);
procedure NouzReleaseLoko();
procedure ConnectChange(Sender: TObject; addr:Integer; code:TConnect_code;
data:Pointer); // event volany z .Trace pri zmene majitele lokomotivy (loko prevzato, ukradeno, nedostupne, ...)
procedure LokComErr(Sender:TObject; addr:Integer); // event oznamujici chybu komunikace s danou lokomotivou (je volan paralelne s error callback eventem, ale jen pro urcite prikazy - pro prikazy tykajici se rizeni konkretni lokomotivy).
procedure LokComOK(Sender:TObject; addr:Integer); // event potvrzujici komunikaci s danym HV (je volan pokazde, pokud centrala odpovi na prikaz o nasatveni dat HV)
// je protipol predchoziho eventu
// eventy z .Trakce pri zapinani systemu (tj. odpoved na priklad GET-STATUS)
procedure InitStatErr(Sender:TObject; Data:Pointer);
procedure InitStatOK(Sender:TObject; Data:Pointer);
// event z .Tracke pri ozivovani systemu po neuspesnem prikazu GET-STATUS
// oziveni - prikaz DCC STOP; tyto eventy tedy odpovidaji inicializacnimu prikazu STOP
procedure InitStopErr(Sender:TObject; Data:Pointer);
procedure InitStopOK(Sender:TObject; Data:Pointer);
// Obecne nastaveni callback komunikacnich eventu
// Tyto funkce nastavi callback eventy do .Trakce
procedure SetCallbackErr(callback_err:TCommandCallback);
procedure SetCallbackOK(callback_ok:TCommandCallback);
// eventy z komunikace s centralou pri prebirani a odhlasovani HV (tj. prebirani a odhlasovani VSECH LOKO)
procedure PrebiraniUpdateOK(Sender:TObject; Data:Pointer); // loko uspesne prevzato
procedure PrebiraniUpdateErr(Sender:TObject; Data:Pointer); // prevzeti se nazdarilo (napr. centrala neodpovedela na prikaz o prevzeti, na POM ...)
procedure OdhlasovaniUpdateOK(Sender:TObject; Data:Pointer); // loko uspesne uvolneno
procedure OdhlasovaniUpdateErr(Sender:TObject; Data:Pointer); // uvolneni loko se nezdarilo (napr. centrala nedopovedela na POM, ...)
// eventy spojene s jednotlivymi fazemi prebirani HV
procedure PrevzatoErr(Sender:TObject; Data:Pointer); // centala nedopovedela na prikaz o prevzeti
// (to, ze centrala odpovedela, ale HV neni dostupne, je signalizovano eventem .ConnectChange)
procedure PrevzatoFunc1328OK(Sender:TObject; Data:Pointer); // funkce 13-28 byly uspesne nacteny
procedure PrevzatoSmerOK(Sender:TObject; Data:Pointer); // uspesne nastaven smer lokomotivy
procedure PrevzatoPOMOK(Sender:TObject; Data:Pointer); // POM vsech CV uspesne dokoncen
procedure PrevzatoFuncOK(Sender:TObject; Data:Pointer); // nastavovani vsech funkci uspesne dokonceno
procedure PrevzatoFuncErr(Sender:TObject; Data:Pointer); // centrala neodpovedela na prikaz o nastaveni funkci
// eventy spojene s jedntlivymi fazemi odhlasovani loko:
procedure OdhlasenoOK(Sender:TObject; Data:Pointer); // loko odhlaseno centrala odpovedela na prikaz o uvolneni
procedure OdhlasenoErr(Sender:TObject; Data:Pointer); // centrala neodpovedela na prikaz o uvolneni
procedure OdhlasenoPOMOK(Sender:TObject; Data:Pointer); // kompletni Release POM hotov
procedure OdhlasenoPOMErr(Sender:TObject; Data:Pointer); // centrala neodpovedela na Release POM
// callbacky spojene s nastavovanim funkci:
// Funkce nastavujeme po jednotlivych sadach.
// K nastaveni dalsi sady dojde az po uspesnem nastaveni sady predchozi - tj. prichodu prikazu OK z centraly, resp. zavolani OK callbacku
procedure FuncOK(Sender:TObject; Data:Pointer);
procedure FuncErr(Sender:TObject; Data:Pointer);
procedure AllPrevzato(); // je volana, pokud jsou vsechny loko prevzaty (primarni vyuziti = interakce s GUI)
procedure AllOdhlaseno(); // je volana, pokud jsou vsechny loko odhlaseny (primarni vyuziti = interakce s GUI)
procedure OnTrackStatusChange(Sender: TObject); // event volany z .Trakce pri zmene TrackStatus (napr. CENTRAL-STOP, SERVICE, ...)
// novy status je k dispozici v .Trakce.TrackStatus
function GetTrkStatus():Ttrk_status; // zjistit TrackStatus s .Trakce
procedure TurnOffFunctions_cmdOK(Sender:TObject; Data:Pointer); // OK callback pro prikaz TurnOff
procedure GotCSVersion(Sender:TObject; version:TCSVersion); // Callback z .Trakce volany pri prichodu prikazu informujicim o verzi v FW v centrale
procedure GotLIVersion(Sender:TObject; version:TLIVersion); // Callback z .Trakce volany pri prichodu prikazu informujicim o verzi v LI
procedure GotLIAddress(Sender:TObject; addr:Byte); // Callback z .Trakce volany pri prichodu prikazu informujicim o adrese LI
// eventy spojene se zapisem jednotlivych POM:
procedure POMCvWroteOK(Sender:TObject; Data:Pointer);
procedure POMCvWroteErr(Sender:TObject; Data:Pointer);
// chyba pri nouzovem uvolnovani HV
// Nouzzove jsou uvolnena takove HV, ktera jsou pri BeforeClose jeste prevzata.
procedure NouzReleaseCallbackErr(Sender:TObject; Data:Pointer);
// callback pri zjistovani verze centraly
procedure GotCSVersionOK(Sender:TObject; Data:Pointer);
procedure GotCSVersionErr(Sender:TObject; Data:Pointer);
// callback pri zjistovani verze LI
procedure GotLIVersionOK(Sender:TObject; Data:Pointer);
procedure GotLIVersionErr(Sender:TObject; Data:Pointer);
// callback pri zjistovani adresy LI
procedure GotLIAddrErr(Sender:TObject; Data:Pointer);
procedure LoksSetFuncOK(Sender:TObject; Data:Pointer);
procedure LoksSetFuncErr(Sender:TObject; Data:Pointer);
procedure SetLoglevelFile(ll:TTrkLogLevel);
procedure SetLoglevelTable(ll:TTrkLogLevel);
procedure LoadSpeedTableToTable(var LVRych:TListView);
procedure UpdateSpeedDir(HV:THV; Sender:TObject; speed:boolean; dir:boolean);
procedure CheckToggleQueue();
procedure FlushToggleQueue();
procedure ProcessHVFunc(hvFunc:THVFunc);
class function HVFunc(HV:THV; fIndex:Cardinal; time:TDateTime):THVFunc;
public
{
Pozn.
Vsechny funkce spojene s nastavovanim dat HV maji parametr Sender
kam je vhodne dat bud konkretni regulator, nebo OR v pripade
regulatoru klienta.
Informace o zmene dat HV je pak volana do vsech systemu mimo Senderu.
Tedy napriklad, pokud je loko otevrene v 5 regulatorech a jeste na serveru
a dojde ke zmene rychlosti v OR1, je infroamce o zmene rychlosti
odeslana do OR2, OR3, OR4, OR5 a regulatoru na serveru, nikoliv
vsak do OR1 (tomu prijde napriklad OK, ci error callback)
}
DCCGoTime:TDateTime;
constructor Create(TrkSystem:Ttrk_system; LogObj:TListView; loglevel_file:TTrkLogLevel = _DEF_LOGLEVEL; loglevel_table: TTrkLogLevel = _DEF_LOGLEVEL);
destructor Destroy(); override;
// otevrit a zavrit spojeni s centralou:
function Open():Byte;
function Close(force:boolean = false):Byte;
// zakladni prikazy do centraly:
function CentralStart():Byte; // TRACK ON
function CentralStop():Byte; // TRACK OFF
function LokSetSpeed(Sender:TObject; HV:THV; speed:Integer; dir:Integer = -1):Byte;
// nastaveni rychlosti daneho HV, rychlost v km/h
function LokSetDirectSpeed(Sender:TObject; HV:THV; speed:Integer; dir:Integer = -1):Byte;
// nastaveni rychlosti daneho HV, rychlost se zadava primo ve stupnich
function LokSetFunc(Sender:TObject; HV:THV; funkce:TFunkce; force:boolean = false):Byte;
// nastaveni funkce HV; force nastavi vsechny funkce v parametru bez ohledu na rozdilnost od aktualniho stavu
function LokFuncToggle(Sender:TObject; HV:THV; fIndex:Cardinal):Byte; // zapne a po 500 ms vypne konkretni funkci
procedure LoksSetFunc(vyznam:string; state:boolean); // nastavi funkci s danym vyznamem u vsech prevzatych hnacich vozidel na hodnotu state
function LokGetSpSteps(HV:THV):Byte; // vysle pozadavek na zjisteni informaci o lokomotive
function EmergencyStop():Byte; // nouzove zastaveni vsech lokomotiv, ktere centrala zna (centrala, nikoliv pocitac!)
function EmergencyStopLoko(Sender:TObject; HV:THV):Byte; // nouzove zastaveni konkretniho HV
function EmergencyStopAddr(addr:Integer):Byte; // nouzove zastaveni konkretni adresy lokmotivy
procedure GetCSVersion(); // zjistit verzi FW v centrale
procedure GetLIVersion(); // zjistit verzi SW a HW LI
procedure GetLIAddress(); // zjisti adresu LI
procedure SetLIAddress(addr:Byte); // nastavi adresu LI
procedure InitSystems(); // odesle centrale povel TRACK-STATUS a doufa v odpoved
// je volano pri pripojeni k centrale jako overeni funkcni komunikace
// nacitani a ukladani rychlostni tabulky z a do souboru
procedure LoadSpeedTable(filename:string;var LVRych:TListView);
procedure SaveSpeedTable(filename:string);
function GetStepSpeed(step:byte):Integer; // vraci rychlosti prislusneho jizdniho stupne
function SetSpetSpeed(step:byte;sp:Integer):Byte; // nastavi rychlost prislusneho jizdniho stupne
procedure PrevzitLoko(HV:THV); // prevzit dane HV (tj. z centraly, nastavit funkce, POM)
procedure OdhlasitLoko(HV:THV); // uvolnit loko (tj. RELEASE POM, odhlasit)
function POMWriteCV(Sender:TObject; HV:THV; cv:Word; data:byte):Integer; // zapsat 1 CV POMem, v praxi nevyuzivano
procedure POMWriteCVs(Sender:TObject; HV:THV; list:TList<THVPomCV>; new:TPomStatus);
// zapsat seznam CV POMem
procedure PrevzitAll(); // prevzit vsechna HV na soupravach
procedure OdhlasitAll(); // odhlasit vsechna prevzata HV
procedure FastResetLoko(); // resetuje lokomotivy do odhlaseneho stavu, rychly reset
procedure TurnOffFunctions(callback:TNotifyEvent); // vypnout funkce vyssi, nez F0; F0 zapnout
procedure Update();
class function LogLevelToString(ll:TTrkLogLevel):string; // rewrite loglevel to human-reada ble format
// aktualni data serioveho portu
property BaudRate:TBaudRate read CPortData.br write CPortData.br;
property COM:string read CPortData.com write CPortData.com;
property StopBits:TStopBits read CPortData.sb write CPortData.sb;
property DataBits:TDataBits read CPortData.db write CPortData.db;
property FlowControl:TFlowCOntrol read CPortData.FlowControl write CPortData.FlowControl;
property openned:boolean read GetOpenned; // otevreny seriovy port
property TrkSystem:Ttrk_system read fTrkSystem; // aktualni TrkSystem (XpressNET, LocoNET, ...)
property isInitOk:boolean read finitok; // komunikuje cetrala?, resp. odpovedel na prikaz STATUS
property status:Ttrk_status read GetTrkStatus; // aktualni STATUS centraly
{ !!! DULEZITE:
pri volani libovolne funkce (i zvnejsku) je mozne do techto properties
nastavit Callback eventy, ktere budou zavolany pri vykonani prikazu.
V praxi:
.callback_err := TTrakce.GenerateCallback(Self.chyba)
.callback_ok := TTrakce.GenerateCallback(Self.uspech)
.SetRych(...)
Vzdy je zavolan prave jeden z callbacku !
OK callback je volan kdyz centrala odpovi na prikaz "OK",
Error callback je volany, kdyz centrala odpovi chybou,
nebo na prikaz opakovane neodpovi.
}
property callback_err:TCommandCallback write SetCallbackErr;
property callback_ok:TCommandCallback write SetCallbackOK;
// vnejsi eventy:
property OnLog: TLogEvent read FOnLog write FOnLog;
property logfile:TTrkLogLevel read flogfile write SetLoglevelFile;
property logtable:TTrkLogLevel read flogtable write SetLoglevelTable;
protected
end;//TTrkGUI
////////////////////////////////////////////////////////////////////////////////
implementation
uses fMain, fSettings, XpressNET, TechnologieRCS, fRegulator, SprDb, Souprava,
GetSystems, THVDatabase, fAdminForm, DataHV,
Prevody, TBloky, RegulatorTCP, TCPServerOR, fFuncsSet;
////////////////////////////////////////////////////////////////////////////////
constructor TTrkGUI.Create(TrkSystem:Ttrk_system; LogObj:TListView; loglevel_file:TTrkLogLevel = _DEF_LOGLEVEL; loglevel_table: TTrkLogLevel = _DEF_LOGLEVEL);
begin
inherited Create;
case TrkSystem of
TRS_LocoNET : ;
TRS_XpressNET : Self.Trakce := TXpressNET.Create();
end;//case
Self.flogfile := loglevel_file;
Self.flogtable := loglevel_table;
Self.fTrkSystem := TrkSystem;
Self.Trakce.OnLog := Self.TrkLog;
Self.Trakce.OnConnectChange := Self.ConnectChange;
Self.Trakce.OnLokComError := Self.LokComErr;
Self.Trakce.OnLokComOK := Self.LokComOK;
Self.Trakce.OnTrackStatusChange := Self.OnTrackStatusChange;
Self.Trakce.OnComError := Self.OnComWriteError;
Self.LogObj := LogObj;
Self.CPortData.br := _DEF_BAUDRATE;
Self.CPortData.sb := _DEF_STOPBITS;
Self.CPortData.db := _DEF_DATABITS;
Self.CPortData.FlowControl := _DEF_FLOWCONTROL;
Self.turnoff_callback := nil;
Self.DCCGoTime := Now;
Self.toggleQueue := TQueue<THVFunc>.Create();
Self.WriteLog(2, 'BEGIN loglevel_file='+LogLevelToString(loglevel_file)+', loglevel_table='+LogLevelToString(loglevel_table));
end;//ctor
destructor TTrkGUI.Destroy();
begin
try
Self.WriteLog(2, 'END');
except
end;
Self.FlushToggleQueue();
FreeAndNil(Self.toggleQueue);
FreeAndNil(Self.Trakce);
inherited;
end;//dotr
////////////////////////////////////////////////////////////////////////////////
function TTrkGUI.GetOpenned():boolean;
begin
if (not Assigned(Self.Trakce.ComPort.CPort)) then Exit(false);
Result := Self.Trakce.ComPort.CPort.Connected;
end;//function
function TTrkGUI.Open():Byte;
begin
Self.finitok := false;
if ((SystemData.Status = starting) and (Self.openned)) then
begin
Self.InitSystems();
Exit(0);
end;
Self.TrkLog(self,2,'OPENING port='+Self.CPortData.com+' br='+BaudRateToStr(Self.CPortData.br)+' sb='+StopBitsToStr(Self.CPortData.sb)+' db='+DataBitsToStr(Self.CPortData.db)+' fc='+FlowControlToStr(Self.CPortData.FlowControl));
if ((Assigned(Self.Trakce.ComPort.CPort)) and (Self.Trakce.ComPort.CPort.Connected)) then
begin
Self.TrkLog(self, 1, 'OPEN: already connected');
Exit(0);
end;
if (not Assigned(Self.Trakce.ComPort.CPort)) then
Self.Trakce.ComPort.CPort := TComPort.Create(nil);
Self.Trakce.ComPort.CPort.OnError := Self.OnComError;
Self.Trakce.ComPort.CPort.OnException := Self.OnComException;
Self.Trakce.ComPort.CPort.OnBeforeOpen := Self.BeforeOpen;
Self.Trakce.ComPort.CPort.OnAfterOpen := Self.AfterOpen;
Self.Trakce.ComPort.CPort.OnBeforeClose := Self.BeforeClose;
Self.Trakce.ComPort.CPort.OnAfterClose := Self.AfterClose;
Self.Trakce.ComPort.CPort.Port := Self.CPortData.com;
Self.Trakce.ComPort.CPort.BaudRate := Self.CPortData.br;
Self.Trakce.ComPort.CPort.DataBits := Self.CPortData.db;
Self.Trakce.ComPort.CPort.StopBits := Self.CPortData.sb;
Self.Trakce.ComPort.CPort.FlowControl.FlowControl := Self.CPortData.FlowControl;
try
Self.Trakce.ComPort.CPort.Open;
except
on E : Exception do
begin
Self.Trakce.ComPort.CPort.Close;
Self.TrkLog(self, 1, 'OPEN ERR: com port object error : '+E.Message);
Self.AfterClose(self);
if (SystemData.Status = TSystemStatus.starting) then
begin
SystemData.Status := TSystemStatus.null;
F_Main.A_System_Start.Enabled := true;
F_Main.A_System_Stop.Enabled := true;
end;
Exit(3);
end;
end;
Result := 0;
end;//function
function TTrkGUI.Close(force:boolean = false):Byte;
var i:Integer;
begin
if ((SystemData.Status = stopping) and (not Self.openned)) then
begin
F_Main.A_RCS_StopExecute(nil);
Exit(0);
end;
Self.TrkLog(self, 2, 'CLOSING...');
if (not Self.openned) then
begin
Self.TrkLog(self, 1, 'CLOSE: already disconnected');
Exit(0);
end;
for i := 0 to _MAX_ADDR-1 do
if (HVDb.HVozidla[i] <> nil) then
begin
HVDb.HVozidla[i].Slot.stolen := false;
HVDb.HVozidla[i].Slot.prevzato := false;
end;
if (not force) then Self.NouzReleaseLoko();
try
Self.Trakce.ComPort.CPort.Close();
except
on E : Exception do
Self.TrkLog(self, 1, 'CLOSE ERR: com port object error : '+E.Message);
end;
try
FreeAndNil(Self.Trakce.ComPort.CPort);
except
Self.AfterClose(self);
end;
Result := 0;
end;//function
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.TrkLog(Sender:TObject; lvl:Integer; msg:string);
var handled:boolean;
begin
handled := false;
if (Assigned(Self.FOnLog)) then Self.FOnLog(self, lvl, msg, handled);
if (handled) then Exit;
Self.WriteLog(lvl, msg);
end;//procedure
procedure TTrkGUI.WriteLog(lvl:Integer; msg:string);
var LV_Log:TListItem;
f:TextFile;
xDate, xTime:string;
begin
if ((lvl > Integer(Self.logfile)) and (lvl > Integer(Self.logtable))) then Exit;
DateTimeToString(xDate, 'yy_mm_dd', Now);
DateTimeToString(xTime, 'hh:mm:ss,zzz', Now);
if (Self.LogObj.Items.Count > 500) then
Self.LogObj.Clear();
if (lvl <= Integer(Self.logtable)) then
begin
try
LV_Log := Self.LogObj.Items.Insert(0);
LV_Log.Caption := xTime;
LV_Log.SubItems.Add(IntToStr(lvl));
LV_Log.SubItems.Add(msg);
except
end;
end;//if Self.logtable
if (lvl <= Integer(Self.logfile)) then
begin
try
AssignFile(f, 'log\lnet\'+xDate+'.log');
if FileExists('log\lnet\'+xDate+'.log') then
Append(f)
else
Rewrite(f);
Writeln(f, xTime+' '+IntToStr(lvl)+': '+msg);
CloseFile(f);
except
end;
end;
end;//prrocedure
////////////////////////////////////////////////////////////////////////////////
function TTrkGUI.CentralStart():Byte;
begin
if (not Assigned(Self.Trakce)) then Exit(1);
if (not Self.openned) then Exit(2);
Self.TrkLog(self,2,'PUT: CENTRAL START');
Self.Trakce.TrackStatus := TS_ON;
Result := 0;
end;//function
function TTrkGUI.CentralStop():Byte;
begin
if (not Assigned(Self.Trakce)) then Exit(1);
if (not Self.openned) then Exit(2);
Self.TrkLog(self,2,'PUT: CENTRAL STOP');
Self.Trakce.TrackStatus := TS_OFF;
Result := 0;
end;//function
////////////////////////////////////////////////////////////////////////////////
function TTrkGUI.LokSetSpeed(Sender:TObject; HV:THV; speed:Integer; dir:Integer = -1):Byte; //rychlost se zadava v km/h
var speedOld:Integer;
dirOld:Integer;
begin
if (not Self.openned) then Exit(1);
if (HV = nil) then Exit(2);
if ((dir > 1) or (dir < -1)) then Exit(4);
if ((HV.Slot.speed = Self.GettSpeed(speed)) and (HV.Slot.Smer = dir)) then
begin
Self.TrkLog(self, 5, 'PUT: IGNORE LOK SPEED: '+HV.data.Nazev+' ('+IntToStr(HV.Adresa)+'); sp='+IntToStr(speed)+' skmph; dir='+IntToStr(dir));
Exit(5);
end;
if (dir = -1) then dir := HV.Slot.Smer;
speedOld := HV.Slot.speed;
dirOld := HV.Slot.smer;
HV.Slot.speed := Self.GettSpeed(speed);
HV.Slot.Smer := dir;
Self.UpdateSpeedDir(HV, Sender, speedOld <> HV.Slot.speed, dirOld <> HV.Slot.smer);
Self.TrkLog(self,2,'PUT: LOK SPEED: '+HV.data.Nazev+' ('+IntToStr(HV.Adresa)+'); sp='+IntToSTr(speed)+' kmph = '+IntToStr(Self.GettSpeed(speed))+' steps; dir='+IntToStr(dir));
Self.Trakce.LokSetSpeed(HV.Adresa,Self.GettSpeed(speed),dir);
Result := 0;
end;//function
function TTrkGUI.LokSetDirectSpeed(Sender:TObject; HV:THV; speed:Integer; dir:Integer = -1):Byte; //rychlost se zadava v steps
var speedOld:Integer;
dirOld:Integer;
begin
if (not Self.openned) then Exit(1);
if (HV = nil) then Exit(2);
if ((dir > 1) or (dir < -1)) then Exit(4);
if ((HV.Slot.speed = speed) and (HV.Slot.Smer = dir)) then
begin
Self.TrkLog(self, 5, 'PUT: IGNORE LOK SPEED: '+HV.data.Nazev+' ('+IntToStr(HV.Adresa)+'); sp='+IntToStr(speed)+' steps; dir='+IntToStr(dir));
Exit(5);
end;
if (dir = -1) then dir := HV.Slot.Smer;
speedOld := HV.Slot.speed;
dirOld := HV.Slot.smer;
HV.Slot.speed := speed;
HV.Slot.Smer := dir;
Self.UpdateSpeedDir(HV, Sender, speedOld <> HV.Slot.speed, dirOld <> HV.Slot.smer);
Self.TrkLog(self,2,'PUT: LOK SPEED: '+HV.data.Nazev+' ('+IntToStr(HV.Adresa)+'); sp='+IntToStr(speed)+' steps; dir='+IntToStr(dir));
Self.Trakce.LokSetSpeed(HV.Adresa,speed,dir);
Result := 0;
end;//function
// nastaveni funkci lokomotiv:
// vypocteme sady a samotne funkce nechame nastavit TTrkGUI.FuncOK(...)
// jednotlive sady se pak nastavuji postupne (po prijeti OK callbacku)
function TTrkGUI.LokSetFunc(Sender:TObject; HV:THV; funkce:TFunkce; force:boolean = false):Byte;
const
_SADY_CNT = 5;
var i:Cardinal;
sady_change:array [0.._SADY_CNT-1] of boolean;
fc:Pointer;
sada:TFuncCBSada;
begin
if (not Self.openned) then Exit(1);
if (HV = nil) then Exit(2);
for i := 0 to _SADY_CNT-1 do sady_change[i] := false;
for i := 0 to _HV_FUNC_MAX do
begin
if ((funkce[i] <> HV.Slot.funkce[i]) or (force)) then
begin
case i of
0..4 : sady_change[0] := true;
5..8 : sady_change[1] := true;
9..12 : sady_change[2] := true;
13..20 : sady_change[3] := true;
21..28 : sady_change[4] := true;
end;//case
HV.Slot.funkce[i] := funkce[i];
HV.Stav.funkce[i] := funkce[i];
end;
end;
GetMem(fc, sizeof(TFuncCallback));
TFuncCallback(fc^).sady := TList<TFuncCBSada>.Create();
TFuncCallback(fc^).addr := HV.adresa;
TFuncCallback(fc^).callback_ok := Self.Trakce.callback_ok;
TFuncCallback(fc^).callback_err := Self.Trakce.callback_err;
Self.callback_err := TTrakce.GenerateCallback(nil);
Self.callback_ok := TTrakce.GenerateCallback(nil);
if (sady_change[0]) then
begin
sada.index := 0;
for i := 0 to 4 do sada.func[i] := funkce[i];
TFuncCallback(fc^).sady.Add(sada);
end;
if (sady_change[1]) then
begin
sada.index := 1;
for i := 0 to 3 do sada.func[i] := funkce[i+5];
TFuncCallback(fc^).sady.Add(sada);
end;
if (sady_change[2]) then
begin
sada.index := 2;
for i := 0 to 3 do sada.func[i] := funkce[i+9];
TFuncCallback(fc^).sady.Add(sada);
end;
if (sady_change[3]) then
begin
sada.index := 3;
for i := 0 to 7 do sada.func[i] := funkce[i+13];
TFuncCallback(fc^).sady.Add(sada);
end;
if (sady_change[4]) then
begin
sada.index := 4;
for i := 0 to 7 do sada.func[i] := funkce[i+21];
TFuncCallback(fc^).sady.Add(sada);
end;
if ((sady_change[0]) or (sady_change[1]) or (sady_change[2]) or (sady_change[3]) or (sady_change[4])) then
begin
HV.Slot.funkce := funkce;
TCPRegulator.LokUpdateFunc(HV, Sender);
RegCollector.UpdateElements(Sender, HV.Slot.adresa);
HV.changed := true;
Self.FuncOK(Self, fc);
end else begin
if (Assigned(TFuncCallback(fc^).callback_ok.callback)) then
TFuncCallback(fc^).callback_ok.callback(Self, TFuncCallback(fc^).callback_ok.data);
FreeMem(fc);
end;
Result := 0;
end;//function
////////////////////////////////////////////////////////////////////////////////
function TTrkGUI.LokFuncToggle(Sender:TObject; HV:THV; fIndex:Cardinal):Byte;
var funkce:TFunkce;
begin
if (HV = nil) then Exit(2);
funkce := HV.Slot.funkce;
funkce[fIndex] := true;
Result := Self.LokSetFunc(Sender, HV, funkce);
if (Result = 0) then
Self.toggleQueue.Enqueue(HVFunc(HV, fIndex, Now+EncodeTime(0, 0, 0, 500)));
end;
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.LoksSetFunc(vyznam:string; state:boolean);
var addr, i:Integer;
cb:Pointer;
begin
for addr := 0 to _MAX_ADDR-1 do
begin
if ((HVDb.HVozidla[addr] = nil) or (not HVDb.HVozidla[addr].Slot.prevzato)) then continue;
for i := 0 to _HV_FUNC_MAX do
if ((HVDb.HVozidla[addr].Data.funcVyznam[i] = vyznam) and (HVDb.HVozidla[addr].Slot.funkce[i] <> state)) then
begin
HVDb.HVozidla[addr].Stav.funkce[i] := state;
GetMem(cb, sizeof(TFuncsCallback));
TFuncsCallback(cb^).callback_ok := Self.Trakce.callback_ok;
TFuncsCallback(cb^).callback_err := Self.Trakce.callback_err;
TFuncsCallback(cb^).addr := addr;
TFuncsCallback(cb^).vyznam := vyznam;
TFuncsCallback(cb^).state := state;
Self.callback_ok := TTrakce.GenerateCallback(Self.LoksSetFuncOK, cb);
Self.callback_err := TTrakce.GenerateCallback(Self.LoksSetFuncErr, cb);
Self.LokSetFunc(Self, HVDb.HVozidla[addr], HVDb.HVozidla[addr].Stav.funkce);
Exit();
end;//if vyznam = vyznam
end;//for i
if (Assigned(Self.Trakce.callback_ok.callback)) then Self.Trakce.callback_ok.callback(Self, Self.Trakce.callback_ok.data);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.LoadSpeedTable(filename:string;var LVRych:TListView);
var i, j:Integer;
myFile:TextFile;
begin
try
AssignFile(myFile, filename);
Reset(myFile);
except
Self.TrkLog(self, 1, 'Chyba pri nacitani souboru s rychlostmi - nepodarilo se pristoupit k souboru! Pouzivam vychozi rychlostni tabulku.');
// nacteme vychozi rychlostni tabulku
for i := 0 to _MAX_SPEED do
Self.SpeedTable[i] := _DEFAULT_SPEED_TABLE[i];
Self.LoadSpeedTableToTable(LVRych);
Exit();
end;
for i := 0 to _MAX_SPEED do
begin
if (Eof(myFile)) then
begin
Self.TrkLog(self, 1, 'Chyba pri nacitani souboru s rychlostmi - prilis malo radku! Doplnuji vychozi rychlostni tabulkou.');
CloseFile(myFile);
for j := i to _MAX_SPEED do
Self.SpeedTable[j] := _DEFAULT_SPEED_TABLE[j];
Self.LoadSpeedTableToTable(LVRych);
Exit();
end else begin
try
ReadLn(myFile, Self.SpeedTable[i]);
except
on E:Exception do
begin
Self.TrkLog(self, 1, 'Soubor s rychlostmi, řádek ' + IntToStr(i+1) + ': ' + E.Message);
Self.SpeedTable[i] := _DEFAULT_SPEED_TABLE[i];
end;
end;
end;
end;//while
CloseFile(myFile);
Self.LoadSpeedTableToTable(LVRych);
end;//function
procedure TTrkGUI.LoadSpeedTableToTable(var LVRych:TListView);
var i:Integer;
LI:TListItem;
begin
LVrych.Clear();
for i := 0 to _MAX_SPEED do
begin
LI := LVRych.Items.Add;
LI.Caption := IntToStr(i);
LI.SubItems.Add(IntToStr(Self.SpeedTable[i])+' km/h');
end;
end;
procedure TTrkGUI.SaveSpeedTable(filename:string);
var i:Integer;
myFile:TextFile;
begin
try
AssignFile(myFile, filename);
Rewrite(myFile);
except
Self.TrkLog(self,1,'Chyba pri ukladani souboru s rychlostmi - nepodarilo se pristoupit k souboru !');
Exit;
end;
for i := 0 to _MAX_SPEED do WriteLn(myFile, IntToStr(Self.SpeedTable[i]));
CloseFile(myFile);
end;//procedure
// vrati jizdni stupen prislusny k dane rychlosti v km/h
function TTrkGUI.GettSpeed(kmph:Integer):Integer;
var i:Integer;
begin
for i := 0 to _MAX_SPEED do
if (Self.SpeedTable[i] = kmph) then
Exit(i);
Exit(1); // v pripade nenalezeni rychlosti vraci nouzovy STOP
end;//fucntion
procedure TTrkGUI.BeforeOpen(Sender:TObject);
begin
F_Main.A_Trk_Connect.Enabled := false;
F_Main.A_Trk_Disconnect.Enabled := false;
F_Main.A_System_Start.Enabled := false;
F_Main.A_System_Stop.Enabled := false;
F_Main.SB1.Panels.Items[_SB_INT].Text := 'Připojování...';
F_Main.S_Intellibox_connect.Brush.Color := clBlue;
F_Main.LogStatus('Centrála: připojování...');
F_Main.B_HV_Add.Enabled := false;
F_Main.B_HV_Delete.Enabled := false;
Application.ProcessMessages();
end;//procedure
procedure TTrkGUI.AfterOpen(Sender:TObject);
begin
Self.Trakce.AfterOpen();
Self.TrkLog(self, 2, 'OPEN OK');
F_Main.A_Trk_Connect.Enabled := false;
F_Main.A_Trk_Disconnect.Enabled := true;
F_Main.SB1.Panels.Items[_SB_INT].Text := 'Centrála připojena';
F_Main.LogStatus('Centrála: připojeno');
F_Main.S_Intellibox_connect.Brush.Color := clLime;
F_Main.A_All_Loko_Prevzit.Enabled := true;
F_Main.B_CS_Ver_Update.Enabled := true;
F_Main.B_Set_LI_Addr.Enabled := true;
F_Main.SE_LI_Addr.Enabled := true;
F_Main.UpdateSystemButtons();
F_Main.A_DCC_Go.Enabled := true;
F_Main.A_DCC_Stop.Enabled := true;
F_Main.A_FuncsSet.Enabled := true;
Application.ProcessMessages();
// na STATUS se ptam vzdy
Self.InitSystems();
end;//procedure
procedure TTrkGUI.BeforeClose(Sender:TObject);
begin
F_Main.A_Trk_Connect.Enabled := false;
F_Main.A_Trk_Disconnect.Enabled := false;
F_Main.A_System_Start.Enabled := false;
F_Main.A_System_Stop.Enabled := false;
F_Main.SB1.Panels.Items[_SB_INT].Text := 'Odpojování...';
F_Main.LogStatus('Centrála: odpojování...');
F_Main.S_Intellibox_connect.Brush.Color := clBlue;
F_Main.G_Loko_Prevzato.Progress := 0;
F_Main.S_lok_prevzato.Brush.Color := clRed;
Application.ProcessMessages();
Self.Trakce.BeforeClose(); // smaze buffer historie
end;//procedure
procedure TTrkGUI.AfterClose(Sender:TObject);
var addr:Integer;
begin
Self.TrkLog(self,2,'CLOSE OK');
F_Main.A_Trk_Connect.Enabled := true;
F_Main.A_Trk_Disconnect.Enabled := false;
F_Main.SB1.Panels.Items[_SB_INT].Text := 'Centrála odpojena';
F_Main.LogStatus('Centrála: odpojena');
F_Main.S_Intellibox_connect.Brush.Color := clRed;
F_Main.A_All_Loko_Prevzit.Enabled := false;
F_Main.A_All_Loko_Odhlasit.Enabled := false;
F_Main.B_HV_Add.Enabled := true;
F_Main.B_CS_Ver_Update.Enabled := false;
F_Main.B_Set_LI_Addr.Enabled := false;
F_Main.SE_LI_Addr.Enabled := false;
F_Main.SE_LI_Addr.Value := 0;
F_Main.UpdateSystemButtons();
// zavrit vsechny regulatory
RegCollector.CloseAll();
HVTableData.LoadToTable();
F_Main.S_Intellibox_go.Brush.Color := clGray;
F_Main.A_DCC_Go.Enabled := false;
F_Main.A_DCC_Stop.Enabled := false;
F_Main.A_FuncsSet.Enabled := false;
if (F_FuncsSet.Showing) then F_FuncsSet.Close();
for addr := 0 to _MAX_ADDR-1 do
if (HVDb.HVozidla[addr] <> nil) then HVDb.HVozidla[addr].Slot.pom := TPomStatus.released;
Application.ProcessMessages();
if (SystemData.Status = stopping) then
F_Main.A_RCS_StopExecute(nil);
end;//procedure
function TTrkGUI.GetStepSpeed(step:byte):Integer;
begin
if (step > _MAX_SPEED) then Exit(-1);
Result := Self.SpeedTable[step];
end;//function
function TTrkGUI.SetSpetSpeed(step:byte;sp:Integer):Byte;
begin
if (step > _MAX_SPEED) then Exit(1);
Self.SpeedTable[step] := sp;
Result := 0;
end;//function
function TTrkGUI.EmergencyStop():Byte;
begin
if (not Self.openned) then Exit(1);
Self.TrkLog(self,2,'PUT: EMERGENCY STOP');
Self.Trakce.EmergencyStop();
Result := 0;
end;//function
function TTrkGUI.EmergencyStopAddr(addr:Integer):Byte;
begin
if (not Self.openned) then Exit(1);
if (addr < 0) then Exit(2);
if (addr > 9999) then Exit(3);
Self.TrkLog(self,2,'PUT: EMERGENCY STOP LOKO '+IntToStr(addr));
Self.Trakce.LokEmergencyStop(addr);
Result := 0;
end;//function
function TTrkGUI.EmergencyStopLoko(Sender:TObject; HV:THV):Byte;
begin
if (not Self.openned) then Exit(1);
if (HV = nil) then Exit(2);
Self.TrkLog(self,2,'PUT: EMERGENCY STOP HV '+HV.data.Nazev+' = '+IntToStr(HV.Adresa));
Self.Trakce.LokEmergencyStop(HV.Adresa);
HV.Slot.speed := 0;
Self.UpdateSpeedDir(HV, Sender, true, false);
Result := 0;
end;//fucnction
function TTrkGUI.LokGetSpSteps(HV:THV):Byte;
begin
if (not Self.openned) then Exit(1);
if (HV = nil) then Exit(2);
Self.TrkLog(self,2,'PUT: GET HV INFO '+HV.data.Nazev+' = '+IntToStr(HV.Adresa));
Self.Trakce.LokGetInfo(HV.Adresa);
Result := 0;
end;//function
////////////////////////////////////////////////////////////////////////////////
// prevzit loko do kontroly systemu:
// pri prebirani LOKO si ulozime vnejsi callbacky, abychom mohli na prevzeti aplikovat vlastni callbacky
// tyto callbacky pak zajisti nastaveni POM podle toho, jestli je loko otevrene v nejakem regulatoru
procedure TTrkGUI.PrevzitLoko(HV:THV);
var cb:Pointer;
begin
if (not Self.openned) then
begin
Self.WriteLog(1, 'ERR: COM not openned');
raise ENotOpenned.Create('COM not openned');
end;
Self.TrkLog(self, 2, 'PUT: LOK-2-MYCONTROL: '+HV.data.Nazev+' ('+IntToStr(HV.Adresa)+')');
HV.Slot.prevzato_full := false;
GetMem(cb, sizeof(TPrevzitCallback));
TPrevzitCallback(cb^).callback_ok := Self.Trakce.callback_ok;
TPrevzitCallback(cb^).callback_err := Self.Trakce.callback_err;
TPrevzitCallback(cb^).addr := HV.adresa;
if (not HV.Slot.prevzato) then
begin
// ok callback neni potreba, protoze se vola ConnectChange
Self.callback_ok := TTrakce.GenerateCallback(nil, cb); // cb tu ale presto musi byt (je potreba v ConnectChange)
Self.callback_err := TTrakce.GenerateCallback(Self.PrevzatoErr, cb);
Self.Trakce.Lok2MyControl(HV.Adresa);
end else begin
Self.callback_err := TTrakce.GenerateCallback(nil);
Self.callback_ok := TTrakce.GenerateCallback(nil);
Self.ConnectChange(Self, HV.adresa, Tconnect_code.TC_Connected, cb);
end;
end;//function
// odhlasovani loko =
// 1) POM release
// 2) odhlasit loko
procedure TTrkGUI.OdhlasitLoko(HV:THV);
var cb:Pointer;
begin
if (not Self.openned) then
begin
Self.WriteLog(1, 'ERR: COM not openned');
raise ENotOpenned.Create('COM not openned');
end;
Self.TrkLog(self, 2, 'PUT: LOK-FROM-MYCONTROL: '+HV.data.Nazev+' ('+IntToStr(HV.Adresa)+')');
GetMem(cb, sizeof(TPrevzitCallback));
TPrevzitCallback(cb^).callback_ok := Self.Trakce.callback_ok;
TPrevzitCallback(cb^).callback_err := Self.Trakce.callback_err;
TPrevzitCallback(cb^).addr := HV.adresa;
Self.callback_ok := TTrakce.GenerateCallback(Self.OdhlasenoPOMOK, cb);
Self.callback_err := TTrakce.GenerateCallback(Self.OdhlasenoPOMErr, cb);
// nenastavovat HV.ruc, POM si tady delame sami !!
HV.Stav.ruc := false;
if (HV.Slot.pom <> TPomStatus.released) then
Self.POMWriteCVs(Self, HV, HV.Data.POMrelease, TPomStatus.released)
else
Self.OdhlasenoPOMOK(Self, cb);
end;//function
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.PrevzitAll();
var i:Integer;
data:Pointer;
k_prevzeti:Integer;
begin
k_prevzeti := 0;
for i := 0 to _MAX_ADDR-1 do
begin
if (HVDb.HVozidla[i] = nil) then continue;
if ((HVDb.HVozidla[i].Slot.Prevzato) and (HVDb.HVozidla[i].Slot.pom = pc)) then continue;
if (HVDb.HVozidla[i].Stav.souprava > -1) then Inc(k_prevzeti);
end;
F_Main.G_Loko_Prevzato.MaxValue := k_prevzeti;
F_Main.G_Loko_Prevzato.Progress := 0;
F_Main.G_Loko_Prevzato.ForeColor := clBlue;
for i := 0 to _MAX_ADDR-1 do
begin
if (HVDb.HVozidla[i] = nil) then continue;
if ((HVDb.HVozidla[i].Slot.Prevzato) and (HVDb.HVozidla[i].Slot.pom = pc)) then continue;
if (HVDb.HVozidla[i].Stav.souprava > -1) then
begin
GetMem(data, sizeof(integer));
Integer(data^) := i;
Self.callback_err := TTrakce.GenerateCallback(Self.PrebiraniUpdateErr, data);
Self.callback_ok := TTrakce.GenerateCallback(Self.PrebiraniUpdateOK, data);
try
Self.PrevzitLoko(HVDb.HVozidla[i]);
except
Self.PrebiraniUpdateErr(self, data);
end;
Exit();
end;
end;
F_Main.LogStatus('Loko: žádné loko k převzetí');
F_Main.G_Loko_Prevzato.MaxValue := 1;
F_Main.G_Loko_Prevzato.Progress := 1;
Self.AllPrevzato();
end;//procedure
procedure TTrkGUI.OdhlasitAll();
var i:Integer;
data:Pointer;
k_odhlaseni:Integer;
begin
k_odhlaseni := 0;
for i := 0 to _MAX_ADDR-1 do
begin
if (HVDb.HVozidla[i] = nil) then continue;
if (HVDb.HVozidla[i].Slot.Prevzato) then Inc(k_odhlaseni);
end;
F_Main.G_Loko_Prevzato.MaxValue := k_odhlaseni;
F_Main.G_Loko_Prevzato.Progress := F_Main.G_Loko_Prevzato.MaxValue;
F_Main.G_Loko_Prevzato.ForeColor := clBlue;
for i := 0 to _MAX_ADDR-1 do
begin
if (HVDb.HVozidla[i] = nil) then continue;
if (HVDb.HVozidla[i].Slot.Prevzato) then
begin
GetMem(data, sizeof(integer));
Integer(data^) := i;
Self.callback_err := TTrakce.GenerateCallback(Self.OdhlasovaniUpdateErr, data);
Self.callback_ok := TTrakce.GenerateCallback(Self.OdhlasovaniUpdateOK, data);
Self.OdhlasitLoko(HVDb.HVozidla[i]);
Exit();
end;
end;
F_Main.LogStatus('Loko: žádné loko k odhlášení');
F_Main.G_Loko_Prevzato.MaxValue := 1;
F_Main.G_Loko_Prevzato.Progress := 0;
Self.AllOdhlaseno();
end;//procedure
////////////////////////////////////////////////////////////////////////////////
//event s TTrakce, ktery se zavola pri uspesnem pripojeni ci odhlaseni loko
// v DATA jsou ulozena data callbacku, ktery prislusi prikazu pro prevzeti
procedure TTrkGUI.ConnectChange(Sender: TObject; addr:Integer; code:TConnect_code; data:Pointer);
var data2:Pointer;
reg:THVRegulator;
begin
// existuje u nas HV vubec ?
if (HVDb.HVozidla[addr] = nil) then Exit;
//nastavit vlastnosti
case (code) of
TConnect_code.TC_Connected:begin
// 1) aktualizace slotu
HVDb.HVozidla[addr].Slot := Self.Trakce.Slot;
HVDb.HVozidla[addr].Slot.prevzato_full := false;
HVDb.HVozidla[addr].Slot.Prevzato := true;
HVDb.HVozidla[addr].Slot.stolen := false;
Self.TrkLog(self,2,'GET LOCO DATA: loko '+HVDb.HVozidla[addr].data.Nazev+' ('+IntToSTr(addr)+')');
HVDb.HVozidla[addr].changed := true;
// 2) priprava POM (POM zatim neprogramujeme, jen si pripravime flag)
HVDb.HVozidla[addr].Slot.pom := progr;
// 3) pokracujeme v prebirani, dalsi faze je ziskani stavu funkci 13-28
// 4) aktualni stav zpropagujeme do celeho programu
if (HVDb.HVozidla[addr].Stav.souprava > -1) then
Blky.ChangeUsekWithSpr(HVDb.HVozidla[addr].Stav.souprava);
RegCollector.ConnectChange(addr);
HVDb.HVozidla[addr].UpdateRuc();
// odesleme do regulatoru info o uspesne autorizaci
// to je dobre tehdy, kdyz je loko prebirano z centraly
if (HVDb.HVozidla[addr].ruc) then
for reg in HVDb.HVozidla[addr].Stav.regulators do
ORTCPServer.SendLn(reg.conn, '-;LOK;'+IntToStr(addr)+';AUTH;total;{'+HVDb.HVozidla[addr].GetPanelLokString()+'}')
else
for reg in HVDb.HVozidla[addr].Stav.regulators do
ORTCPServer.SendLn(reg.conn, '-;LOK;'+IntToStr(addr)+';AUTH;ok;{'+HVDb.HVozidla[addr].GetPanelLokString()+'}');
if (data <> nil) then
begin
data2 := data;
end else begin
GetMem(data2, sizeof(TPrevzitCallback));
TPrevzitCallback(data2^).addr := addr;
TPrevzitCallback(data2^).callback_ok := TTrakce.GenerateCallback(nil);
TPrevzitCallback(data2^).callback_err := TTrakce.GenerateCallback(nil);
end;
// 5) nacteme stav funkci 13-28
Self.callback_ok := TTrakce.GenerateCallback(Self.PrevzatoFunc1328OK, data2);
Self.callback_err := TTrakce.GenerateCallback(Self.PrevzatoErr, data2);
Self.Trakce.LokGetFunctions(addr, 13);
end;//TC_Connected
TConnect_code.TC_Unavailable:begin
// tato funkce neni na XpressNETu podporovana, proto neni dodelana
RegCollector.ConnectChange(addr);
end;
TConnect_code.TC_Disconnected:begin
HVDb.HVozidla[addr].Slot.Prevzato := false;
end;//TC_Connected
TConnect_code.TC_Stolen:begin
if (not HVDb.HVozidla[addr].Slot.prevzato) then Exit(); // tato situace muze nastat, kdyz odhlasime HV a pak si ho vezme Rocomouse
// odhlaseni HV totiz fakticky nerekne centrale, ze ji odhlasujeme
HVDb.HVozidla[addr].Slot.Prevzato := false;
HVDb.HVozidla[addr].Slot.stolen := true;
RegCollector.Stolen(addr);
TCPRegulator.LokStolen(HVDb.HVozidla[addr]);
if (HVDb.HVozidla[addr].Stav.souprava > -1) then
Blky.ChangeUsekWithSpr(HVDb.HVozidla[addr].Stav.souprava);
HVDb.HVozidla[addr].UpdateRuc();
// zapiseme POM rucniho rizeni
Self.POMWriteCVs(Self, HVDb.HVozidla[addr], HVDb.HVozidla[addr].Data.POMrelease, TPomStatus.released);
end;//TC_Connected
end;//case
HVDb.HVozidla[addr].changed := true;
end;//procedure
procedure TTrkGUI.SetLoglevelFile(ll:TTrkLogLevel);
begin
Self.flogfile := ll;
Self.WriteLog(2, 'NEW loglevel_file = '+LogLevelToString(ll));
end;
procedure TTrkGUI.SetLoglevelTable(ll:TTrkLogLevel);
begin
Self.flogtable := ll;
Self.WriteLog(2, 'NEW loglevel_table = '+LogLevelToString(ll));
end;
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.InitSystems();
begin
F_Main.LogStatus('Centrála: testuji komunikaci - vysílám povel STATUS');
Self.callback_err := TTrakce.GenerateCallback(Self.InitStatErr);
Self.callback_ok := TTrakce.GenerateCallback(Self.InitStatOK);
Self.Trakce.GetTrackStatus();
end;//procedure
procedure TTrkGUI.InitStatErr(Sender:TObject; Data:Pointer);
begin
F_Main.LogStatus('WARN: Centrála: neodpověděla na příkaz STATUS, zkouším příkaz STOP...');
Self.callback_err := TTrakce.GenerateCallback(Self.InitStopErr);
Self.callback_ok := TTrakce.GenerateCallback(Self.InitStopOK);
Self.CentralStop();
end;//procedure
procedure TTrkGUI.InitStatOK(Sender:TObject; Data:Pointer);
begin
Self.finitok := true;
F_Main.LogStatus('Centrála: komunikuje');
F_Main.LogStatus('Zjišťuji verzi FW v centrále...');
Self.callback_ok := TTrakce.GenerateCallback(Self.GotCSVersionOK);
Self.callback_err := TTrakce.GenerateCallback(Self.GotCSVersionErr);
Self.GetCSVersion();
end;//procedure
procedure TTrkGUI.InitStopErr(Sender:TObject; Data:Pointer);
begin
Self.finitok := false;
F_Main.LogStatus('ERR: Centrála: neodpověděla na příkaz STOP !');
SystemData.Status := TSystemStatus.null;
F_Main.A_System_Start.Enabled := true;
F_Main.A_System_Stop.Enabled := true;
Application.MessageBox('Centrála neodpověděla na příkaz STATUS a STOP', 'Nelze pokračovat', MB_OK OR MB_ICONWARNING);
end;//procedure
procedure TTrkGUI.InitStopOK(Sender:TObject; Data:Pointer);
begin
Self.finitok := true;
F_Main.LogStatus('Centrála: komunikuje');
Self.callback_ok := TTrakce.GenerateCallback(Self.GotCSVersionOK);
Self.callback_err := TTrakce.GenerateCallback(Self.GotCSVersionErr);
Self.GetCSVersion();
if (SystemData.Status = starting) then
begin
// poslali jsme STOP -> je jasne, ze musime DCC opet zapnout
F_Main.A_DCC_GoExecute(self)
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.SetCallbackErr(callback_err:TCommandCallback);
begin
Self.Trakce.callback_err := callback_err;
end;//procedure
procedure TTrkGUI.SetCallbackOK(callback_ok:TCommandCallback);
begin
Self.Trakce.callback_ok := callback_ok;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// eventy pri prebirani vsech LOKO:
procedure TTrkGUI.PrebiraniUpdateOK(Sender:TObject; Data:Pointer);
var i:Integer;
begin
F_Main.G_Loko_Prevzato.Progress := F_Main.G_Loko_Prevzato.Progress + 1;
F_Main.G_Loko_Prevzato.ForeColor := clBlue;
for i := Integer(data^) to _MAX_ADDR-1 do
begin
if ((HVDb.HVozidla[i] = nil) or ((HVDb.HVozidla[i].Slot.Prevzato) and ((HVDb.HVozidla[i].Slot.pom = released) or (HVDb.HVozidla[i].Slot.pom = pc)))) then continue;
if (HVDb.HVozidla[i].Stav.souprava > -1) then
begin
Integer(data^) := i;
Self.callback_err := TTrakce.GenerateCallback(Self.PrebiraniUpdateErr, data);
Self.callback_ok := TTrakce.GenerateCallback(Self.PrebiraniUpdateOK, data);
try
Self.PrevzitLoko(HVDb.HVozidla[i]);
except
Self.PrebiraniUpdateErr(self, data);
end;
Exit();
end;
end;
// zadne dalsi loko k prevzeti
FreeMem(data);
Application.ProcessMessages();
F_Main.LogStatus('Loko: všechna loko převzata');
Self.AllPrevzato();
end;//procedure
procedure TTrkGUI.PrebiraniUpdateErr(Sender:TObject; Data:Pointer);
begin
Self.WriteLog(1, 'ERR: LOKO '+ IntToStr(Integer(data^)) + ' se nepodařilo převzít');
F_Main.LogStatus('LOKO: loko '+ IntToStr(Integer(data^)) + ' se nepodařilo převzít');
F_Main.G_Loko_Prevzato.ForeColor := clRed;
F_Main.S_lok_prevzato.Brush.Color := clRed;
F_Main.A_All_Loko_Prevzit.Enabled := true;
if (SystemData.Status = TSystemStatus.starting) then
begin
SystemData.Status := TSystemStatus.null;
F_Main.A_System_Start.Enabled := true;
F_Main.A_System_Stop.Enabled := true;
end;
Application.MessageBox(PChar('LOKO '+ IntToStr(Integer(data^)) + ' se nepodařilo převzít'), 'Chyba', MB_OK OR MB_ICONWARNING);
FreeMem(data);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// eventy pri odhlasovani vech LOKO:
procedure TTrkGUI.OdhlasovaniUpdateOK(Sender:TObject; Data:Pointer);
var i:Integer;
begin
F_Main.G_Loko_Prevzato.Progress := F_Main.G_Loko_Prevzato.Progress - 1;
F_Main.G_Loko_Prevzato.ForeColor := clBlue;
// loko odhlaseno -> najdeme dalsi k odhlaseni a naprogramujeme POM
for i := Integer(data^) to _MAX_ADDR-1 do
begin
if (HVDb.HVozidla[i] = nil) then continue;
if (HVDb.HVozidla[i].Slot.Prevzato) then
begin
Integer(data^) := i;
Self.callback_err := TTrakce.GenerateCallback(Self.OdhlasovaniUpdateErr, data);
Self.callback_ok := TTrakce.GenerateCallback(Self.OdhlasovaniUpdateOK, data);
try
Self.OdhlasitLoko(HVDb.HVozidla[i]);
except
on E:Exception do
begin
Self.callback_err := TTrakce.GenerateCallback(nil);
Self.callback_ok := TTrakce.GenerateCallback(nil);
FreeMem(data);
F_Main.LogStatus('Výjimka: ' + E.Message);
end;
end;
Exit();
end;
end;
// zadne dalsi loko k odhlaseni
FreeMem(data);
F_Main.LogStatus('Loko: všechna loko odhlášena');
Application.ProcessMessages();
Self.AllOdhlaseno();
end;//procedure
procedure TTrkGUI.OdhlasovaniUpdateErr(Sender:TObject; Data:Pointer);
begin
// pokud behem odhlasovani loko nastane chyba, nahlasime ji, ale loko povazujeme za odhlasene
Self.WriteLog(1, 'WARN: Loko '+IntToStr(Integer(data^))+ ' se nepodařilo odhlásit');
F_Main.LogStatus('WARN: Loko '+IntToStr(Integer(data^))+ ' se nepodařilo odhlásit');
F_Main.G_Loko_Prevzato.ForeColor := clRed;
HVDb.HVozidla[Integer(data^)].Slot.prevzato := false;
HVDb.HVozidla[Integer(data^)].Slot.prevzato_full := false;
Self.OdhlasovaniUpdateOK(Self, data);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// callback funkce pri prebirani jednoho HV a pri programovani POM (pri prebirani):
procedure TTrkGUI.PrevzatoErr(Sender:TObject; Data:Pointer);
begin
// loko se nepodarilo prevzit -> zavolat error callback
if (Assigned(TPrevzitCallback(data^).callback_err.callback)) then
TPrevzitCallback(data^).callback_err.callback(Self, TPrevzitCallback(data^).callback_err.data);
FreeMem(data);
end;//procedure
procedure TTrkGUI.PrevzatoPOMOK(Sender:TObject; Data:Pointer);
begin
// HV konecne kompletne prevzato
HVDb.HVozidla[TPrevzitCallback(data^).addr].Slot.prevzato_full := true;
// volame OK callback
if (Assigned(TPrevzitCallback(data^).callback_ok.callback)) then
TPrevzitCallback(data^).callback_ok.callback(Self, TPrevzitCallback(data^).callback_ok.data);
FreeMem(data);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.PrevzatoFunc1328OK(Sender:TObject; Data:Pointer);
var i:Integer;
HV:THV;
smer:Integer;
begin
HV := HVDb.HVozidla[TPrevzitCallback(data^).addr];
// nacetli jsme stav funkci 13-28 -> stav ulozime do slotu
for i := 13 to 28 do
HV.Slot.funkce[i] := Self.Trakce.Slot.funkce[i];
// pokud ma souprava jasne dany smer, nastavime ho
// podminka na sipky je tu kvuli prebirani z RUCniho rizeni z XpressNETu
if ((HV.Stav.souprava > -1) and
(Soupravy[HV.Stav.souprava].sdata.smer_L xor Soupravy[HV.Stav.souprava].sdata.smer_S)) then
begin
// souprava ma zadany prave jeden smer
smer := (Integer(Soupravy[HV.Stav.souprava].smer) xor Integer(HV.Stav.StanovisteA));
if ((smer = HV.Slot.smer) and (HV.Slot.speed = 0)) then
begin
// smer ok
Self.PrevzatoSmerOK(Sender, Data);
Exit();
end else begin
// smer nok -> aktualizovat smer
Self.callback_ok := TTrakce.GenerateCallback(Self.PrevzatoSmerOK, data);
Self.callback_err := TTrakce.GenerateCallback(Self.PrevzatoErr, data);
Self.LokSetDirectSpeed(nil, HV, 0, smer);
end;
end else
Self.PrevzatoSmerOK(Sender, Data);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.PrevzatoSmerOK(Sender:TObject; Data:Pointer);
begin
// nastavime funkce tak, jak je chceme my
Self.callback_ok := TTrakce.GenerateCallback(Self.PrevzatoFuncOK, data);
Self.callback_err := TTrakce.GenerateCallback(Self.PrevzatoFuncErr, data);
Self.LokSetFunc(nil, HVDb.HVozidla[TPrevzitCallback(data^).addr], HVDb.HVozidla[TPrevzitCallback(data^).addr].Stav.funkce);
end;
////////////////////////////////////////////////////////////////////////////////
// callback funkce pri odhlasovani hnaciho vozidla a pri programovani POM pri odhlasovani:
procedure TTrkGUI.OdhlasenoOK(Sender:TObject; Data:Pointer);
begin
// loko odhlaseno a POM nastaveno -> volame OK callback
if (Assigned(TPrevzitCallback(data^).callback_ok.callback)) then
TPrevzitCallback(data^).callback_ok.callback(Self, TPrevzitCallback(data^).callback_ok.data);
FreeMem(data);
end;//procedure
procedure TTrkGUI.OdhlasenoErr(Sender:TObject; Data:Pointer);
begin
// POM nastaveno, ale loko neodhlaseno -> volame error callback
if (Assigned(TPrevzitCallback(data^).callback_err.callback)) then
TPrevzitCallback(data^).callback_err.callback(Self, TPrevzitCallback(data^).callback_err.data);
FreeMem(data);
end;//procedure
procedure TTrkGUI.OdhlasenoPOMOK(Sender:TObject; Data:Pointer);
begin
// release POM uspesne naprogramovano -> odhlasit loko
if (Assigned(HVDb.HVozidla[TPrevzitCallback(data^).addr])) then
begin
HVDb.HVozidla[TPrevzitCallback(data^).addr].changed := true;
RegCollector.ConnectChange(TPrevzitCallback(data^).addr);
end;
Self.callback_ok := TTrakce.GenerateCallback(Self.OdhlasenoOK, data);
Self.callback_err := TTrakce.GenerateCallback(Self.OdhlasenoErr, data);
Self.Trakce.LokFromMyControl(TPrevzitCallback(data^).addr);
end;//procedure
procedure TTrkGUI.OdhlasenoPOMErr(Sender:TObject; Data:Pointer);
begin
// release POM error -> zavolat error callback
if (Assigned(TPrevzitCallback(data^).callback_err.callback)) then
TPrevzitCallback(data^).callback_err.callback(Self, TPrevzitCallback(data^).callback_err.data);
FreeMem(data);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.AllPrevzato();
begin
F_Main.S_lok_prevzato.Brush.Color := clLime;
F_Main.A_All_Loko_Prevzit.Enabled := false;
F_Main.A_All_Loko_Odhlasit.Enabled := true;
F_Main.G_Loko_Prevzato.Progress := HVDb.cnt;
F_Main.G_Loko_Prevzato.ForeColor := clLime;
if (SystemData.Status = starting) then
F_Main.A_PanelServer_StartExecute(nil);
end;//procedure
procedure TTrkGUI.AllOdhlaseno();
begin
F_Main.S_lok_prevzato.Brush.Color := clRed;
F_Main.A_All_Loko_Prevzit.Enabled := true;
F_Main.A_All_Loko_Odhlasit.Enabled := false;
F_Main.G_Loko_Prevzato.Progress := 0;
F_Main.G_Loko_Prevzato.ForeColor := clBlue;
if (SystemData.Status = stopping) then
F_Main.SetCallMethod(F_Main.A_Trk_DisconnectExecute);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.LokComErr(Sender:TObject; addr:Integer);
begin
if (not Assigned(HVDb.HVozidla[addr])) then Exit();
if (not HVDb.HVozidla[addr].Slot.com_err) then
begin
HVDb.HVozidla[addr].Slot.com_err := true;
HVDb.HVozidla[addr].changed := true;
end;
end;//procedure
procedure TTrkGUI.LokComOK(Sender:TObject; addr:Integer);
begin
if (not Assigned(HVDb.HVozidla[addr])) then Exit();
if (HVDb.HVozidla[addr].Slot.com_err) then
begin
HVDb.HVozidla[addr].Slot.com_err := false;
HVDb.HVozidla[addr].changed := true;
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.OnComError(Sender: TObject; Errors: TComErrors);
begin
Self.WriteLog(1, 'ERR: COM PORT ERROR');
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.OnComException(Sender: TObject;
TComException: TComExceptions; ComportMessage: string; WinError: Int64;
WinMessage: string);
begin
Self.WriteLog(1, 'ERR: COM PORT EXCEPTION: '+ComportMessage+'; '+WinMessage);
raise Exception.Create(ComportMessage);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.OnTrackStatusChange(Sender: TObject);
begin
if (Self.Trakce.TrackStatus = Ttrk_status.TS_ON) then Self.DCCGoTime := Now;
F_Main.OnCentralaDCCChange(Self, Self.Trakce.TrackStatus = Ttrk_status.TS_ON);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
function TTrkGUI.GetTrkStatus():Ttrk_status;
begin
Result := Self.Trakce.TrackStatus;
end;//function
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.OnComWriteError(Sender:TObject);
begin
if (Self.openned) then Self.Close(true);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// tato funkce je volana pri vypnuti systemu / vypne u vsech hnacich vozidel zvuk
// zvuk si ale zapamatuje jako zaply pro pristi nabeh systemu
procedure TTrkGUI.TurnOffFunctions(callback:TNotifyEvent);
var i, j:Integer;
func:Integer;
newfuncs:TFunkce;
addr:Pointer;
begin
if (Assigned(Self.turnoff_callback)) then Exit();
Self.turnoff_callback := callback;
F_Main.LogStatus('Vypínám zvuky hnacích vozidel...');
Application.ProcessMessages();
for i := 0 to _MAX_ADDR-1 do
begin
if ((HVDb.HVozidla[i] <> nil) and (HVDb.HVozidla[i].Slot.prevzato) and (not HVDb.HVozidla[i].Slot.stolen)) then
begin
func := -1;
for j := 0 to _HV_FUNC_MAX do
if ((HVDb.HVozidla[i].Data.funcVyznam[j] = 'zvuk') and (HVDb.HVozidla[i].Slot.funkce[j])) then
begin
func := j;
break;
end;
if (func = -1) then continue;
GetMem(addr, 3);
Integer(addr^) := i;
newfuncs := HVDb.HVozidla[i].Stav.funkce;
newfuncs[func] := false;
Self.callback_err := Trakce.GenerateCallback(Self.TurnOffFunctions_cmdOK, addr);
Self.callback_ok := Trakce.GenerateCallback(Self.TurnOffFunctions_cmdOK, addr);
Self.LokSetFunc(Self, HVDb.HVozidla[i], newfuncs);
HVDb.HVozidla[i].Stav.funkce[func] := true;
Exit();
end;
end;//for i
// no loco
if Assigned(Self.turnoff_callback) then
begin
Self.turnoff_callback(Self);
Self.turnoff_callback := nil;
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.TurnOffFunctions_cmdOK(Sender:TObject; Data:Pointer);
var i, j:Integer;
func:Integer;
newfuncs:TFunkce;
begin
for i := Integer(data^)+1 to _MAX_ADDR-1 do
begin
if ((HVDb.HVozidla[i] <> nil) and (HVDb.HVozidla[i].Slot.prevzato) and (not HVDb.HVozidla[i].Slot.stolen)) then
begin
func := -1;
for j := 0 to _HV_FUNC_MAX do
if ((HVDb.HVozidla[i].Data.funcVyznam[j] = 'zvuk') and (HVDb.HVozidla[i].Slot.funkce[j])) then
begin
func := j;
break;
end;
if (func = -1) then continue;
Integer(data^) := i;
newfuncs := HVDb.HVozidla[i].Stav.funkce;
newfuncs[func] := false;
Self.callback_err := Trakce.GenerateCallback(Self.TurnOffFunctions_cmdOK, data);
Self.callback_ok := Trakce.GenerateCallback(Self.TurnOffFunctions_cmdOK, data);
Self.LokSetFunc(Self, HVDb.HVozidla[i], newfuncs);
HVDb.HVozidla[i].Stav.funkce[func] := true;
Exit();
end;
end;//for i
// no further loco
F_Main.LogStatus('Zvuky všech hnacích vozidel vypnuty');
Application.ProcessMessages();
FreeMem(data);
if Assigned(Self.turnoff_callback) then
begin
Self.turnoff_callback(Self);
Self.turnoff_callback := nil;
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.GotCSVersion(Sender:TObject; version:TCSVersion);
begin
F_Main.L_CS_FW.Caption := IntToStr(version.major) + '.' + IntToStr(version.minor);
F_Main.L_CS_ID.Caption := IntToStr(version.id);
F_Main.L_CS_UpdateTime.Caption := FormatDateTime('dd.mm.yyyy hh:nn:ss', Now);
F_Main.LogStatus('FW v centrále: '+IntToStr(version.major) + '.' + IntToStr(version.minor) + ', id: '+IntToStr(version.id));
end;//procedure
procedure TTrkGUI.GotLIVersion(Sender:TObject; version:TLIVersion);
begin
F_Main.L_CS_LI_FW.Caption := 'HW: ' + IntToStr(version.hw_major) + '.' + IntToStr(version.hw_minor) +
', SW: ' + IntToStr(version.sw_major) + '.' + IntToStr(version.sw_minor);
F_Main.L_CS_UpdateTime.Caption := FormatDateTime('dd.mm.yyyy hh:nn:ss', Now);
F_Main.LogStatus('FW v LI: '+F_Main.L_CS_LI_FW.Caption);
end;//procedure
procedure TTrkGUI.GotLIAddress(Sender:TObject; addr:Byte);
begin
F_Main.SE_LI_Addr.Value := addr;
F_Main.SE_LI_Addr.Enabled := true;
F_Main.B_Set_LI_Addr.Enabled := true;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.GetCSVersion();
begin
Self.Trakce.GetCSVersion(Self.GotCSVersion);
end;//procedure
procedure TTrkGUI.GetLIVersion();
begin
Self.Trakce.GetLIVersion(Self.GotLIVersion);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.GetLIAddress();
begin
Self.Trakce.GetLIAddress(Self.GotLIAddress);
end;
procedure TTrkGUI.SetLIAddress(addr:Byte);
begin
Self.Trakce.SetLIAddress(Self.GotLIAddress, addr);
end;
////////////////////////////////////////////////////////////////////////////////
function TTrkGUI.POMWriteCV(Sender:TObject; HV:THV; cv:Word; data:byte):Integer;
begin
if (not Self.openned) then Exit(1);
if (HV = nil) then Exit(2);
Self.TrkLog(self, 2, 'PUT: POM '+HV.data.Nazev+' ('+IntToStr(HV.Adresa)+') : '+IntToStr(cv)+':'+IntToStr(data));
Self.Trakce.POMWriteCV(HV.adresa, cv, data);
Result := 0;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// zapsat seznam vsech cv v listu
procedure TTrkGUI.POMWriteCVs(Sender:TObject; HV:THV; list:TList<THVPomCV>; new:TPomStatus);
var data:Pointer;
begin
// vytvorime si callback
GetMem(data, sizeof(TPOMCallback));
TPOMCallback(data^).addr := HV.adresa;
TPOMCallback(data^).list := list;
TPOMCallback(data^).callback_ok := Self.Trakce.callback_ok;
TPOMCallback(data^).callback_err := Self.Trakce.callback_err;
TPOMCallback(data^).index := 0;
TPOMCallback(data^).new := new;
HV.Slot.pom := progr;
HV.changed := true;
if (list.Count < 1) then
begin
Self.callback_err := TTrakce.GenerateCallback(nil);
Self.callback_ok := TTrakce.GenerateCallback(nil);
Self.POMCvWroteOK(Self, data);
end else begin
// callback pro jednotlive pom
Self.callback_err := TTrakce.GenerateCallback(Self.POMCvWroteErr, data);
Self.callback_ok := TTrakce.GenerateCallback(Self.POMCvWroteOK, data);
Self.POMWriteCV(Sender, HV, list[0].cv, list[0].data);
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.POMCvWroteOK(Sender:TObject; Data:Pointer);
begin
if (TPOMCallback(data^).index >= (TPOMCallback(data^).list.Count-1)) then
begin
// posledni data -> zavolame OK event
if (Assigned(HVDb.HVozidla[TPOMCallback(data^).addr])) then
begin
HVDb.HVozidla[TPOMCallback(data^).addr].Slot.pom := TPOMCallback(data^).new;
HVDb.HVozidla[TPOMCallback(data^).addr].changed := true;
RegCollector.ConnectChange(TPOMCallback(data^).addr);
// HVDb.HVozidla[TPOMCallback(data^).addr].UpdateRuc(); zakomentovano - resi se pri RUC hanciho vozidla
end;
if (Assigned(TPOMCallback(data^).callback_ok.callback)) then TPOMCallback(data^).callback_ok.callback(Self, TPOMCallback(data^).callback_ok.data);
FreeMem(data);
end else begin
// odesleme dalsi data
TPOMCallback(data^).index := TPOMCallback(data^).index+1;
Self.callback_err := TTrakce.GenerateCallback(Self.POMCvWroteErr, data);
Self.callback_ok := TTrakce.GenerateCallback(Self.POMCvWroteOK, data);
Self.POMWriteCV(Sender, HVDB.HVozidla[TPOMCallback(data^).addr], TPOMCallback(data^).list[TPOMCallback(data^).index].cv, TPOMCallback(data^).list[TPOMCallback(data^).index].data);
end;// else konec dat
end;//procedure
// pokud pri POMu nastane chyba, zavolame Error callback a ukoncime programovani
procedure TTrkGUI.POMCvWroteErr(Sender:TObject; Data:Pointer);
begin
if (Assigned(HVDb.HVozidla[TPOMCallback(data^).addr])) then
begin
HVDb.HVozidla[TPOMCallback(data^).addr].Slot.pom := TPomStatus.error;
HVDb.HVozidla[TPOMCallback(data^).addr].changed := true;
RegCollector.ConnectChange(TPOMCallback(data^).addr);
// HVDb.HVozidla[TPOMCallback(data^).addr].UpdateRuc(); resi se pri RUC hnaciho vozidla
end;
if (Assigned(TPOMCallback(data^).callback_err.callback)) then
TPOMCallback(data^).callback_err.callback(Self, TPOMCallback(data^).callback_err.data);
FreeMem(data);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.NouzReleaseCallbackErr(Sender:TObject; Data:Pointer);
begin
HVDb.HVozidla[Integer(data^)].Slot.prevzato := false;
HVDb.HVozidla[Integer(data^)].Slot.prevzato_full := false;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.GotCSVersionOK(Sender:TObject; Data:Pointer);
begin
Self.callback_ok := TTrakce.GenerateCallback(Self.GotLIVersionOK);
Self.callback_err := TTrakce.GenerateCallback(Self.GotLIVersionErr);
Self.GetLIVersion();
Self.callback_err := TTrakce.GenerateCallback(Self.GotLIAddrErr);
Self.GetLIAddress();
end;//procedure
procedure TTrkGUI.GotCSVersionErr(Sender:TObject; Data:Pointer);
begin
F_Main.LogStatus('WARN: Centrála nepodvěděla na požadavek o verzi centrály, pokračuji...');
Self.GotCSVersionOK(Self, data);
end;//procedure
procedure TTrkGUI.GotLIVersionOK(Sender:TObject; Data:Pointer);
begin
if (SystemData.Status = starting) then
begin
if (Self.Trakce.TrackStatus <> Ttrk_status.TS_ON) then
F_Main.A_DCC_GoExecute(self)
else
F_Main.A_All_Loko_PrevzitExecute(nil);
end;
end;//procedure
procedure TTrkGUI.GotLIVersionErr(Sender:TObject; Data:Pointer);
begin
F_Main.LogStatus('WARN: Centrála neodpověděla na požadavek o verzi LI, pokračuji...');
Self.GotLIVersionOK(Self, data);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.GotLIAddrErr(Sender:TObject; Data:Pointer);
begin
F_Main.LogStatus('WARN: Centrála neodpověděla na požadavek o adresu LI');
end;
////////////////////////////////////////////////////////////////////////////////
// callbacky pri nastavovani funkci hnacicho vozidel (F0-Fn)
// data jsou TFuncCallback
procedure TTrkGUI.FuncOK(Sender:TObject; Data:Pointer);
var i:Integer;
func:Byte;
sada:Integer;
s:string;
begin
if (TFuncCallback(data^).sady.Count < 1) then
begin
// vsechny sady nastaveny
TFuncCallback(data^).sady.Free();
if (Assigned(TFuncCallback(data^).callback_ok.callback)) then
TFuncCallback(data^).callback_ok.callback(Self, TFuncCallback(data^).callback_ok.data);
FreeMem(data);
end else begin
// nastavit dalsi sadu
// vypocet func bytu pro jednotlive sady separatne:
sada := TFuncCallback(data^).sady[0].index;
case (sada) of
0:begin
for i := 0 to 4 do s := s + IntToStr(PrevodySoustav.BoolToInt(TFuncCallback(data^).sady[0].func[i]));
Self.TrkLog(self, 2, 'PUT: LOK FUNC 0-4: '+HVDb.HVozidla[TFuncCallback(data^).addr].Data.Nazev+' ('+IntToStr(TFuncCallback(data^).addr)+') : '+s);
func := 0;
for i := 0 to 3 do if (TFuncCallback(data^).sady[0].func[i+1]) then func := func or (1 shl (i+1));
if (TFuncCallback(data^).sady[0].func[0]) then func := func or 1;
end;
1: begin
for i := 0 to 3 do s := s + IntToStr(PrevodySoustav.BoolToInt(TFuncCallback(data^).sady[0].func[i]));
Self.TrkLog(self, 2, 'PUT: LOK FUNC 5-8: '+HVDb.HVozidla[TFuncCallback(data^).addr].Data.Nazev+' ('+IntToStr(TFuncCallback(data^).addr)+') : '+s);
func := 0;
for i := 0 to 3 do if (TFuncCallback(data^).sady[0].func[i]) then func := func or (1 shl i);
end;
2: begin
for i := 0 to 3 do s := s + IntToStr(PrevodySoustav.BoolToInt(TFuncCallback(data^).sady[0].func[i]));
Self.TrkLog(self, 2, 'PUT: LOK FUNC 9-12: '+HVDb.HVozidla[TFuncCallback(data^).addr].Data.Nazev+' ('+IntToStr(TFuncCallback(data^).addr)+') : '+s);
func := 0;
for i := 0 to 3 do if (TFuncCallback(data^).sady[0].func[i]) then func := func or (1 shl i);
end;
3: begin
for i := 0 to 7 do s := s + IntToStr(PrevodySoustav.BoolToInt(TFuncCallback(data^).sady[0].func[i]));
Self.TrkLog(self, 2, 'PUT: LOK FUNC 13-20: '+HVDb.HVozidla[TFuncCallback(data^).addr].Data.Nazev+' ('+IntToStr(TFuncCallback(data^).addr)+') : '+s);
func := 0;
for i := 0 to 7 do if (TFuncCallback(data^).sady[0].func[i]) then func := func or (1 shl i);
end;
4: begin
for i := 0 to 7 do s := s + IntToStr(PrevodySoustav.BoolToInt(TFuncCallback(data^).sady[0].func[i]));
Self.TrkLog(self, 2, 'PUT: LOK FUNC 21-28: '+HVDb.HVozidla[TFuncCallback(data^).addr].Data.Nazev+' ('+IntToStr(TFuncCallback(data^).addr)+') : '+s);
func := 0;
for i := 0 to 7 do if (TFuncCallback(data^).sady[0].func[i]) then func := func or (1 shl i);
end;
else
// neznama sada -> konec
TFuncCallback(data^).sady.Free();
if (Assigned(TFuncCallback(data^).callback_ok.callback)) then
TFuncCallback(data^).callback_ok.callback(Self, TFuncCallback(data^).callback_ok.data);
FreeMem(data);
Exit();
end;
TFuncCallback(data^).sady.Delete(0); // prvni sada zpracovana
Self.callback_ok := TTrakce.GenerateCallback(Self.FuncOK, data);
Self.callback_err := TTrakce.GenerateCallback(Self.FuncErr, data);
Self.Trakce.LokSetFunc(TFuncCallback(data^).addr, sada, func);
end;
end;//procedure
procedure TTrkGUI.FuncErr(Sender:TObject; Data:Pointer);
begin
// chyba pri nastavovani funkci -> zavolame error callback
TFuncCallback(data^).sady.Free();
if (Assigned(TFuncCallback(data^).callback_err.callback)) then
TFuncCallback(data^).callback_err.callback(Self, TFuncCallback(data^).callback_err.data);
FreeMem(data);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// callbacky pri nastavovani funkci hnaciho vozidla pri prebirani:
procedure TTrkGUI.PrevzatoFuncOK(Sender:TObject; Data:Pointer);
begin
// HV prevzato a funkce nastaveny -> nastavit POM
Self.callback_ok := TTrakce.GenerateCallback(Self.PrevzatoPOMOK, data);
Self.callback_err := TTrakce.GenerateCallback(Self.PrevzatoErr, data);
if ((RegCollector.IsLoko(HVDb.HVozidla[TPrevzitCallback(data^).addr])) or (HVDb.HVozidla[TPrevzitCallback(data^).addr].ruc)) then
begin
// rucni rizeni
HVDb.HVozidla[TPrevzitCallback(data^).addr].Stav.ruc := true;
Self.POMWriteCVs(Self, HVDb.HVozidla[TPrevzitCallback(data^).addr], HVDb.HVozidla[TPrevzitCallback(data^).addr].Data.POMrelease, TPomStatus.released);
end else begin
// rizeni automatem
HVDb.HVozidla[TPrevzitCallback(data^).addr].Stav.ruc := false;
Self.POMWriteCVs(Self, HVDb.HVozidla[TPrevzitCallback(data^).addr], HVDb.HVozidla[TPrevzitCallback(data^).addr].Data.POMtake, TPomStatus.pc);
end;
end;//procedure
procedure TTrkGUI.PrevzatoFuncErr(Sender:TObject; Data:Pointer);
begin
// loko prevzato, ale funkce se nepodarilo nastavit -> error callback
Self.WriteLog(1, 'WARN: LOKO '+ IntToStr(TPrevzitCallback(data^).addr) + ' se nepodařilo nastavit funkce');
F_Main.LogStatus('WARN: loko '+ IntToStr(TPrevzitCallback(data^).addr) + ' se nepodařilo nastavit funkce');
Self.PrevzatoFuncOK(Self, data);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
// callbacky hromadneho nastavovani funkci dle vyznamu:
// napr. zapni "zvuk" vsech hnacich vozidel
procedure TTrkGUI.LoksSetFuncOK(Sender:TObject; Data:Pointer);
var addr, i:Integer;
begin
for addr := TFuncsCallback(data^).addr+1 to _MAX_ADDR-1 do
begin
if ((HVDb.HVozidla[addr] = nil) or (not HVDb.HVozidla[addr].Slot.prevzato)) then continue;
for i := 0 to _HV_FUNC_MAX do
if ((HVDb.HVozidla[addr].Data.funcVyznam[i] = TFuncsCallback(data^).vyznam) and (HVDb.HVozidla[addr].Slot.funkce[i] <> TFuncsCallback(data^).state)) then
begin
HVDb.HVozidla[addr].Stav.funkce[i] := TFuncsCallback(data^).state;
TFuncsCallback(data^).addr := addr;
Self.callback_ok := TTrakce.GenerateCallback(Self.LoksSetFuncOK, data);
Self.callback_err := TTrakce.GenerateCallback(Self.LoksSetFuncErr, data);
Self.LokSetFunc(Self, HVDb.HVozidla[addr], HVDb.HVozidla[addr].Stav.funkce);
Exit();
end;//if vyznam = vyznam
end;//for i
if (Assigned(TFuncsCallback(data^).callback_ok.callback)) then TFuncsCallback(data^).callback_ok.callback(Self, TFuncsCallback(data^).callback_ok.data);
FreeMem(data);
end;//procedure
procedure TTrkGUI.LoksSetFuncErr(Sender:TObject; Data:Pointer);
begin
// sem lze pridat oznameni chyby
Self.LoksSetFuncOK(Sender, Data);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.FastResetLoko();
var i:Integer;
begin
for i := 0 to _MAX_ADDR-1 do
begin
if (HVDb.HVozidla[i] = nil) then continue;
if (HVDb.HVozidla[i].Slot.Prevzato) then
begin
HVDb.HVozidla[i].Slot.Prevzato := false;
HVDb.HVozidla[i].Slot.pom := TPomStatus.released;
end;
end;//for i
Self.AllOdhlaseno();
end;
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.NouzReleaseLoko();
var i:Integer;
data:Pointer;
begin
GetMem(data, sizeof(integer));
for i := 0 to _MAX_ADDR-1 do
begin
if (HVDb.HVozidla[i] = nil) then continue;
try
if (HVDb.HVozidla[i].Slot.prevzato) then
begin
Integer(data^) := i;
Self.callback_err := TTrakce.GenerateCallback(Self.NouzReleaseCallbackErr, data);
try
Self.OdhlasitLoko(HVDb.HVozidla[i]);
except
on E:Exception do
FreeMem(data);
end;
end;
while (HVDb.HVozidla[i].Slot.prevzato) do
begin
sleep(1);
Application.ProcessMessages;
end;
except
end;
end;
FreeMem(data);
end;
////////////////////////////////////////////////////////////////////////////////
class function TTrkGUI.LogLevelToString(ll:TTrkLogLevel):string;
begin
case ll of
TTrkLogLevel.tllNo : Result := 'žádné zprávy';
TTrkLogLevel.tllErrors : Result := 'chyby';
TTrkLogLevel.tllCommands : Result := 'příkazy';
TTrkLogLevel.tllData : Result := 'data';
TTrkLogLevel.tllChanges : Result := 'změny stavů';
TTrkLogLevel.tllDetail : Result := 'podrobné informace';
else
Result := 'neznámý';
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.UpdateSpeedDir(HV:THV; Sender:TObject; speed:boolean; dir:boolean);
begin
TCPRegulator.LokUpdateSpeed(HV, Sender);
RegCollector.UpdateElements(Sender, HV.Slot.adresa);
HV.changed := true;
if ((dir) and (HV.Stav.souprava > -1)) then
if ((Sender <> Soupravy[HV.Stav.souprava]) and (Soupravy[HV.Stav.souprava] <> nil)) then
Soupravy[HV.Stav.souprava].LokDirChanged();
// Soupravy[HV.Stav.souprava] <> nil muze nastat pri aktualizaci HV na souprave,
// coz se dede prave tady
end;
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.CheckToggleQueue();
begin
if (Self.toggleQueue.Count = 0) then Exit();
if (Now >= Self.toggleQueue.Peek.time) then
Self.ProcessHVFunc(Self.toggleQueue.Dequeue());
end;
procedure TTrkGUI.FlushToggleQueue();
begin
while (Self.toggleQueue.Count > 0) do
Self.ProcessHVFunc(Self.toggleQueue.Dequeue());
end;
procedure TTrkGUI.ProcessHVFunc(hvFunc:THVFunc);
var funkce:TFunkce;
begin
if (hvFunc.HV = nil) then Exit();
funkce := hvFunc.HV.Slot.funkce;
funkce[hvFunc.fIndex] := false;
Self.LokSetFunc(Self, hvFunc.HV, funkce);
end;
////////////////////////////////////////////////////////////////////////////////
///
class function TTrkGUI.HVFunc(HV:THV; fIndex:Cardinal; time:TDateTime):THVFunc;
begin
Result.HV := HV;
Result.fIndex := fIndex;
Result.time := time;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TTrkGUI.Update();
begin
Self.CheckToggleQueue();
end;
////////////////////////////////////////////////////////////////////////////////
end.//unit
|
unit xdarray;
interface
uses SysUtils, Windows, Dialogs, Math;
procedure DynArrayDelete(var A; elSize: Longint; index, Count: Integer);
procedure DynArrayInsert(var A; elSize: Longint; index, Count: Integer);
procedure DynArrayCopy(var ADst; const ASrc; elSize: Longint; IndexDst, IndexSrc, Count: Integer);
procedure DynArrayAppend(var ADst; const ASrc; elSize: Longint; IndexSrc, Count: Integer);
implementation
procedure DynArraySetZero(var A);
var
P: PLongint;
begin
P := PLongint(A);
Dec(P);
P^ := 0;
Dec(P);
P^ := 0;
end;
procedure DynArrayDelete(var A; elSize: Longint; index, Count: Integer);
var
len, MaxDelete: Integer;
P: PLongint;
begin
P := PLongint(A);
if P = nil then Exit;
len := PLongint(PChar(P) - 4)^;
if index >= len then Exit;
MaxDelete := len - index;
Count := Min(Count, MaxDelete);
if Count = 0 then Exit; // nothing to delete
Dec(len, Count);
MoveMemory(PChar(P) + index * elSize, PChar(P) + (index + Count) * elSize, (len - index) * elSize);
Dec(P);
Dec(P);
ReallocMem(P, len * elSize + Sizeof(Longint) * 2);
Inc(P);
P^ := len; // new length
Inc(P);
PLongint(A) := P;
end;
procedure DynArrayInsert(var A; elSize: Longint; index, Count: Integer);
const
PNull: Pointer = nil;
var
len, I: Integer;
P: PLongint;
begin
P := PLongint(A);
if P <> nil then
begin
len := PLongint(PChar(P) - 4)^;
if (index > len) or (Count = 0) then Exit; // nothing to insert
Dec(P);
Dec(P);
end else len := 0;
ReallocMem(P, (len + Count) * elSize + Sizeof(Longint) * 2); // 先 realloc
Inc(P);
P^ := len + Count;
Inc(P);
MoveMemory(PChar(P) + (index + Count) * elSize, PChar(P) + index * elSize, (len - index) * elSize); // 往後挪
for I := index to index + Count - 1 do
System.Move(PNull, PChar(Integer(P) + I * elSize)^, elSize);
PLongint(A) := P;
end;
procedure DynArrayCopy(var ADst; const ASrc; elSize: Longint; IndexDst, IndexSrc, Count: Integer);
var
PDst, PSrc: PLongint;
LenDst, LenSrc: Integer;
begin
PDst := PLongint(ADst);
PSrc := PLongint(ASrc);
if (PSrc = nil) then Exit;
if PDst <> nil then
LenDst := PLongint(PChar(PDst) - 4)^
else LenDst := 0;
LenSrc := PLongint(PChar(PSrc) - 4)^;
Count := Min(LenSrc - IndexSrc, Count); // src array 不足時, 減少 count
if IndexDst + Count - 1 > LenDst then // dst array 空間不足
begin
DynArrayInsert(ADst, elSize, IndexDst, (IndexDst + Count) - LenDst); // 補足, 內容不管, 待會就蓋掉了
PDst := PLongint(ADst);
end;
MoveMemory(PChar(PDst) + IndexDst * elSize, PChar(PSrc) + IndexSrc * elSize, Count * elSize); // 複製
end;
procedure DynArrayAppend(var ADst; const ASrc; elSize: Longint; IndexSrc, Count: Integer);
var
P: PLongint;
begin
P := PLongint(ADst);
if (P = nil) then Exit;
DynArrayCopy(ADst, ASrc, elSize, PLongint(PChar(P) - 4)^, IndexSrc, Count);
end;
end.
|
unit MainFrm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys,
FireDAC.Phys.MongoDB, FireDAC.Phys.MongoDBDef, System.Rtti, System.JSON.Types,
System.JSON.Readers, System.JSON.BSON, System.JSON.Builders,
FireDAC.Phys.MongoDBWrapper, FireDAC.VCLUI.Wait, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, FireDAC.Phys.MongoDBDataSet;
type
TfrmMain = class(TForm)
btnConnect: TButton;
btnAdd: TButton;
btnRead: TButton;
btnUpdate: TButton;
btnDelete: TButton;
memLog: TMemo;
FDMongoQuery: TFDMongoQuery;
FDConnection: TFDConnection;
procedure btnAddClick(Sender: TObject);
procedure btnConnectClick(Sender: TObject);
procedure btnUpdateClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnReadClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FConnected: Boolean;
procedure LogMessage(const AMessage: string);
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
const
DB_NAME = 'delphidemo';
COLLECTION_NAME = 'anagrafica';
procedure TfrmMain.btnAddClick(Sender: TObject);
var
i: Integer;
MongConn: TMongoConnection;
MongoDoc: TMongoDocument;
MongoEnv: TMongoEnv;
begin
MongConn := TMongoConnection(FDConnection.CliObj);
MongoEnv := MongConn.Env;
MongConn[DB_NAME][COLLECTION_NAME].RemoveAll;
for i := 1 to 10 do
begin
MongoDoc := MongoEnv.NewDoc;
try
MongoDoc
.Add('name', 'Name ' + IntToStr(i) + ' - Record ' + IntToStr(i));
MongConn[DB_NAME][COLLECTION_NAME].Insert(MongoDoc);
finally
MongoDoc.Free;
end;
end;
LogMessage('Added 10 documents');
end;
procedure TfrmMain.btnConnectClick(Sender: TObject);
begin
if FConnected = False then
begin
FDMongoQuery.DatabaseName := DB_NAME;
FDMongoQuery.CollectionName := COLLECTION_NAME;
FDMongoQuery.Open;
btnConnect.Caption := 'Disconnect';
FConnected := True;
end
else
begin
FDMongoQuery.Close;
FDMongoQuery.FieldDefs.Clear;
btnConnect.Caption := 'Connect';
FConnected := False;
end;
end;
procedure TfrmMain.btnDeleteClick(Sender: TObject);
begin
FDMongoQuery.First;
while not FDMongoQuery.Eof do
FDMongoQuery.Delete;
LogMessage('All documents was deleted');
end;
procedure TfrmMain.btnReadClick(Sender: TObject);
begin
FDMongoQuery.Close;
FDMongoQuery.Open;
FDMongoQuery.First;
while not FDMongoQuery.Eof do
begin
LogMessage('Record: ' + FDMongoQuery.FieldByName('name').AsString);
FDMongoQuery.Next;
end;
if FDMongoQuery.IsEmpty then
LogMessage('No records found');
end;
procedure TfrmMain.btnUpdateClick(Sender: TObject);
var
i: Integer;
begin
FDMongoQuery.Close;
FDMongoQuery.Open;
FDMongoQuery.First;
i := 1;
while not FDMongoQuery.Eof do
begin
FDMongoQuery.Edit;
FDMongoQuery.FieldByName('name').AsString := 'Updated ' + IntToStr(i);
FDMongoQuery.Post;
Inc(i);
FDMongoQuery.Next;
end;
LogMessage('All documents updated');
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
FDMongoQuery.Close;
end;
procedure TfrmMain.LogMessage(const AMessage: string);
begin
memLog.Lines.Append(AMessage);
end;
end.
|
unit UGSEUADPref;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2013 by Bradford Technologies, Inc. }
{ This is the unit for setting the preferences for UAD Compliance }
{$WARN SYMBOL_PLATFORM OFF}
{$WARN UNIT_PLATFORM OFF}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, UStatus, UForms, UContainer, ExtCtrls;
const
cUADFirstLook = 1;
cUADPowerUser = 2;
cUADSpecialist = 3;
type
TGSEUADPref = class(TVistaAdvancedForm)
Panel1: TPanel;
Panel2: TPanel;
GroupBox1: TGroupBox;
rdoUADFirstLook: TRadioButton;
rdoUADPowerUser: TRadioButton;
rdoUADSpecialist: TRadioButton;
stxUADActive: TStaticText;
stxUADAskToEnable: TStaticText;
stxAutoAddUADDefs: TStaticText;
chkAutoAddUADDefs: TCheckBox;
chkUADAskToEnable: TCheckBox;
chkUADActive: TCheckBox;
stNoUADForms: TStaticText;
chkDesignAndCarActive: TCheckBox;
btnOK: TButton;
btnCancel: TButton;
rdoUADoption: TRadioGroup;
chkAutoAddUADSubjDet: TCheckBox;
procedure SelectUADInterfaceClick(Sender: TObject);
procedure chkUADActiveClick(Sender: TObject);
procedure chkUADAskToEnableClick(Sender: TObject);
procedure chkAutoAddUADDefsClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure ChkUserState(FirstLookChkd, PwrUserChkd: Boolean);
procedure chkAutoAddUADSubjDetClick(Sender: TObject);
procedure chkDesignAndCarActiveClick(Sender: TObject);
procedure rdoUADoptionClick(Sender: TObject);
private
FDoc: TContainer;
FUADIsOn: Boolean;
FUADAsk: Boolean;
FUADAppendDefs: Boolean;
FUADAppendSubjDet: Boolean;
FUADAutoDlgs: Boolean;
FUADInterface: Integer;
FUADDesignOn: Boolean;
FUADAutoConvert: Boolean; //github 237
procedure AdjustDPISettings;
public
constructor Create(AOwner: TComponent); override;
end;
var
GSEUADPref: TGSEUADPref;
procedure SetUADCompliancePrefs(Doc: TContainer);
implementation
uses
UMain, UGlobals, UStrings, ULicUser, UUADUtils;
{$R *.dfm}
procedure SetUADCompliancePrefs(Doc: TContainer);
var
UADPref: TGSEUADPref;
begin
UADPref := TGSEUADPref.Create(doc);
try
if (not Assigned(Doc)) or (Doc.FormCount = 0) or HasUADForm(doc) then
begin
UADPref.stNoUADForms.Visible := False;
end
else
begin
UADPref.GroupBox1.Enabled := False;
UADPref.rdoUADFirstLook.Enabled := False;
UADPref.rdoUADPowerUser.Enabled := False;
UADPref.rdoUADSpecialist.Enabled := False;
UADPref.chkUADActive.Enabled := False;
UADPref.chkUADAskToEnable.Enabled := False;
UADPref.chkAutoAddUADDefs.Enabled := False;
UADPref.chkDesignAndCarActive.Enabled := False;
UADPref.btnOK.Enabled := False;
end;
UADPref.ShowModal;
finally
UADPref.Free;
end;
end;
{ TGSEUADPref }
constructor TGSEUADPref.Create(AOwner: TComponent);
begin
inherited Create(nil);
FDoc := AOwner as TContainer;
//remember original settings
FUADIsOn := appPref_UADIsActive;
FUADAsk := appPref_UADAskBeforeEnable;
FUADAppendDefs := appPref_UADAppendGlossary;
FUADAppendSubjDet := appPref_UADAppendSubjDet;
FUADAutoDlgs := appPref_AutoDisplayUADDlgs;
FUADInterface := appPref_UADInterface;
FUADDesignOn := appPref_UADCarNDesignActive;
FUADAutoConvert := appPref_UADAutoConvert;
//set the check boxes - show the user
chkUADActive.Checked := appPref_UADIsActive;
chkAutoAddUADDefs.Checked := appPref_UADAppendGlossary;
chkAutoAddUADSubjDet.Checked := appPref_UADAppendSubjDet;
chkUADAskToEnable.Checked := appPref_UADAskBeforeEnable;
chkDesignAndCarActive.Checked := appPref_UADCarNDesignActive or (date >= StrToDate(CUADCarAndDesignEffDate));
if appPref_UADNoConvert then
rdoUADOption.ItemIndex := 0
else if appPref_AutoDisplayUADDlgs then
rdoUADOption.ItemIndex := 1
else if appPref_UADAutoConvert then
rdoUADOption.ItemIndex := 2;
if (date >= StrToDate(CUADCarAndDesignEffDate)) then //don't let user change after this date
chkDesignAndCarActive.enabled := False;
//set the UAD interface
(*
case appPref_UADInterface of
cUADFirstLook: rdoUADFirstLook.Checked := True;
cUADPowerUser: rdoUADPowerUser.Checked := True;
cUADSpecialist: rdoUADSpecialist.Checked := True;
else
rdoUADFirstLook.Checked := True;
end;
ChkUserState(rdoUADFirstLook.Checked, rdoUADPowerUser.Checked);
*)
end;
//st the beginning - check if user is in licensed for UAD Compliance Service
procedure TGSEUADPref.SelectUADInterfaceClick(Sender: TObject);
begin
// if not (TRadioButton(Sender).Tag = cUADSpecialist) then //REMOVE IF when UAD Specialis is Active
// FUADInterface := TRadioButton(Sender).Tag; //TAG is interface indicator
FUADInterface := 3; //github #445: always set as special List
{if TRadioButton(Sender).Tag = cUADSpecialist then //Specialist coming soon
begin
ShowNotice('The UAD Specialist interface will be released soon. Please use UAD First Look to become familiar with the UAD Requirements. Then use UAD Power User to increase your productivity.');
//reset last checked interface option
case FUADInterface of
cUADFirstLook: rdoUADFirstLook.Checked := True;
cUADPowerUser: rdoUADPowerUser.Checked := True;
end;
end;}
// ChkUserState(rdoUADFirstLook.Checked, rdoUADPowerUser.Checked);
end;
procedure TGSEUADPref.chkUADActiveClick(Sender: TObject);
begin
FUADIsOn := chkUADActive.Checked;
//enable or disable depending if UAD is ON or OFF
chkUADAskToEnable.Enabled := FUADIsOn;
chkAutoAddUADDefs.Enabled := FUADIsOn;
chkDesignAndCarActive.Enabled := FUADIsOn and (date < StrToDate(CUADCarAndDesignEffDate));
chkAutoAddUADSubjDet.Enabled := FUADIsOn; //github 344
rdoUADOption.ItemIndex := 1; //github 344
rdoUADOption.Enabled := FUADIsOn; //github 344
end;
procedure TGSEUADPref.chkUADAskToEnableClick(Sender: TObject);
begin
FUADAsk := chkUADAskToEnable.Checked;
end;
procedure TGSEUADPref.chkAutoAddUADDefsClick(Sender: TObject);
begin
FUADAppendDefs := chkAutoAddUADDefs.Checked;
end;
//save the UAD Settings
procedure TGSEUADPref.FormClose(Sender: TObject; var Action: TCloseAction);
//var
// addedPowerUser: Boolean;
begin
if ModalResult <> mrCancel then
begin
appPref_UADIsActive := FUADIsOn;
appPref_UADAskBeforeEnable := FUADAsk;
appPref_UADAppendGlossary := FUADAppendDefs;
appPref_UADAppendSubjDet := FUADAppendSubjDet;
appPref_AutoDisplayUADDlgs := FUADAutoDlgs;
appPref_UADInterface := FUADInterface;
appPref_UADCarNDesignActive := FUADDesignOn;
appPref_UADAutoConvert := FUADAutoConvert;
//do we need to apply this to current Containers? (what about others - ie later)
if assigned(FDoc) then
begin
if FUADIsOn and not FDoc.UADEnabled then //UAD On, doc is off - turn doc on
FDoc.UADEnabled := IsOKToEnableUAD
else if Not FUADIsOn and FDoc.UADEnabled then //UAD off, doc is on, ask to trun doc off
begin
if (mrYes = WhichOption12('Continue', 'Cancel', 'The UAD Compliance Rules for this report will be terminated. Continue?')) then
FDoc.UADEnabled := False
else //canceled - do nothing
begin
action := caNone; //don't close the dialog.
exit;
end;
end;
//are power user forms in the report?
if FUADIsOn and (FUADInterface = cUADPowerUser) then
begin
// addedPowerUser := False;
if FDoc.GetFormIndex(981) = -1 then //if Subject details not in the report
begin
FDoc.GetFormByOccurance(981, 0, True); //add it
// addedPowerUser := True;
end;
(*
if FDoc.GetFormIndex(982) = -1 then //if Comp details not in the report
begin
FDoc.GetFormByOccurance(982, 0, True); //add it
end;
*)
// if addedPowerUser then
// ShowNotice('The UAD Power User addednums have been added to the end of the report.');
end;
end;
//now set the menu item display
SetUADServiceMenu(FUADIsOn);
end;
end;
procedure TGSEUADPref.FormShow(Sender: TObject);
begin
AdjustDPISettings;
end;
procedure TGSEUADPref.AdjustDPISettings;
begin
// stNoUADForms.top := Panel1.Height - 30;
// stxAutoAddUADSubjDet.Top := stNoUADForms.Top - stxAutoAddUADSubjDet.height - 10;
// chkAutoAddUADSubjDet.Top := stxAutoAddUADSubjDet.Top;
self.width := stNoUADForms.left + stNoUADForms.width + 100;
Panel1.Width := self.Width;
Panel1.Align := alClient;
end;
procedure TGSEUADPref.ChkUserState(FirstLookChkd, PwrUserChkd: Boolean);
begin
if FirstLookChkd and chkUADActive.Checked then //github 344
begin
// chkAutoUADDlgs.Checked := True;
rdoUADOption.ItemIndex := 1;
rdoUADOption.Enabled := False;
// chkAutoUADDlgs.Enabled := False;
// stxAutoUADDlgs.Enabled := False;
chkAutoAddUADSubjDet.Checked := False;
chkAutoAddUADSubjDet.Enabled := True; //github 344
//github 821 make UAD Def unchecked for default
chkAutoAddUADDefs.Checked := False;
chkAutoAddUADDefs.Enabled := True;
// stxAutoAddUADSubjDet.Enabled := False;
//github 237: only the specialist can use the auto convert
// chkUADAutoConvert.Enabled := False;
// chkUADAutoConvert.Checked := False;
// stxAutoUADConvert.Enabled := False;
appPref_UADAutoConvert := False; //turn off auto convert
end
else if PwrUserChkd then
begin
rdoUADOption.ItemIndex := 1;
rdoUADOption.Enabled := False;
chkAutoAddUADSubjDet.Checked := True;
chkAutoAddUADSubjDet.Enabled := True; //github 344
//github 821 make UAD Def unchecked for default
chkAutoAddUADDefs.Checked := True;
chkAutoAddUADDefs.Enabled := True;
appPref_UADAutoConvert := False; //github 237: turn off auto convert
end
else
begin
if appPref_UADNoConvert then
rdoUADOption.ItemIndex := 0
else if FUADAutoDlgs and not appPref_UADAutoConvert then
begin
rdoUADOption.ItemIndex := 1;
rdoUADOption.Enabled := True;
chkAutoAddUADSubjDet.Checked := False;
chkAutoAddUADSubjDet.Enabled := True; //github 344
//github 821 make UAD Def unchecked for default
chkAutoAddUADDefs.Checked := False;
chkAutoAddUADDefs.Enabled := True;
end;
if not chkUADActive.Checked then //github 344
begin
rdoUADOption.ItemIndex := 1;
rdoUADOption.Enabled := False;
chkAutoAddUADSubjDet.Checked := False;
chkAutoAddUADSubjDet.Enabled := False;
//github 821 make UAD Def unchecked for default
chkAutoAddUADDefs.Checked := False;
chkAutoAddUADDefs.Enabled := False;
end;
end;
end;
procedure TGSEUADPref.chkAutoAddUADSubjDetClick(Sender: TObject);
begin
FUADAppendSubjDet := chkAutoAddUADSubjDet.Checked;
end;
procedure TGSEUADPref.chkDesignAndCarActiveClick(Sender: TObject);
begin
FUADDesignOn := chkDesignAndCarActive.checked;
end;
//github 237
procedure TGSEUADPref.rdoUADoptionClick(Sender: TObject);
begin
case rdoUADOption.ItemIndex of
0: begin //github #443
FUADAutoDlgs := False;
FUADAutoConvert := False;
appPref_UADNoConvert := True;
appPref_AutoDisplayUADDlgs := False;
appPref_UADAutoConvert := False;
chkDesignAndCarActive.Checked := False; //github 454
end;
1: begin
FUADAutoDlgs := True;
FUADAutoConvert := False;
appPref_AutoDisplayUADDlgs := True;
appPref_UADAutoConvert := False;
appPref_UADNoConvert := False;
chkDesignAndCarActive.Checked := appPref_UADCarNDesignActive or (date >= StrToDate(CUADCarAndDesignEffDate));
end;
2: begin
FUADAutoConvert := True;
FUADAutoDlgs := False;
appPref_UADAutoConvert := True;
appPref_AutoDisplayUADDlgs := False;
appPref_UADNoConvert := False;
chkDesignAndCarActive.Checked := False;
end;
end;
FUADDesignOn := chkDesignAndCarActive.Checked;
end;
end.
|
unit FMX.Android.Permissions;
interface
uses
System.SysUtils, System.Classes, System.Types, System.UITypes, System.DateUtils, System.Generics.Collections,
FMX.Utils, FMX.Types, FMX.Controls, FMX.Objects, FMX.StdCtrls, FMX.Graphics, FMX.MultiResBitmap, FMX.Dialogs,
FMX.Ani, FMX.Effects, System.Actions, FMX.ActnList, FMX.Layouts, FMX.Filter.Effects, FMX.DialogService,
{$IF DEFINED(VER330) OR DEFINED(VER340)}
System.Permissions,
{$IFDEF ANDROID}
FMX.Platform.Android,
FMX.Helpers.Android,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.Net,
Androidapi.JNI.Os,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNIBridge,
Androidapi.Helpers,
{$ENDIF} {$ENDIF}
TypInfo;
Type
TAndroidPermissionsNames = Class(TPersistent)
Private
fSEND_SMS: Boolean;
fCAPTURE_AUDIO_OUTPUT: Boolean;
fWRITE_VOICEMAIL: Boolean;
fWRITE_SECURE_SETTINGS: Boolean;
fSET_TIME_ZONE: Boolean;
fREAD_SYNC_SETTINGS: Boolean;
fMODIFY_AUDIO_SETTINGS: Boolean;
fKILL_BACKGROUND_PROCESSES: Boolean;
fGET_TASKS: Boolean;
fDELETE_CACHE_FILES: Boolean;
fCAPTURE_VIDEO_OUTPUT: Boolean;
fBIND_NOTIFICATION_LISTENER_SERVICE: Boolean;
fUPDATE_DEVICE_STATS: Boolean;
fREAD_CONTACTS: Boolean;
fBIND_TELECOM_CONNECTION_SERVICE: Boolean;
fBIND_PRINT_SERVICE: Boolean;
fRECORD_AUDIO: Boolean;
fREAD_FRAME_BUFFER: Boolean;
fMOUNT_UNMOUNT_FILESYSTEMS: Boolean;
fPACKAGE_USAGE_STATS: Boolean;
fGET_PACKAGE_SIZE: Boolean;
fBROADCAST_STICKY: Boolean;
fWRITE_SYNC_SETTINGS: Boolean;
fREAD_SMS: Boolean;
fREAD_CALENDAR: Boolean;
fCONTROL_LOCATION_UPDATES: Boolean;
fBIND_REMOTEVIEWS: Boolean;
fADD_VOICEMAIL: Boolean;
fWRITE_CONTACTS: Boolean;
fREAD_INPUT_STATE: Boolean;
fCHANGE_NETWORK_STATE: Boolean;
fCAPTURE_SECURE_VIDEO_OUTPUT: Boolean;
fCAMERA: Boolean;
fBIND_NFC_SERVICE: Boolean;
fWRITE_GSERVICES: Boolean;
fSET_WALLPAPER: Boolean;
fREQUEST_DELETE_PACKAGES: Boolean;
fBIND_VPN_SERVICE: Boolean;
fBIND_CHOOSER_TARGET_SERVICE: Boolean;
fINSTALL_PACKAGES: Boolean;
fCLEAR_APP_CACHE: Boolean;
fBIND_VR_LISTENER_SERVICE: Boolean;
fACCESS_NOTIFICATION_POLICY: Boolean;
fWRITE_CALENDAR: Boolean;
fSET_TIME: Boolean;
fDUMP: Boolean;
fBROADCAST_SMS: Boolean;
fBIND_TEXT_SERVICE: Boolean;
fBIND_MIDI_DEVICE_SERVICE: Boolean;
fBIND_ACCESSIBILITY_SERVICE: Boolean;
fBATTERY_STATS: Boolean;
fUSE_SIP: Boolean;
fUSE_FINGERPRINT: Boolean;
fUSE_BIOMETRIC: Boolean;
fTRANSMIT_IR: Boolean;
fSEND_RESPOND_VIA_MESSAGE: Boolean;
fREAD_EXTERNAL_STORAGE: Boolean;
fDIAGNOSTIC: Boolean;
fBIND_APPWIDGET: Boolean;
fPERSISTENT_ACTIVITY: Boolean;
fBIND_CONDITION_PROVIDER_SERVICE: Boolean;
fSET_ANIMATION_SCALE: Boolean;
fSET_ALARM: Boolean;
fREAD_SYNC_STATS: Boolean;
fCHANGE_WIFI_STATE: Boolean;
fSTATUS_BAR: Boolean;
fMOUNT_FORMAT_FILESYSTEMS: Boolean;
fMANAGE_DOCUMENTS: Boolean;
fWRITE_EXTERNAL_STORAGE: Boolean;
fLOCATION_HARDWARE: Boolean;
fGLOBAL_SEARCH: Boolean;
fACCESS_NETWORK_STATE: Boolean;
fVIBRATE: Boolean;
fRECEIVE_SMS: Boolean;
fRECEIVE_BOOT_COMPLETED: Boolean;
fCHANGE_WIFI_MULTICAST_STATE: Boolean;
fBIND_CARRIER_SERVICES: Boolean;
fSET_PROCESS_LIMIT: Boolean;
fREBOOT: Boolean;
fCHANGE_CONFIGURATION: Boolean;
fBLUETOOTH_ADMIN: Boolean;
fBIND_DEVICE_ADMIN: Boolean;
fBIND_AUTOFILL_SERVICE: Boolean;
fANSWER_PHONE_CALLS: Boolean;
fBODY_SENSORS: Boolean;
fBIND_TV_INPUT: Boolean;
fBIND_QUICK_SETTINGS_TILE: Boolean;
fBIND_INCALL_SERVICE: Boolean;
fSET_DEBUG_APP: Boolean;
fRESTART_PACKAGES: Boolean;
fREQUEST_IGNORE_BATTERY_OPTIMIZATIONS: Boolean;
fBIND_DREAM_SERVICE: Boolean;
fEXPAND_STATUS_BAR: Boolean;
fDELETE_PACKAGES: Boolean;
fACCESS_COARSE_LOCATION: Boolean;
fSET_ALWAYS_FINISH: Boolean;
fREAD_CALL_LOG: Boolean;
fINTERNET: Boolean;
fINSTANT_APP_FOREGROUND_SERVICE: Boolean;
fBIND_VISUAL_VOICEMAIL_SERVICE: Boolean;
fACCESS_WIFI_STATE: Boolean;
fPROCESS_OUTGOING_CALLS: Boolean;
fNFC: Boolean;
fMANAGE_OWN_CALLS: Boolean;
fINSTALL_SHORTCUT: Boolean;
fWRITE_APN_SETTINGS: Boolean;
fUNINSTALL_SHORTCUT: Boolean;
fSET_WALLPAPER_HINTS: Boolean;
fMODIFY_PHONE_STATE: Boolean;
fDISABLE_KEYGUARD: Boolean;
fBROADCAST_WAP_PUSH: Boolean;
fBIND_VOICE_INTERACTION: Boolean;
fBIND_CARRIER_MESSAGING_SERVICE: Boolean;
fCHANGE_COMPONENT_ENABLED_STATE: Boolean;
fBLUETOOTH_PRIVILEGED: Boolean;
fBIND_SCREENING_SERVICE: Boolean;
fWRITE_CALL_LOG: Boolean;
fWAKE_LOCK: Boolean;
fCALL_PRIVILEGED: Boolean;
fSYSTEM_ALERT_WINDOW: Boolean;
fREQUEST_COMPANION_USE_DATA_IN_BACKGROUND: Boolean;
fMASTER_CLEAR: Boolean;
fINSTALL_LOCATION_PROVIDER: Boolean;
fSIGNAL_PERSISTENT_PROCESSES: Boolean;
fMEDIA_CONTENT_CONTROL: Boolean;
fFACTORY_TEST: Boolean;
fBLUETOOTH: Boolean;
fACCESS_CHECKIN_PROPERTIES: Boolean;
fREQUEST_COMPANION_RUN_IN_BACKGROUND: Boolean;
fGET_ACCOUNTS_PRIVILEGED: Boolean;
fBROADCAST_PACKAGE_REMOVED: Boolean;
fACCESS_LOCATION_EXTRA_COMMANDS: Boolean;
fWRITE_SETTINGS: Boolean;
fREQUEST_INSTALL_PACKAGES: Boolean;
fREORDER_TASKS: Boolean;
fRECEIVE_WAP_PUSH: Boolean;
fREAD_PHONE_STATE: Boolean;
fREAD_LOGS: Boolean;
fBIND_INPUT_METHOD: Boolean;
fSET_PREFERRED_APPLICATIONS: Boolean;
fRECEIVE_MMS: Boolean;
fREAD_VOICEMAIL: Boolean;
fREAD_PHONE_NUMBERS: Boolean;
fBIND_WALLPAPER: Boolean;
fACCOUNT_MANAGER: Boolean;
fGET_ACCOUNTS: Boolean;
fCALL_PHONE: Boolean;
fACCESS_FINE_LOCATION: Boolean;
Published
Property ACCESS_CHECKIN_PROPERTIES : Boolean Read fACCESS_CHECKIN_PROPERTIES Write fACCESS_CHECKIN_PROPERTIES;
Property ACCESS_COARSE_LOCATION : Boolean Read fACCESS_COARSE_LOCATION Write fACCESS_COARSE_LOCATION;
Property ACCESS_FINE_LOCATION : Boolean Read fACCESS_FINE_LOCATION Write fACCESS_FINE_LOCATION;
Property ACCESS_LOCATION_EXTRA_COMMANDS : Boolean Read fACCESS_LOCATION_EXTRA_COMMANDS Write fACCESS_LOCATION_EXTRA_COMMANDS;
Property ACCESS_NETWORK_STATE : Boolean Read fACCESS_NETWORK_STATE Write fACCESS_NETWORK_STATE;
Property ACCESS_NOTIFICATION_POLICY : Boolean Read fACCESS_NOTIFICATION_POLICY Write fACCESS_NOTIFICATION_POLICY;
Property ACCESS_WIFI_STATE : Boolean Read fACCESS_WIFI_STATE Write fACCESS_WIFI_STATE;
Property ACCOUNT_MANAGER : Boolean Read fACCOUNT_MANAGER Write fACCOUNT_MANAGER;
Property ADD_VOICEMAIL : Boolean Read fADD_VOICEMAIL Write fADD_VOICEMAIL;
Property ANSWER_PHONE_CALLS : Boolean Read fANSWER_PHONE_CALLS Write fANSWER_PHONE_CALLS;
Property BATTERY_STATS : Boolean Read fBATTERY_STATS Write fBATTERY_STATS;
Property BIND_ACCESSIBILITY_SERVICE : Boolean Read fBIND_ACCESSIBILITY_SERVICE Write fBIND_ACCESSIBILITY_SERVICE;
Property BIND_APPWIDGET : Boolean Read fBIND_APPWIDGET Write fBIND_APPWIDGET;
Property BIND_AUTOFILL_SERVICE : Boolean Read fBIND_AUTOFILL_SERVICE Write fBIND_AUTOFILL_SERVICE;
Property BIND_CARRIER_MESSAGING_SERVICE : Boolean Read fBIND_CARRIER_MESSAGING_SERVICE Write fBIND_CARRIER_MESSAGING_SERVICE;
Property BIND_CARRIER_SERVICES : Boolean Read fBIND_CARRIER_SERVICES Write fBIND_CARRIER_SERVICES;
Property BIND_CHOOSER_TARGET_SERVICE : Boolean Read fBIND_CHOOSER_TARGET_SERVICE Write fBIND_CHOOSER_TARGET_SERVICE;
Property BIND_CONDITION_PROVIDER_SERVICE : Boolean Read fBIND_CONDITION_PROVIDER_SERVICE Write fBIND_CONDITION_PROVIDER_SERVICE;
Property BIND_DEVICE_ADMIN : Boolean Read fBIND_DEVICE_ADMIN Write fBIND_DEVICE_ADMIN;
Property BIND_DREAM_SERVICE : Boolean Read fBIND_DREAM_SERVICE Write fBIND_DREAM_SERVICE;
Property BIND_INCALL_SERVICE : Boolean Read fBIND_INCALL_SERVICE Write fBIND_INCALL_SERVICE;
Property BIND_INPUT_METHOD : Boolean Read fBIND_INPUT_METHOD Write fBIND_INPUT_METHOD;
Property BIND_MIDI_DEVICE_SERVICE : Boolean Read fBIND_MIDI_DEVICE_SERVICE Write fBIND_MIDI_DEVICE_SERVICE;
Property BIND_NFC_SERVICE : Boolean Read fBIND_NFC_SERVICE Write fBIND_NFC_SERVICE;
Property BIND_NOTIFICATION_LISTENER_SERVICE : Boolean Read fBIND_NOTIFICATION_LISTENER_SERVICE Write fBIND_NOTIFICATION_LISTENER_SERVICE;
Property BIND_PRINT_SERVICE : Boolean Read fBIND_PRINT_SERVICE Write fBIND_PRINT_SERVICE;
Property BIND_QUICK_SETTINGS_TILE : Boolean Read fBIND_QUICK_SETTINGS_TILE Write fBIND_QUICK_SETTINGS_TILE;
Property BIND_REMOTEVIEWS : Boolean Read fBIND_REMOTEVIEWS Write fBIND_REMOTEVIEWS;
Property BIND_SCREENING_SERVICE : Boolean Read fBIND_SCREENING_SERVICE Write fBIND_SCREENING_SERVICE;
Property BIND_TELECOM_CONNECTION_SERVICE : Boolean Read fBIND_TELECOM_CONNECTION_SERVICE Write fBIND_TELECOM_CONNECTION_SERVICE;
Property BIND_TEXT_SERVICE : Boolean Read fBIND_TEXT_SERVICE Write fBIND_TEXT_SERVICE;
Property BIND_TV_INPUT : Boolean Read fBIND_TV_INPUT Write fBIND_TV_INPUT;
Property BIND_VISUAL_VOICEMAIL_SERVICE : Boolean Read fBIND_VISUAL_VOICEMAIL_SERVICE Write fBIND_VISUAL_VOICEMAIL_SERVICE;
Property BIND_VOICE_INTERACTION : Boolean Read fBIND_VOICE_INTERACTION Write fBIND_VOICE_INTERACTION;
Property BIND_VPN_SERVICE : Boolean Read fBIND_VPN_SERVICE Write fBIND_VPN_SERVICE;
Property BIND_VR_LISTENER_SERVICE : Boolean Read fBIND_VR_LISTENER_SERVICE Write fBIND_VR_LISTENER_SERVICE;
Property BIND_WALLPAPER : Boolean Read fBIND_WALLPAPER Write fBIND_WALLPAPER;
Property BLUETOOTH : Boolean Read fBLUETOOTH Write fBLUETOOTH;
Property BLUETOOTH_ADMIN : Boolean Read fBLUETOOTH_ADMIN Write fBLUETOOTH_ADMIN;
Property BLUETOOTH_PRIVILEGED : Boolean Read fBLUETOOTH_PRIVILEGED Write fBLUETOOTH_PRIVILEGED;
Property BODY_SENSORS : Boolean Read fBODY_SENSORS Write fBODY_SENSORS;
Property BROADCAST_PACKAGE_REMOVED : Boolean Read fBROADCAST_PACKAGE_REMOVED Write fBROADCAST_PACKAGE_REMOVED;
Property BROADCAST_SMS : Boolean Read fBROADCAST_SMS Write fBROADCAST_SMS;
Property BROADCAST_STICKY : Boolean Read fBROADCAST_STICKY Write fBROADCAST_STICKY;
Property BROADCAST_WAP_PUSH : Boolean Read fBROADCAST_WAP_PUSH Write fBROADCAST_WAP_PUSH;
Property CALL_PHONE : Boolean Read fCALL_PHONE Write fCALL_PHONE;
Property CALL_PRIVILEGED : Boolean Read fCALL_PRIVILEGED Write fCALL_PRIVILEGED;
Property CAMERA : Boolean Read fCAMERA Write fCAMERA;
Property CAPTURE_AUDIO_OUTPUT : Boolean Read fCAPTURE_AUDIO_OUTPUT Write fCAPTURE_AUDIO_OUTPUT;
Property CAPTURE_SECURE_VIDEO_OUTPUT : Boolean Read fCAPTURE_SECURE_VIDEO_OUTPUT Write fCAPTURE_SECURE_VIDEO_OUTPUT;
Property CAPTURE_VIDEO_OUTPUT : Boolean Read fCAPTURE_VIDEO_OUTPUT Write fCAPTURE_VIDEO_OUTPUT;
Property CHANGE_COMPONENT_ENABLED_STATE : Boolean Read fCHANGE_COMPONENT_ENABLED_STATE Write fCHANGE_COMPONENT_ENABLED_STATE;
Property CHANGE_CONFIGURATION : Boolean Read fCHANGE_CONFIGURATION Write fCHANGE_CONFIGURATION;
Property CHANGE_NETWORK_STATE : Boolean Read fCHANGE_NETWORK_STATE Write fCHANGE_NETWORK_STATE;
Property CHANGE_WIFI_MULTICAST_STATE : Boolean Read fCHANGE_WIFI_MULTICAST_STATE Write fCHANGE_WIFI_MULTICAST_STATE;
Property CHANGE_WIFI_STATE : Boolean Read fCHANGE_WIFI_STATE Write fCHANGE_WIFI_STATE;
Property CLEAR_APP_CACHE : Boolean Read fCLEAR_APP_CACHE Write fCLEAR_APP_CACHE;
Property CONTROL_LOCATION_UPDATES : Boolean Read fCONTROL_LOCATION_UPDATES Write fCONTROL_LOCATION_UPDATES;
Property DELETE_CACHE_FILES : Boolean Read fDELETE_CACHE_FILES Write fDELETE_CACHE_FILES;
Property DELETE_PACKAGES : Boolean Read fDELETE_PACKAGES Write fDELETE_PACKAGES;
Property DIAGNOSTIC : Boolean Read fDIAGNOSTIC Write fDIAGNOSTIC;
Property DISABLE_KEYGUARD : Boolean Read fDISABLE_KEYGUARD Write fDISABLE_KEYGUARD;
Property DUMP : Boolean Read fDUMP Write fDUMP;
Property EXPAND_STATUS_BAR : Boolean Read fEXPAND_STATUS_BAR Write fEXPAND_STATUS_BAR;
Property FACTORY_TEST : Boolean Read fFACTORY_TEST Write fFACTORY_TEST;
Property GET_ACCOUNTS : Boolean Read fGET_ACCOUNTS Write fGET_ACCOUNTS;
Property GET_ACCOUNTS_PRIVILEGED : Boolean Read fGET_ACCOUNTS_PRIVILEGED Write fGET_ACCOUNTS_PRIVILEGED;
Property GET_PACKAGE_SIZE : Boolean Read fGET_PACKAGE_SIZE Write fGET_PACKAGE_SIZE;
Property GET_TASKS : Boolean Read fGET_TASKS Write fGET_TASKS;
Property GLOBAL_SEARCH : Boolean Read fGLOBAL_SEARCH Write fGLOBAL_SEARCH;
Property INSTALL_LOCATION_PROVIDER : Boolean Read fINSTALL_LOCATION_PROVIDER Write fINSTALL_LOCATION_PROVIDER;
Property INSTALL_PACKAGES : Boolean Read fINSTALL_PACKAGES Write fINSTALL_PACKAGES;
Property INSTALL_SHORTCUT : Boolean Read fINSTALL_SHORTCUT Write fINSTALL_SHORTCUT;
Property INSTANT_APP_FOREGROUND_SERVICE : Boolean Read fINSTANT_APP_FOREGROUND_SERVICE Write fINSTANT_APP_FOREGROUND_SERVICE;
Property INTERNET : Boolean Read fINTERNET Write fINTERNET;
Property KILL_BACKGROUND_PROCESSES : Boolean Read fKILL_BACKGROUND_PROCESSES Write fKILL_BACKGROUND_PROCESSES;
Property LOCATION_HARDWARE : Boolean Read fLOCATION_HARDWARE Write fLOCATION_HARDWARE;
Property MANAGE_DOCUMENTS : Boolean Read fMANAGE_DOCUMENTS Write fMANAGE_DOCUMENTS;
Property MANAGE_OWN_CALLS : Boolean Read fMANAGE_OWN_CALLS Write fMANAGE_OWN_CALLS;
Property MASTER_CLEAR : Boolean Read fMASTER_CLEAR Write fMASTER_CLEAR;
Property MEDIA_CONTENT_CONTROL : Boolean Read fMEDIA_CONTENT_CONTROL Write fMEDIA_CONTENT_CONTROL;
Property MODIFY_AUDIO_SETTINGS : Boolean Read fMODIFY_AUDIO_SETTINGS Write fMODIFY_AUDIO_SETTINGS;
Property MODIFY_PHONE_STATE : Boolean Read fMODIFY_PHONE_STATE Write fMODIFY_PHONE_STATE;
Property MOUNT_FORMAT_FILESYSTEMS : Boolean Read fMOUNT_FORMAT_FILESYSTEMS Write fMOUNT_FORMAT_FILESYSTEMS;
Property MOUNT_UNMOUNT_FILESYSTEMS : Boolean Read fMOUNT_UNMOUNT_FILESYSTEMS Write fMOUNT_UNMOUNT_FILESYSTEMS;
Property NFC : Boolean Read fNFC Write fNFC;
Property PACKAGE_USAGE_STATS : Boolean Read fPACKAGE_USAGE_STATS Write fPACKAGE_USAGE_STATS;
Property PERSISTENT_ACTIVITY : Boolean Read fPERSISTENT_ACTIVITY Write fPERSISTENT_ACTIVITY;
Property PROCESS_OUTGOING_CALLS : Boolean Read fPROCESS_OUTGOING_CALLS Write fPROCESS_OUTGOING_CALLS;
Property READ_CALENDAR : Boolean Read fREAD_CALENDAR Write fREAD_CALENDAR;
Property READ_CALL_LOG : Boolean Read fREAD_CALL_LOG Write fREAD_CALL_LOG;
Property READ_CONTACTS : Boolean Read fREAD_CONTACTS Write fREAD_CONTACTS;
Property READ_EXTERNAL_STORAGE : Boolean Read fREAD_EXTERNAL_STORAGE Write fREAD_EXTERNAL_STORAGE;
Property READ_FRAME_BUFFER : Boolean Read fREAD_FRAME_BUFFER Write fREAD_FRAME_BUFFER;
Property READ_INPUT_STATE : Boolean Read fREAD_INPUT_STATE Write fREAD_INPUT_STATE;
Property READ_LOGS : Boolean Read fREAD_LOGS Write fREAD_LOGS;
Property READ_PHONE_NUMBERS : Boolean Read fREAD_PHONE_NUMBERS Write fREAD_PHONE_NUMBERS;
Property READ_PHONE_STATE : Boolean Read fREAD_PHONE_STATE Write fREAD_PHONE_STATE;
Property READ_SMS : Boolean Read fREAD_SMS Write fREAD_SMS;
Property READ_SYNC_SETTINGS : Boolean Read fREAD_SYNC_SETTINGS Write fREAD_SYNC_SETTINGS;
Property READ_SYNC_STATS : Boolean Read fREAD_SYNC_STATS Write fREAD_SYNC_STATS;
Property READ_VOICEMAIL : Boolean Read fREAD_VOICEMAIL Write fREAD_VOICEMAIL;
Property REBOOT : Boolean Read fREBOOT Write fREBOOT;
Property RECEIVE_BOOT_COMPLETED : Boolean Read fRECEIVE_BOOT_COMPLETED Write fRECEIVE_BOOT_COMPLETED;
Property RECEIVE_MMS : Boolean Read fRECEIVE_MMS Write fRECEIVE_MMS;
Property RECEIVE_SMS : Boolean Read fRECEIVE_SMS Write fRECEIVE_SMS;
Property RECEIVE_WAP_PUSH : Boolean Read fRECEIVE_WAP_PUSH Write fRECEIVE_WAP_PUSH;
Property RECORD_AUDIO : Boolean Read fRECORD_AUDIO Write fRECORD_AUDIO;
Property REORDER_TASKS : Boolean Read fREORDER_TASKS Write fREORDER_TASKS;
Property REQUEST_COMPANION_RUN_IN_BACKGROUND : Boolean Read fREQUEST_COMPANION_RUN_IN_BACKGROUND Write fREQUEST_COMPANION_RUN_IN_BACKGROUND;
Property REQUEST_COMPANION_USE_DATA_IN_BACKGROUND : Boolean Read fREQUEST_COMPANION_USE_DATA_IN_BACKGROUND Write fREQUEST_COMPANION_USE_DATA_IN_BACKGROUND;
Property REQUEST_DELETE_PACKAGES : Boolean Read fREQUEST_DELETE_PACKAGES Write fREQUEST_DELETE_PACKAGES;
Property REQUEST_IGNORE_BATTERY_OPTIMIZATIONS : Boolean Read fREQUEST_IGNORE_BATTERY_OPTIMIZATIONS Write fREQUEST_IGNORE_BATTERY_OPTIMIZATIONS;
Property REQUEST_INSTALL_PACKAGES : Boolean Read fREQUEST_INSTALL_PACKAGES Write fREQUEST_INSTALL_PACKAGES;
Property RESTART_PACKAGES : Boolean Read fRESTART_PACKAGES Write fRESTART_PACKAGES;
Property SEND_RESPOND_VIA_MESSAGE : Boolean Read fSEND_RESPOND_VIA_MESSAGE Write fSEND_RESPOND_VIA_MESSAGE;
Property SEND_SMS : Boolean Read fSEND_SMS Write fSEND_SMS;
Property SET_ALARM : Boolean Read fSET_ALARM Write fSET_ALARM;
Property SET_ALWAYS_FINISH : Boolean Read fSET_ALWAYS_FINISH Write fSET_ALWAYS_FINISH;
Property SET_ANIMATION_SCALE : Boolean Read fSET_ANIMATION_SCALE Write fSET_ANIMATION_SCALE;
Property SET_DEBUG_APP : Boolean Read fSET_DEBUG_APP Write fSET_DEBUG_APP;
Property SET_PREFERRED_APPLICATIONS : Boolean Read fSET_PREFERRED_APPLICATIONS Write fSET_PREFERRED_APPLICATIONS;
Property SET_PROCESS_LIMIT : Boolean Read fSET_PROCESS_LIMIT Write fSET_PROCESS_LIMIT;
Property SET_TIME : Boolean Read fSET_TIME Write fSET_TIME;
Property SET_TIME_ZONE : Boolean Read fSET_TIME_ZONE Write fSET_TIME_ZONE;
Property SET_WALLPAPER : Boolean Read fSET_WALLPAPER Write fSET_WALLPAPER;
Property SET_WALLPAPER_HINTS : Boolean Read fSET_WALLPAPER_HINTS Write fSET_WALLPAPER_HINTS;
Property SIGNAL_PERSISTENT_PROCESSES : Boolean Read fSIGNAL_PERSISTENT_PROCESSES Write fSIGNAL_PERSISTENT_PROCESSES;
Property STATUS_BAR : Boolean Read fSTATUS_BAR Write fSTATUS_BAR;
Property SYSTEM_ALERT_WINDOW : Boolean Read fSYSTEM_ALERT_WINDOW Write fSYSTEM_ALERT_WINDOW;
Property TRANSMIT_IR : Boolean Read fTRANSMIT_IR Write fTRANSMIT_IR;
Property UNINSTALL_SHORTCUT : Boolean Read fUNINSTALL_SHORTCUT Write fUNINSTALL_SHORTCUT;
Property UPDATE_DEVICE_STATS : Boolean Read fUPDATE_DEVICE_STATS Write fUPDATE_DEVICE_STATS;
Property USE_FINGERPRINT : Boolean Read fUSE_FINGERPRINT Write fUSE_FINGERPRINT;
Property USE_BIOMETRIC : Boolean Read fUSE_BIOMETRIC Write fUSE_BIOMETRIC;
Property USE_SIP : Boolean Read fUSE_SIP Write fUSE_SIP;
Property VIBRATE : Boolean Read fVIBRATE Write fVIBRATE;
Property WAKE_LOCK : Boolean Read fWAKE_LOCK Write fWAKE_LOCK;
Property WRITE_APN_SETTINGS : Boolean Read fWRITE_APN_SETTINGS Write fWRITE_APN_SETTINGS;
Property WRITE_CALENDAR : Boolean Read fWRITE_CALENDAR Write fWRITE_CALENDAR;
Property WRITE_CALL_LOG : Boolean Read fWRITE_CALL_LOG Write fWRITE_CALL_LOG;
Property WRITE_CONTACTS : Boolean Read fWRITE_CONTACTS Write fWRITE_CONTACTS;
Property WRITE_EXTERNAL_STORAGE : Boolean Read fWRITE_EXTERNAL_STORAGE Write fWRITE_EXTERNAL_STORAGE;
Property WRITE_GSERVICES : Boolean Read fWRITE_GSERVICES Write fWRITE_GSERVICES;
Property WRITE_SECURE_SETTINGS : Boolean Read fWRITE_SECURE_SETTINGS Write fWRITE_SECURE_SETTINGS;
Property WRITE_SETTINGS : Boolean Read fWRITE_SETTINGS Write fWRITE_SETTINGS;
Property WRITE_SYNC_SETTINGS : Boolean Read fWRITE_SYNC_SETTINGS Write fWRITE_SYNC_SETTINGS;
Property WRITE_VOICEMAIL : Boolean Read fWRITE_VOICEMAIL Write fWRITE_VOICEMAIL;
End;
TAndroidPermissionsMessages = Class(TPersistent)
Private
fSEND_SMS: String;
fCAPTURE_AUDIO_OUTPUT: String;
fWRITE_VOICEMAIL: String;
fWRITE_SECURE_SETTINGS: String;
fSET_TIME_ZONE: String;
fREAD_SYNC_SETTINGS: String;
fMODIFY_AUDIO_SETTINGS: String;
fKILL_BACKGROUND_PROCESSES: String;
fGET_TASKS: String;
fDELETE_CACHE_FILES: String;
fCAPTURE_VIDEO_OUTPUT: String;
fBIND_NOTIFICATION_LISTENER_SERVICE: String;
fUPDATE_DEVICE_STATS: String;
fREAD_CONTACTS: String;
fBIND_TELECOM_CONNECTION_SERVICE: String;
fBIND_PRINT_SERVICE: String;
fRECORD_AUDIO: String;
fREAD_FRAME_BUFFER: String;
fMOUNT_UNMOUNT_FILESYSTEMS: String;
fPACKAGE_USAGE_STATS: String;
fGET_PACKAGE_SIZE: String;
fBROADCAST_STICKY: String;
fWRITE_SYNC_SETTINGS: String;
fREAD_SMS: String;
fREAD_CALENDAR: String;
fCONTROL_LOCATION_UPDATES: String;
fBIND_REMOTEVIEWS: String;
fADD_VOICEMAIL: String;
fWRITE_CONTACTS: String;
fREAD_INPUT_STATE: String;
fCHANGE_NETWORK_STATE: String;
fCAPTURE_SECURE_VIDEO_OUTPUT: String;
fCAMERA: String;
fBIND_NFC_SERVICE: String;
fWRITE_GSERVICES: String;
fSET_WALLPAPER: String;
fREQUEST_DELETE_PACKAGES: String;
fBIND_VPN_SERVICE: String;
fBIND_CHOOSER_TARGET_SERVICE: String;
fINSTALL_PACKAGES: String;
fCLEAR_APP_CACHE: String;
fBIND_VR_LISTENER_SERVICE: String;
fACCESS_NOTIFICATION_POLICY: String;
fWRITE_CALENDAR: String;
fSET_TIME: String;
fDUMP: String;
fBROADCAST_SMS: String;
fBIND_TEXT_SERVICE: String;
fBIND_MIDI_DEVICE_SERVICE: String;
fBIND_ACCESSIBILITY_SERVICE: String;
fBATTERY_STATS: String;
fUSE_SIP: String;
fUSE_FINGERPRINT: String;
fUSE_BIOMETRIC : String;
fTRANSMIT_IR: String;
fSEND_RESPOND_VIA_MESSAGE: String;
fREAD_EXTERNAL_STORAGE: String;
fDIAGNOSTIC: String;
fBIND_APPWIDGET: String;
fPERSISTENT_ACTIVITY: String;
fBIND_CONDITION_PROVIDER_SERVICE: String;
fSET_ANIMATION_SCALE: String;
fSET_ALARM: String;
fREAD_SYNC_STATS: String;
fCHANGE_WIFI_STATE: String;
fSTATUS_BAR: String;
fMOUNT_FORMAT_FILESYSTEMS: String;
fMANAGE_DOCUMENTS: String;
fWRITE_EXTERNAL_STORAGE: String;
fLOCATION_HARDWARE: String;
fGLOBAL_SEARCH: String;
fACCESS_NETWORK_STATE: String;
fVIBRATE: String;
fRECEIVE_SMS: String;
fRECEIVE_BOOT_COMPLETED: String;
fCHANGE_WIFI_MULTICAST_STATE: String;
fBIND_CARRIER_SERVICES: String;
fSET_PROCESS_LIMIT: String;
fREBOOT: String;
fCHANGE_CONFIGURATION: String;
fBLUETOOTH_ADMIN: String;
fBIND_DEVICE_ADMIN: String;
fBIND_AUTOFILL_SERVICE: String;
fANSWER_PHONE_CALLS: String;
fBODY_SENSORS: String;
fBIND_TV_INPUT: String;
fBIND_QUICK_SETTINGS_TILE: String;
fBIND_INCALL_SERVICE: String;
fSET_DEBUG_APP: String;
fRESTART_PACKAGES: String;
fREQUEST_IGNORE_BATTERY_OPTIMIZATIONS: String;
fBIND_DREAM_SERVICE: String;
fEXPAND_STATUS_BAR: String;
fDELETE_PACKAGES: String;
fACCESS_COARSE_LOCATION: String;
fSET_ALWAYS_FINISH: String;
fREAD_CALL_LOG: String;
fINTERNET: String;
fINSTANT_APP_FOREGROUND_SERVICE: String;
fBIND_VISUAL_VOICEMAIL_SERVICE: String;
fACCESS_WIFI_STATE: String;
fPROCESS_OUTGOING_CALLS: String;
fNFC: String;
fMANAGE_OWN_CALLS: String;
fINSTALL_SHORTCUT: String;
fWRITE_APN_SETTINGS: String;
fUNINSTALL_SHORTCUT: String;
fSET_WALLPAPER_HINTS: String;
fMODIFY_PHONE_STATE: String;
fDISABLE_KEYGUARD: String;
fBROADCAST_WAP_PUSH: String;
fBIND_VOICE_INTERACTION: String;
fBIND_CARRIER_MESSAGING_SERVICE: String;
fCHANGE_COMPONENT_ENABLED_STATE: String;
fBLUETOOTH_PRIVILEGED: String;
fBIND_SCREENING_SERVICE: String;
fWRITE_CALL_LOG: String;
fWAKE_LOCK: String;
fCALL_PRIVILEGED: String;
fSYSTEM_ALERT_WINDOW: String;
fREQUEST_COMPANION_USE_DATA_IN_BACKGROUND: String;
fMASTER_CLEAR: String;
fINSTALL_LOCATION_PROVIDER: String;
fSIGNAL_PERSISTENT_PROCESSES: String;
fMEDIA_CONTENT_CONTROL: String;
fFACTORY_TEST: String;
fBLUETOOTH: String;
fACCESS_CHECKIN_PROPERTIES: String;
fREQUEST_COMPANION_RUN_IN_BACKGROUND: String;
fGET_ACCOUNTS_PRIVILEGED: String;
fBROADCAST_PACKAGE_REMOVED: String;
fACCESS_LOCATION_EXTRA_COMMANDS: String;
fWRITE_SETTINGS: String;
fREQUEST_INSTALL_PACKAGES: String;
fREORDER_TASKS: String;
fRECEIVE_WAP_PUSH: String;
fREAD_PHONE_STATE: String;
fREAD_LOGS: String;
fBIND_INPUT_METHOD: String;
fSET_PREFERRED_APPLICATIONS: String;
fRECEIVE_MMS: String;
fREAD_VOICEMAIL: String;
fREAD_PHONE_NUMBERS: String;
fBIND_WALLPAPER: String;
fACCOUNT_MANAGER: String;
fGET_ACCOUNTS: String;
fCALL_PHONE: String;
fACCESS_FINE_LOCATION: String;
Published
Property ACCESS_CHECKIN_PROPERTIES : String Read fACCESS_CHECKIN_PROPERTIES Write fACCESS_CHECKIN_PROPERTIES;
Property ACCESS_COARSE_LOCATION : String Read fACCESS_COARSE_LOCATION Write fACCESS_COARSE_LOCATION;
Property ACCESS_FINE_LOCATION : String Read fACCESS_FINE_LOCATION Write fACCESS_FINE_LOCATION;
Property ACCESS_LOCATION_EXTRA_COMMANDS : String Read fACCESS_LOCATION_EXTRA_COMMANDS Write fACCESS_LOCATION_EXTRA_COMMANDS;
Property ACCESS_NETWORK_STATE : String Read fACCESS_NETWORK_STATE Write fACCESS_NETWORK_STATE;
Property ACCESS_NOTIFICATION_POLICY : String Read fACCESS_NOTIFICATION_POLICY Write fACCESS_NOTIFICATION_POLICY;
Property ACCESS_WIFI_STATE : String Read fACCESS_WIFI_STATE Write fACCESS_WIFI_STATE;
Property ACCOUNT_MANAGER : String Read fACCOUNT_MANAGER Write fACCOUNT_MANAGER;
Property ADD_VOICEMAIL : String Read fADD_VOICEMAIL Write fADD_VOICEMAIL;
Property ANSWER_PHONE_CALLS : String Read fANSWER_PHONE_CALLS Write fANSWER_PHONE_CALLS;
Property BATTERY_STATS : String Read fBATTERY_STATS Write fBATTERY_STATS;
Property BIND_ACCESSIBILITY_SERVICE : String Read fBIND_ACCESSIBILITY_SERVICE Write fBIND_ACCESSIBILITY_SERVICE;
Property BIND_APPWIDGET : String Read fBIND_APPWIDGET Write fBIND_APPWIDGET;
Property BIND_AUTOFILL_SERVICE : String Read fBIND_AUTOFILL_SERVICE Write fBIND_AUTOFILL_SERVICE;
Property BIND_CARRIER_MESSAGING_SERVICE : String Read fBIND_CARRIER_MESSAGING_SERVICE Write fBIND_CARRIER_MESSAGING_SERVICE;
Property BIND_CARRIER_SERVICES : String Read fBIND_CARRIER_SERVICES Write fBIND_CARRIER_SERVICES;
Property BIND_CHOOSER_TARGET_SERVICE : String Read fBIND_CHOOSER_TARGET_SERVICE Write fBIND_CHOOSER_TARGET_SERVICE;
Property BIND_CONDITION_PROVIDER_SERVICE : String Read fBIND_CONDITION_PROVIDER_SERVICE Write fBIND_CONDITION_PROVIDER_SERVICE;
Property BIND_DEVICE_ADMIN : String Read fBIND_DEVICE_ADMIN Write fBIND_DEVICE_ADMIN;
Property BIND_DREAM_SERVICE : String Read fBIND_DREAM_SERVICE Write fBIND_DREAM_SERVICE;
Property BIND_INCALL_SERVICE : String Read fBIND_INCALL_SERVICE Write fBIND_INCALL_SERVICE;
Property BIND_INPUT_METHOD : String Read fBIND_INPUT_METHOD Write fBIND_INPUT_METHOD;
Property BIND_MIDI_DEVICE_SERVICE : String Read fBIND_MIDI_DEVICE_SERVICE Write fBIND_MIDI_DEVICE_SERVICE;
Property BIND_NFC_SERVICE : String Read fBIND_NFC_SERVICE Write fBIND_NFC_SERVICE;
Property BIND_NOTIFICATION_LISTENER_SERVICE : String Read fBIND_NOTIFICATION_LISTENER_SERVICE Write fBIND_NOTIFICATION_LISTENER_SERVICE;
Property BIND_PRINT_SERVICE : String Read fBIND_PRINT_SERVICE Write fBIND_PRINT_SERVICE;
Property BIND_QUICK_SETTINGS_TILE : String Read fBIND_QUICK_SETTINGS_TILE Write fBIND_QUICK_SETTINGS_TILE;
Property BIND_REMOTEVIEWS : String Read fBIND_REMOTEVIEWS Write fBIND_REMOTEVIEWS;
Property BIND_SCREENING_SERVICE : String Read fBIND_SCREENING_SERVICE Write fBIND_SCREENING_SERVICE;
Property BIND_TELECOM_CONNECTION_SERVICE : String Read fBIND_TELECOM_CONNECTION_SERVICE Write fBIND_TELECOM_CONNECTION_SERVICE;
Property BIND_TEXT_SERVICE : String Read fBIND_TEXT_SERVICE Write fBIND_TEXT_SERVICE;
Property BIND_TV_INPUT : String Read fBIND_TV_INPUT Write fBIND_TV_INPUT;
Property BIND_VISUAL_VOICEMAIL_SERVICE : String Read fBIND_VISUAL_VOICEMAIL_SERVICE Write fBIND_VISUAL_VOICEMAIL_SERVICE;
Property BIND_VOICE_INTERACTION : String Read fBIND_VOICE_INTERACTION Write fBIND_VOICE_INTERACTION;
Property BIND_VPN_SERVICE : String Read fBIND_VPN_SERVICE Write fBIND_VPN_SERVICE;
Property BIND_VR_LISTENER_SERVICE : String Read fBIND_VR_LISTENER_SERVICE Write fBIND_VR_LISTENER_SERVICE;
Property BIND_WALLPAPER : String Read fBIND_WALLPAPER Write fBIND_WALLPAPER;
Property BLUETOOTH : String Read fBLUETOOTH Write fBLUETOOTH;
Property BLUETOOTH_ADMIN : String Read fBLUETOOTH_ADMIN Write fBLUETOOTH_ADMIN;
Property BLUETOOTH_PRIVILEGED : String Read fBLUETOOTH_PRIVILEGED Write fBLUETOOTH_PRIVILEGED;
Property BODY_SENSORS : String Read fBODY_SENSORS Write fBODY_SENSORS;
Property BROADCAST_PACKAGE_REMOVED : String Read fBROADCAST_PACKAGE_REMOVED Write fBROADCAST_PACKAGE_REMOVED;
Property BROADCAST_SMS : String Read fBROADCAST_SMS Write fBROADCAST_SMS;
Property BROADCAST_STICKY : String Read fBROADCAST_STICKY Write fBROADCAST_STICKY;
Property BROADCAST_WAP_PUSH : String Read fBROADCAST_WAP_PUSH Write fBROADCAST_WAP_PUSH;
Property CALL_PHONE : String Read fCALL_PHONE Write fCALL_PHONE;
Property CALL_PRIVILEGED : String Read fCALL_PRIVILEGED Write fCALL_PRIVILEGED;
Property CAMERA : String Read fCAMERA Write fCAMERA;
Property CAPTURE_AUDIO_OUTPUT : String Read fCAPTURE_AUDIO_OUTPUT Write fCAPTURE_AUDIO_OUTPUT;
Property CAPTURE_SECURE_VIDEO_OUTPUT : String Read fCAPTURE_SECURE_VIDEO_OUTPUT Write fCAPTURE_SECURE_VIDEO_OUTPUT;
Property CAPTURE_VIDEO_OUTPUT : String Read fCAPTURE_VIDEO_OUTPUT Write fCAPTURE_VIDEO_OUTPUT;
Property CHANGE_COMPONENT_ENABLED_STATE : String Read fCHANGE_COMPONENT_ENABLED_STATE Write fCHANGE_COMPONENT_ENABLED_STATE;
Property CHANGE_CONFIGURATION : String Read fCHANGE_CONFIGURATION Write fCHANGE_CONFIGURATION;
Property CHANGE_NETWORK_STATE : String Read fCHANGE_NETWORK_STATE Write fCHANGE_NETWORK_STATE;
Property CHANGE_WIFI_MULTICAST_STATE : String Read fCHANGE_WIFI_MULTICAST_STATE Write fCHANGE_WIFI_MULTICAST_STATE;
Property CHANGE_WIFI_STATE : String Read fCHANGE_WIFI_STATE Write fCHANGE_WIFI_STATE;
Property CLEAR_APP_CACHE : String Read fCLEAR_APP_CACHE Write fCLEAR_APP_CACHE;
Property CONTROL_LOCATION_UPDATES : String Read fCONTROL_LOCATION_UPDATES Write fCONTROL_LOCATION_UPDATES;
Property DELETE_CACHE_FILES : String Read fDELETE_CACHE_FILES Write fDELETE_CACHE_FILES;
Property DELETE_PACKAGES : String Read fDELETE_PACKAGES Write fDELETE_PACKAGES;
Property DIAGNOSTIC : String Read fDIAGNOSTIC Write fDIAGNOSTIC;
Property DISABLE_KEYGUARD : String Read fDISABLE_KEYGUARD Write fDISABLE_KEYGUARD;
Property DUMP : String Read fDUMP Write fDUMP;
Property EXPAND_STATUS_BAR : String Read fEXPAND_STATUS_BAR Write fEXPAND_STATUS_BAR;
Property FACTORY_TEST : String Read fFACTORY_TEST Write fFACTORY_TEST;
Property GET_ACCOUNTS : String Read fGET_ACCOUNTS Write fGET_ACCOUNTS;
Property GET_ACCOUNTS_PRIVILEGED : String Read fGET_ACCOUNTS_PRIVILEGED Write fGET_ACCOUNTS_PRIVILEGED;
Property GET_PACKAGE_SIZE : String Read fGET_PACKAGE_SIZE Write fGET_PACKAGE_SIZE;
Property GET_TASKS : String Read fGET_TASKS Write fGET_TASKS;
Property GLOBAL_SEARCH : String Read fGLOBAL_SEARCH Write fGLOBAL_SEARCH;
Property INSTALL_LOCATION_PROVIDER : String Read fINSTALL_LOCATION_PROVIDER Write fINSTALL_LOCATION_PROVIDER;
Property INSTALL_PACKAGES : String Read fINSTALL_PACKAGES Write fINSTALL_PACKAGES;
Property INSTALL_SHORTCUT : String Read fINSTALL_SHORTCUT Write fINSTALL_SHORTCUT;
Property INSTANT_APP_FOREGROUND_SERVICE : String Read fINSTANT_APP_FOREGROUND_SERVICE Write fINSTANT_APP_FOREGROUND_SERVICE;
Property INTERNET : String Read fINTERNET Write fINTERNET;
Property KILL_BACKGROUND_PROCESSES : String Read fKILL_BACKGROUND_PROCESSES Write fKILL_BACKGROUND_PROCESSES;
Property LOCATION_HARDWARE : String Read fLOCATION_HARDWARE Write fLOCATION_HARDWARE;
Property MANAGE_DOCUMENTS : String Read fMANAGE_DOCUMENTS Write fMANAGE_DOCUMENTS;
Property MANAGE_OWN_CALLS : String Read fMANAGE_OWN_CALLS Write fMANAGE_OWN_CALLS;
Property MASTER_CLEAR : String Read fMASTER_CLEAR Write fMASTER_CLEAR;
Property MEDIA_CONTENT_CONTROL : String Read fMEDIA_CONTENT_CONTROL Write fMEDIA_CONTENT_CONTROL;
Property MODIFY_AUDIO_SETTINGS : String Read fMODIFY_AUDIO_SETTINGS Write fMODIFY_AUDIO_SETTINGS;
Property MODIFY_PHONE_STATE : String Read fMODIFY_PHONE_STATE Write fMODIFY_PHONE_STATE;
Property MOUNT_FORMAT_FILESYSTEMS : String Read fMOUNT_FORMAT_FILESYSTEMS Write fMOUNT_FORMAT_FILESYSTEMS;
Property MOUNT_UNMOUNT_FILESYSTEMS : String Read fMOUNT_UNMOUNT_FILESYSTEMS Write fMOUNT_UNMOUNT_FILESYSTEMS;
Property NFC : String Read fNFC Write fNFC;
Property PACKAGE_USAGE_STATS : String Read fPACKAGE_USAGE_STATS Write fPACKAGE_USAGE_STATS;
Property PERSISTENT_ACTIVITY : String Read fPERSISTENT_ACTIVITY Write fPERSISTENT_ACTIVITY;
Property PROCESS_OUTGOING_CALLS : String Read fPROCESS_OUTGOING_CALLS Write fPROCESS_OUTGOING_CALLS;
Property READ_CALENDAR : String Read fREAD_CALENDAR Write fREAD_CALENDAR;
Property READ_CALL_LOG : String Read fREAD_CALL_LOG Write fREAD_CALL_LOG;
Property READ_CONTACTS : String Read fREAD_CONTACTS Write fREAD_CONTACTS;
Property READ_EXTERNAL_STORAGE : String Read fREAD_EXTERNAL_STORAGE Write fREAD_EXTERNAL_STORAGE;
Property READ_FRAME_BUFFER : String Read fREAD_FRAME_BUFFER Write fREAD_FRAME_BUFFER;
Property READ_INPUT_STATE : String Read fREAD_INPUT_STATE Write fREAD_INPUT_STATE;
Property READ_LOGS : String Read fREAD_LOGS Write fREAD_LOGS;
Property READ_PHONE_NUMBERS : String Read fREAD_PHONE_NUMBERS Write fREAD_PHONE_NUMBERS;
Property READ_PHONE_STATE : String Read fREAD_PHONE_STATE Write fREAD_PHONE_STATE;
Property READ_SMS : String Read fREAD_SMS Write fREAD_SMS;
Property READ_SYNC_SETTINGS : String Read fREAD_SYNC_SETTINGS Write fREAD_SYNC_SETTINGS;
Property READ_SYNC_STATS : String Read fREAD_SYNC_STATS Write fREAD_SYNC_STATS;
Property READ_VOICEMAIL : String Read fREAD_VOICEMAIL Write fREAD_VOICEMAIL;
Property REBOOT : String Read fREBOOT Write fREBOOT;
Property RECEIVE_BOOT_COMPLETED : String Read fRECEIVE_BOOT_COMPLETED Write fRECEIVE_BOOT_COMPLETED;
Property RECEIVE_MMS : String Read fRECEIVE_MMS Write fRECEIVE_MMS;
Property RECEIVE_SMS : String Read fRECEIVE_SMS Write fRECEIVE_SMS;
Property RECEIVE_WAP_PUSH : String Read fRECEIVE_WAP_PUSH Write fRECEIVE_WAP_PUSH;
Property RECORD_AUDIO : String Read fRECORD_AUDIO Write fRECORD_AUDIO;
Property REORDER_TASKS : String Read fREORDER_TASKS Write fREORDER_TASKS;
Property REQUEST_COMPANION_RUN_IN_BACKGROUND : String Read fREQUEST_COMPANION_RUN_IN_BACKGROUND Write fREQUEST_COMPANION_RUN_IN_BACKGROUND;
Property REQUEST_COMPANION_USE_DATA_IN_BACKGROUND : String Read fREQUEST_COMPANION_USE_DATA_IN_BACKGROUND Write fREQUEST_COMPANION_USE_DATA_IN_BACKGROUND;
Property REQUEST_DELETE_PACKAGES : String Read fREQUEST_DELETE_PACKAGES Write fREQUEST_DELETE_PACKAGES;
Property REQUEST_IGNORE_BATTERY_OPTIMIZATIONS : String Read fREQUEST_IGNORE_BATTERY_OPTIMIZATIONS Write fREQUEST_IGNORE_BATTERY_OPTIMIZATIONS;
Property REQUEST_INSTALL_PACKAGES : String Read fREQUEST_INSTALL_PACKAGES Write fREQUEST_INSTALL_PACKAGES;
Property RESTART_PACKAGES : String Read fRESTART_PACKAGES Write fRESTART_PACKAGES;
Property SEND_RESPOND_VIA_MESSAGE : String Read fSEND_RESPOND_VIA_MESSAGE Write fSEND_RESPOND_VIA_MESSAGE;
Property SEND_SMS : String Read fSEND_SMS Write fSEND_SMS;
Property SET_ALARM : String Read fSET_ALARM Write fSET_ALARM;
Property SET_ALWAYS_FINISH : String Read fSET_ALWAYS_FINISH Write fSET_ALWAYS_FINISH;
Property SET_ANIMATION_SCALE : String Read fSET_ANIMATION_SCALE Write fSET_ANIMATION_SCALE;
Property SET_DEBUG_APP : String Read fSET_DEBUG_APP Write fSET_DEBUG_APP;
Property SET_PREFERRED_APPLICATIONS : String Read fSET_PREFERRED_APPLICATIONS Write fSET_PREFERRED_APPLICATIONS;
Property SET_PROCESS_LIMIT : String Read fSET_PROCESS_LIMIT Write fSET_PROCESS_LIMIT;
Property SET_TIME : String Read fSET_TIME Write fSET_TIME;
Property SET_TIME_ZONE : String Read fSET_TIME_ZONE Write fSET_TIME_ZONE;
Property SET_WALLPAPER : String Read fSET_WALLPAPER Write fSET_WALLPAPER;
Property SET_WALLPAPER_HINTS : String Read fSET_WALLPAPER_HINTS Write fSET_WALLPAPER_HINTS;
Property SIGNAL_PERSISTENT_PROCESSES : String Read fSIGNAL_PERSISTENT_PROCESSES Write fSIGNAL_PERSISTENT_PROCESSES;
Property STATUS_BAR : String Read fSTATUS_BAR Write fSTATUS_BAR;
Property SYSTEM_ALERT_WINDOW : String Read fSYSTEM_ALERT_WINDOW Write fSYSTEM_ALERT_WINDOW;
Property TRANSMIT_IR : String Read fTRANSMIT_IR Write fTRANSMIT_IR;
Property UNINSTALL_SHORTCUT : String Read fUNINSTALL_SHORTCUT Write fUNINSTALL_SHORTCUT;
Property UPDATE_DEVICE_STATS : String Read fUPDATE_DEVICE_STATS Write fUPDATE_DEVICE_STATS;
Property USE_FINGERPRINT : String Read fUSE_FINGERPRINT Write fUSE_FINGERPRINT;
Property USE_BIOMETRIC : String Read fUSE_BIOMETRIC Write fUSE_BIOMETRIC;
Property USE_SIP : String Read fUSE_SIP Write fUSE_SIP;
Property VIBRATE : String Read fVIBRATE Write fVIBRATE;
Property WAKE_LOCK : String Read fWAKE_LOCK Write fWAKE_LOCK;
Property WRITE_APN_SETTINGS : String Read fWRITE_APN_SETTINGS Write fWRITE_APN_SETTINGS;
Property WRITE_CALENDAR : String Read fWRITE_CALENDAR Write fWRITE_CALENDAR;
Property WRITE_CALL_LOG : String Read fWRITE_CALL_LOG Write fWRITE_CALL_LOG;
Property WRITE_CONTACTS : String Read fWRITE_CONTACTS Write fWRITE_CONTACTS;
Property WRITE_EXTERNAL_STORAGE : String Read fWRITE_EXTERNAL_STORAGE Write fWRITE_EXTERNAL_STORAGE;
Property WRITE_GSERVICES : String Read fWRITE_GSERVICES Write fWRITE_GSERVICES;
Property WRITE_SECURE_SETTINGS : String Read fWRITE_SECURE_SETTINGS Write fWRITE_SECURE_SETTINGS;
Property WRITE_SETTINGS : String Read fWRITE_SETTINGS Write fWRITE_SETTINGS;
Property WRITE_SYNC_SETTINGS : String Read fWRITE_SYNC_SETTINGS Write fWRITE_SYNC_SETTINGS;
Property WRITE_VOICEMAIL : String Read fWRITE_VOICEMAIL Write fWRITE_VOICEMAIL;
End;
{$IFDEF ANDROID}
JFileProvider = interface;
JFileProviderClass = interface(JContentProviderClass)
['{33A87969-5731-4791-90F6-3AD22F2BB822}']
{class} function getUriForFile(context: JContext; authority: JString; _file: JFile): Jnet_Uri; cdecl;
{class} function init: JFileProvider; cdecl;
end;
[JavaSignature('android/support/v4/content/FileProvider')]
JFileProvider = interface(JContentProvider)
['{12F5DD38-A3CE-4D2E-9F68-24933C9D221B}']
procedure attachInfo(context: JContext; info: JProviderInfo); cdecl;
function delete(uri: Jnet_Uri; selection: JString; selectionArgs: TJavaObjectArray<JString>): Integer; cdecl;
function getType(uri: Jnet_Uri): JString; cdecl;
function insert(uri: Jnet_Uri; values: JContentValues): Jnet_Uri; cdecl;
function onCreate: Boolean; cdecl;
function openFile(uri: Jnet_Uri; mode: JString): JParcelFileDescriptor; cdecl;
function query(uri: Jnet_Uri; projection: TJavaObjectArray<JString>; selection: JString; selectionArgs: TJavaObjectArray<JString>; sortOrder: JString): JCursor; cdecl;
function update(uri: Jnet_Uri; values: JContentValues; selection: JString; selectionArgs: TJavaObjectArray<JString>): Integer; cdecl;
end;
TJFileProvider = class(TJavaGenericImport<JFileProviderClass, JFileProvider>) end;
{$ENDIF}
{$IF DEFINED(VER330) OR DEFINED(VER340)}
[ComponentPlatformsAttribute (pidAndroid32Arm Or pidAndroid64Arm)]
{$ELSE}
[ComponentPlatformsAttribute (pidAndroid)]
{$ENDIF}
TAndroidPermissions = Class(TComponent)
Private
// FMSG : TISMessageDlg;
FPropList : PPropList;
FPropInfo : PPropInfo;
FPropListCount : Integer;
FPermissionsList : TStringList;
FPermissionsDeniedList : TStringList;
FAutoRequest : Boolean;
FDisplayRationale : Boolean;
FDisplayHeader : String;
FPermissionsRequest : TAndroidPermissionsNames;
FPermissionsGranted : TAndroidPermissionsNames;
FPermissionsDenied : TAndroidPermissionsNames;
FPermissionsMessages : TAndroidPermissionsMessages;
FPermissions : TArray<String>;
FRequestResponse : TNotifyEvent;
FAllPermissionsGranted : TNotifyEvent;
FSomePermissionsDenied : TNotifyEvent;
{$IF DEFINED(VER330) OR DEFINED(VER340)}
procedure PermissionsResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>);
{$ENDIF}
Protected
{$IF DEFINED(VER330) OR DEFINED(VER340)}
Procedure Loaded; Override;
{$ENDIF}
Public
Constructor Create(aOwner : TComponent); Override;
Destructor Destroy; Override;
{$IF DEFINED(VER330) OR DEFINED(VER340)}
{$IFDEF ANDROID}
Function GetFileUri(aFile: String): JNet_Uri;
{$ENDIF}
Function AllRequiredGranted : Boolean;
Function SomePermissionsDenied : Boolean;
Function GetPermissionsDenied : TArray<String>;
Procedure GetPermissionsStatus;
Procedure RequestPermissions;
{$ENDIF}
Published
Property AutoRequestPermissions : Boolean Read FAutoRequest Write FAutoRequest;
// Property DisplayRationale : Boolean Read FDisplayRationale Write FDisplayRationale;
Property DisplayHeader : String Read FDisplayHeader Write FDisplayHeader;
Property PermissionsRequired : TAndroidPermissionsNames Read FPermissionsRequest Write FPermissionsRequest;
Property PermissionsGranted : TAndroidPermissionsNames Read FPermissionsGranted;
Property PermissionsDenied : TAndroidPermissionsNames Read FPermissionsDenied;
Property PermissionsMessages : TAndroidPermissionsMessages Read FPermissionsMessages Write FPermissionsMessages;
Property OnRequestResponse : TNotifyEvent Read FRequestResponse Write FRequestResponse;
Property OnAllPermissionsGranted : TNotifyEvent Read FAllPermissionsGranted Write FAllPermissionsGranted;
Property OnSomePermissionsDenied : TNotifyEvent Read FSomePermissionsDenied Write FSomePermissionsDenied;
End;
Implementation
{ TRCPermissions }
constructor TAndroidPermissions.Create(aOwner: TComponent);
var
I : Integer;
Name : String;
begin
inherited;
FAutoRequest := True;
FDisplayHeader := 'O aplicativo precisa de permissões para:';
FDisplayRationale := False;
FPermissionsList := TStringList.Create;
FPermissionsDeniedList := TStringList.Create;
FPermissionsRequest := TAndroidPermissionsNames.Create;
FPermissionsGranted := TAndroidPermissionsNames.Create;
FPermissionsDenied := TAndroidPermissionsNames.Create;
FPermissionsMessages := TAndroidPermissionsMessages.Create;
{$IFDEF ANDROID}
FPropListCount := GetPropList(TypeInfo(TAndroidPermissionsNames), FPropList);
//FMsg := TISMessageDlg.Create(Self);
For I := 0 to FPropListCount-1 do
begin
FPropInfo := FPropList^[I];
Name := FPropInfo^.NameFld.ToString;
FPermissionsList.Add(Name);
SetPropValue(FPermissionsMessages, Name, '');
end;
{$ENDIF}
end;
destructor TAndroidPermissions.Destroy;
begin
FPermissionsList .DisposeOf;
FPermissionsDeniedList.DisposeOf;
FPermissionsRequest .DisposeOf;
FPermissionsDenied .DisposeOf;
FPermissionsGranted .DisposeOf;
FPermissionsMessages .DisposeOf;
inherited;
end;
{$IF DEFINED(VER330) OR DEFINED(VER340)}
{$IFDEF ANDROID}
Function TAndroidPermissions.GetFileUri(aFile: String): JNet_Uri;
Var
FileAtt : JFile;
Auth : JString;
PackageName : String;
begin
PackageName := JStringToString(TAndroidHelper.Context.getPackageName);
FileAtt := TJFile.JavaClass.init(StringToJString(aFile));
Auth := StringToJString(Packagename+'.fileprovider');
Result := TJFileProvider.JavaClass.getUriForFile(TAndroidHelper.Context, Auth, FileAtt);
end;
{$ENDIF}
procedure TAndroidPermissions.Loaded;
begin
inherited;
{$IFDEF ANDROID}
if Not (csDesigning in ComponentState) then
Begin
TThread.CreateAnonymousThread(
procedure
Begin
Sleep(200);
TThread.Queue(Nil,
Procedure
Begin
GetPermissionsStatus;
if FAutoRequest And Not AllRequiredGranted then RequestPermissions;
End);
End).Start;
End;
{$ENDIF}
end;
function TAndroidPermissions.GetPermissionsDenied: TArray<String>;
Var
I, Q : Integer;
begin
Q := 0;
for I := 0 to FPermissionsList.Count-1 do
Begin
If (GetPropValue(FPermissionsRequest, FPermissionsList[I]) = True) And
(GetPropValue(FPermissionsDenied, FPermissionsList[I]) = True) Then
Inc(Q);
End;
SetLength(Result, Q);
Q := 0;
for I := 0 to FPermissionsList.Count-1 do
Begin
If (GetPropValue(FPermissionsRequest, FPermissionsList[I]) = True) And
(GetPropValue(FPermissionsDenied, FPermissionsList[I]) = True) Then
Begin
Result[Q] := FPermissionsList[I];
Inc(Q);
End;
End;
end;
procedure TAndroidPermissions.GetPermissionsStatus;
Var
I : Integer;
begin
FPermissionsDeniedList.Clear;
for I := 0 to FPermissionsList.Count-1 do
Begin
If PermissionsService.IsPermissionGranted('android.permission.'+FPermissionsList[I]) Then
Begin
SetPropValue(FPermissionsGranted, FPermissionsList[I], True);
SetPropValue(FPermissionsDenied, FPermissionsList[I], False);
End
Else
Begin
SetPropValue(FPermissionsGranted, FPermissionsList[I], False);
SetPropValue(FPermissionsDenied, FPermissionsList[I], True);
If GetPropValue(FPermissionsRequest, FPermissionsList[I]) = True Then //Comparado com true pq retorno é Variant
Begin
FPermissionsDeniedList.Add(FPermissionsList[I]);
End;
End;
End;
end;
function TAndroidPermissions.AllRequiredGranted: Boolean;
{$IFDEF ANDROID}
Var
I : Integer;
{$ENDIF}
begin
Result := True;
{$IFDEF ANDROID}
for I := 0 to FPermissionsList.Count-1 do
Begin
If (GetPropValue(FPermissionsRequest, FPermissionsList[I]) = True) And
(GetPropValue(FPermissionsDenied, FPermissionsList[I]) = True) Then
Result := False;
End;
{$ENDIF}
end;
function TAndroidPermissions.SomePermissionsDenied: Boolean;
begin
Result := Not AllRequiredGranted;
end;
procedure TAndroidPermissions.PermissionsResult(Sender: TObject; const APermissions: TArray<string>; const AGrantResults: TArray<TPermissionStatus>);
begin
GetPermissionsStatus;
if Assigned(OnRequestResponse) then OnRequestResponse(Sender);
if Assigned(OnAllPermissionsGranted) And AllRequiredGranted then OnAllPermissionsGranted(Sender);
if Assigned(OnSomePermissionsDenied) And SomePermissionsDenied then OnSomePermissionsDenied(Sender);
end;
procedure TAndroidPermissions.RequestPermissions;
Procedure LDisplayMessage;
Var
Permission : String;
MessageText : String;
Text : String;
I : Integer;
Begin
MessageText := '';
for I := 0 to FPermissionsDeniedList.Count-1 do
Begin
Permission := FPermissions[i].Remove(0, 19);
Text := GetPropValue(FPermissionsMessages, Permission);
Text := Text.Trim;
if Not Text.IsEmpty then MessageText := MessageText+'- '+Text + #13#10;
End;
if Not MessageText.IsEmpty then
Begin
MessageText := Self.FDisplayHeader+#13#10+#13#10+MessageText;
// FMsg.MessageOk(MessageText,
// Procedure
// Begin
// PermissionsService.RequestPermissions(FPermissions, PermissionsResult);
// End);
End;
End;
Var
I : Integer;
begin
SetLength(FPermissions, FPermissionsDeniedList.Count);
for I := 0 to FPermissionsDeniedList.Count-1 do
Begin
FPermissions[I] := 'android.permission.'+FPermissionsDeniedList[I];
End;
if FDisplayRationale then
LDisplayMessage
Else
PermissionsService.RequestPermissions(FPermissions, PermissionsResult);
end;
{$ENDIF}
Initialization
RegisterFMXClasses([TAndroidPermissions]);
end.
|
unit rssunit;
{$ifdef FPC}{$mode objfpc}{$h+}{$endif}
interface
type
TRSSItem = class
private
FAuthor: string;
FCategory: string;
FComments: string;
FDescription: string;
FGuid: string;
FLink: string;
FPubDate: string;
FTitle: string;
fContent: string;
fContentencoded: string;
public
constructor Create;
property Content: string read fContent;
property Title: string read FTitle;
property Link: string read FLink;
property Guid: string read FGuid;
property Category: string read FCategory;
property PubDate: string read FPubDate;
property Description: string read FDescription;
property Author: string read FAuthor;
property Comments: string read FComments;
property Contentencoded : string read fContentencoded;
end;
titemsarr = array of TRSSItem;
tRss = class
private
ftext : string;
ftitle,
flink,
fdescription,
flastBuildDate,
flanguage,
fgenerator : string;
fitems : titemsarr;
fitemcount : integer;
procedure parsetext(var txt : string);
public
constructor Create;
destructor Destroy; override;
procedure LoadFromFile(const fName: string);
procedure clear;
property title : string read ftitle;
property link : string read flink;
property description : string read fdescription;
property lastBuildDate : string read flastBuildDate;
property language : string read flanguage;
property generator : string read fgenerator;
property items : titemsarr read fitems;
property itemcount : integer read fitemcount;
end;
implementation
uses sysutils,classes;
function FileToString(FileName:String):String;
var hFile : Integer; nSize : Integer;
begin
hFile := FileOpen(FileName,fmOpenRead);
try
nSize := FileSeek(hFile,0,2); FileSeek(hFile,0,0);
SetLength(Result,nSize);
FileRead(hFile,Result[1],nSize);
finally
FileClose(hFile);
end;
end;
function cleartext(const txt : string) : string;
label a,c,d,e,f,g;
var s, s2,ss : string;
l,i : integer;
b : boolean;
begin
s := txt;
l := length(s);
i := 0;
if l > 1 then
while i < l do
begin
inc(i);
a:
b := false;
if pos('<pre',s) = i then begin delete(s,i,7);b := true; end;
if pos('</pre',s) = i then begin delete(s,i,8);b := true; end;
if pos('<p',s) = i then begin delete(s,i,5);b := true; end;
if pos('</p',s) = i then begin delete(s,i,6);b := true; end;
if pos('<code',s) = i then begin delete(s,i,8);b := true;end;
if pos('</code',s) = i then begin delete(s,i,9);b := true;end;
if pos('<ul',s) = i then begin delete(s,i,6);insert(#10,s,i);b := true;end;
if pos('</ul',s) = i then begin delete(s,i,7);insert(#10,s,i);b := true;end;
if pos('<em',s) = i then begin delete(s,i,6); b := true;end;
if pos('</em',s) = i then begin delete(s,i,7); b := true;end;
if pos('<li',s) = i then begin delete(s,i,6);insert(' - ',s,i);b := true;end;
if pos('</li',s) = i then begin delete(s,i,7);b := true;end;
if pos('"',s) = i then begin delete(s,i,6);b := true;end;
if pos('<strong',s) = i then begin delete(s,i,10);insert(' ',s,i);b := true;end;
if pos('</strong',s) = i then begin delete(s,i,11);insert(' ',s,i);b := true;end;
if pos('<div class="code"',s) = i then begin delete(s,i,20);insert(#10+'[code]----------------------------------------------------------'+#10,s,i);b := true;end;
if pos('</div',s) = i then begin delete(s,i,8);insert(#10+'[end]-----------------------------------------------------------'+#10,s,i);b := true;end;
if pos('</a',s) = i then begin delete(s,i,6);b := true;end;
if pos('&qt;',s) = i then begin delete(s,i,4);b := true; end;
if pos('<![CDATA[',s) = i then begin delete(s,i,9);b := true; end;
if pos(']]>',s) = i then begin delete(s,i,3);b := true; end;
if pos('<a',s) = i then
begin
d:
delete(s,i,1);
if s[i] <> '"' then goto d;
e:
delete(s,i,1);
if s[i] <> '"' then goto e;
delete(s,i,1);
b := true;
end;
if pos('&#',s) = i then
begin
f:
delete(s,i,1);
if s[i] <> ';' then goto f;
delete(s,i,1);
b := true;
end;
if pos('<img',s) = i then
begin
g:
delete(s,i,1);
if pos('<br /',s) <> i then goto g;
b := true;
end;
if pos('<br /',s) = i then begin delete(s,i,8);insert(#10,s,i); b := true; end; //must be last!!!
if pos('<br/',s) = i then begin delete(s,i,7);insert(#10,s,i); b := true; end; //must be last!!!
if pos('<strike',s) = i then begin delete(s,i,10);insert(' ',s,i);b := true; end; //must be last!!!
if pos('</strike',s) = i then begin delete(s,i,11);insert(' ',s,i);b := true; end; //must be last!!!
if pos('&rdquo;',s) = i then begin delete(s,i,11);insert(' ',s,i);b := true; end; //must be last!!!
if pos('&ldquo;',s) = i then begin delete(s,i,11);insert(' ',s,i);b := true; end; //must be last!!!
if pos('<p>',s) = i then begin delete(s,i,3); b := true; end;
if pos('</p>',s) = i then begin delete(s,i,4);insert(#10,s,i); b := true; end;
if pos('<br>',s) = i then begin delete(s,i,4);insert(#10,s,i); b := true; end;
if pos('<br />',s) = i then begin delete(s,i,6);insert(#10,s,i); b := true; end;
if pos('<ul>',s) = i then begin delete(s,i,4);insert(#10,s,i); b := true; end;
if pos('</ul>',s) = i then begin delete(s,i,5);insert(#10,s,i); b := true; end;
if pos('<li>',s) = i then begin delete(s,i,4);insert(' - ',s,i); b := true; end;
if pos('</li>',s) = i then begin delete(s,i,5);insert(#10,s,i); b := true; end;
if pos('<strong>',s) = i then begin delete(s,i,8);insert(' ',s,i); b := true; end;
if pos('</strong>',s) = i then begin delete(s,i,9);insert(' ',s,i); b := true; end;
if pos('<em>',s) = i then begin delete(s,i,4);insert(' ',s,i); b := true; end;
if pos('</em>',s) = i then begin delete(s,i,5);insert(' ',s,i); b := true; end;
if pos('<hr />',s) = i then begin delete(s,i,6);insert(#10,s,i); b := true; end;
if b = true then goto a;
l := length(s);
end;
for i := 1 to length(s) do
begin
c:
b := false;
if pos('>',s) = i then begin delete(s,i,4);b := true; end;
if b = true then goto c;
end;
result := s;
end;
function getparam(const fparam : string; var ftext : string) : string;
var txt : string;
p : integer;
begin
{
txt := copy(ftext, pos('<' + fparam + '>', ftext)
+ length('<' + fparam + '>'),
pos('</' + fparam + '>', ftext)
- pos('<' + fparam + '>', ftext)
- length('<' + fparam + '>'));
delete(ftext, pos('<' + fparam + '>', ftext),
pos('</' + fparam + '>', ftext)
- pos('<' + fparam + '>', ftext)
+ length('</' + fparam + '>'));
}
p := pos('<' + fparam, ftext);
if p > 0 then
begin
while ftext[p] <> '>' do delete(ftext,p,1);
delete(ftext,p,1);
txt := copy(ftext,p,pos('</' + fparam + '>',ftext) - p);
//writeln(fparam,'===',txt);
delete(ftext,p,pos('</' + fparam + '>',ftext) - p + length('</' + fparam + '>'));
//writeln('ftxt=================================================',ftext);
end;
result := cleartext(txt);
end;
constructor TRSS.Create;
begin
end;
destructor TRSS.Destroy;
begin
inherited Destroy;
end;
procedure TRSS.LoadFromFile(const fname : string);
begin
ftext := filetostring(fName);
parsetext(ftext);
end;
procedure TRSS.parsetext(var txt : string);
var itemtxt : string;
itm : TRSSItem;
r : integer;
begin
delete(txt,1,pos('<chanel',txt) - 1);
ftitle := getparam('title',txt);
flink := getparam('link',txt);
fdescription := getparam('description',txt);
flastBuildDate:= getparam('lastBuildDate',txt);
flanguage := getparam('language',txt);
fgenerator := getparam('generator',txt);
r := 0;
while system.pos('<item',txt) <> 0 do
begin
itemtxt := getparam('item',txt);
// writeln('==================================',txt);
itm := TRSSItem.create;
itm.FAuthor := getparam('author',itemtxt);
itm.FCategory:= getparam('category',itemtxt);
itm.FComments:= getparam('comments',itemtxt);
itm.FDescription := getparam('description',itemtxt);
itm.FGuid := getparam('guid',itemtxt);
itm.FLink := getparam('link',itemtxt);
itm.FPubDate := getparam('pubdate',itemtxt);
itm.FTitle := getparam('title',itemtxt);
itm.fContentencoded := getparam('content:encoded',itemtxt);
itm.fContent := getparam('content',itemtxt);
setlength(fitems,r + 1);
fitems[r] := itm;
inc(r);
end;
fitemcount := r;
end;
procedure TRSS.clear;
begin
ftitle := '';
flink := '';
fdescription := '';
flastBuildDate:= '';
flanguage := '';
fgenerator := '';
setlength(fitems,0);
fitemcount := 0;
end;
constructor TRSSItem.Create;
begin
end;
end.
|
unit Model.Interfaces;
interface
uses
//System.Generics.Collections,
Spring.Collections,
Model.Declarations,
Model.FormDeclarations,
Model.ProSu.Interfaces,
Spring.Data.ObjectDataset,
Spring.Persistence.Criteria.Interfaces,
Data.DB;
type
IMainModelInterface = interface
['{38A70DAE-34F2-4EC9-AD78-1B3517543BD8}']
end;
IMainViewModelInterface = interface(IMainModelInterface)
['{1A3025AE-0C33-4AB2-8185-EA4DE0EE30F9}']
function GetModel: IMainModelInterface;
procedure SetModel (const newModel: IMainModelInterface);
property Model: IMainModelInterface read GetModel write SetModel;
end;
ICountryModelInterface = interface
['{C2DF169E-C7E6-4856-A2A6-FD341F8FF0C3}']
function GetAllCountries(const filter : string) : IObjectList;
function GetAllCountriesDS(const filter : string) : TObjectDataset;
procedure AddCountry(const newCountry: TCountry);
function GetCountry(const CountryId : Integer) : TCountry;
procedure UpdateCountry(const Country: TCountry);
procedure DeleteCountry(const Country: TCountry);
end;
ICountryListViewModelInterface = interface
['{999DCC9B-01EF-4E2A-B2E4-F23C969886C7}']
function GetModel: ICountryModelInterface;
procedure SetModel(const newModel: ICountryModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: ICountryModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
ICountryEditViewModelInterface = interface
['{C68438F2-794E-4540-862E-C4CCCF52657B}']
function GetModel: ICountryModelInterface;
procedure SetModel(const newModel: ICountryModelInterface);
function GetProvider : IProviderInterface;
property Model: ICountryModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
ICityModelInterface = interface
['{406EDEA1-51EA-4123-8AB3-B8CC50979B31}']
function GetAllCities(const filter : string) : IObjectList;
function GetAllCitiesDS(const filter : string) : TObjectDataset;
procedure AddCity(const newCity: TCity);
function GetCity(const CityId : Integer) : TCity;
procedure UpdateCity(const City: TCity);
procedure DeleteCity(const City: TCity);
end;
ICityListViewModelInterface = interface
['{461262B4-9B11-4A52-8AF1-E5B16E739AD1}']
function GetModel: ICityModelInterface;
procedure SetModel(const newModel: ICityModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: ICityModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
ICityEditViewModelInterface = interface
['{4295B646-A223-4ECF-B5A1-663F1B8EFF1F}']
function GetModel: ICityModelInterface;
procedure SetModel(const newModel: ICityModelInterface);
function GetProvider : IProviderInterface;
property Model: ICityModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
ITownModelInterface = interface
['{52BF90BC-28E3-4DAC-8492-6B243DCB5208}']
//function GetTownListFormLabelsText: TTownListFormLabelsText;
function GetAllTowns(const filter : string) : IObjectList;
function GetTownsDataset(const filter : string) : TObjectDataset;
procedure AddTown(const newTown: TTown);
function GetTown(const TownId : Integer) : TTown;
procedure UpdateTown(const Town: TTown);
procedure DeleteTown(const Town: TTown);
end;
ITownListViewModelInterface = interface
['{DC5B9BFA-FCCD-4CB3-8122-1F0AEB749C02}']
function GetModel: ITownModelInterface;
procedure SetModel(const newModel: ITownModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: ITownModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
ITownEditViewModelInterface = interface
['{326BEB14-99DD-4F24-8420-0A56E420EEC9}']
function GetModel: ITownModelInterface;
procedure SetModel(const newModel: ITownModelInterface);
function GetProvider : IProviderInterface;
property Model: ITownModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
IEmployeeModelInterface = interface
['{58B3B10F-3B6D-4AD8-B85A-D0D03DE9260E}']
function GetAllEmployees(acompanyId : integer; const filter : string) : IObjectList;
function GetAllEmployeesDS(acompanyId : integer; const filter : string) : TObjectDataset;
procedure AddEmployee(const newEmployee: TEmployee);
function GetEmployee(const EmployeeId : Integer) : TEmployee;
procedure UpdateEmployee(const Employee: TEmployee);
procedure DeleteEmployee(const Employee: TEmployee);
end;
IEmployeeListViewModelInterface = interface
['{864F9C05-7333-4521-A466-46F304697221}']
function GetModel: IEmployeeModelInterface;
procedure SetModel(const newModel: IEmployeeModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: IEmployeeModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
IEmployeeEditViewModelInterface = interface
['{C037B0E2-85EC-4D6F-9B87-89465F494715}']
function GetModel: IEmployeeModelInterface;
procedure SetModel(const newModel: IEmployeeModelInterface);
function GetProvider : IProviderInterface;
property Model: IEmployeeModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
IOthIncomeOutcomeDefModelInterface = interface
['{AB8419CA-B652-4820-8595-15EF6E4D95E0}']
function GetAllOthIncomeOutcomeDefs(acompanyId : integer; const filter : string) : IObjectList;
function GetAllOthIncomeOutcomeDefsDS(acompanyId : integer; const filter : string) : TObjectDataset;
procedure AddOthIncomeOutcomeDef(const newOthIncomeOutcomeDef: TOthIncomeOutcomeDef);
function GetOthIncomeOutcomeDef(const OthIncomeOutcomeDefId : Integer) : TOthIncomeOutcomeDef;
procedure UpdateOthIncomeOutcomeDef(const OthIncomeOutcomeDef: TOthIncomeOutcomeDef);
procedure DeleteOthIncomeOutcomeDef(const OthIncomeOutcomeDef: TOthIncomeOutcomeDef);
end;
IOthIncomeOutcomeDefListViewModelInterface = interface
['{F41611CA-E014-479D-AED2-BA680457CE46}']
function GetModel: IOthIncomeOutcomeDefModelInterface;
procedure SetModel(const newModel: IOthIncomeOutcomeDefModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: IOthIncomeOutcomeDefModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
IOthIncomeOutcomeDefEditViewModelInterface = interface
['{207A831F-C479-4980-BEAE-32610BF38D2C}']
function GetModel: IOthIncomeOutcomeDefModelInterface;
procedure SetModel(const newModel: IOthIncomeOutcomeDefModelInterface);
function GetProvider : IProviderInterface;
property Model: IOthIncomeOutcomeDefModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
ICompanyModelInterface = interface
['{A5D31ADE-A0B9-4168-866D-F034D01BC06A}']
function GetAllCompanies(const filter : string) : IObjectList;
function GetAllCompaniesDS(const filter : string) : TObjectDataset;
procedure AddCompany(const newCompany: TCompany);
function GetCompany(const CompanyId : Integer) : TCompany; overload;
function GetCompany(const CompanyCode : string) : TCompany; overload;
procedure UpdateCompany(const Company: TCompany);
procedure DeleteCompany(const Company: TCompany);
end;
ICompanyListViewModelInterface = interface
['{C777060E-ED62-40D4-860E-EFAA96FF3BB1}']
function GetModel: ICompanyModelInterface;
procedure SetModel(const newModel: ICompanyModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: ICompanyModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
ICompanyEditViewModelInterface = interface
['{B43B54E4-EAFC-40EA-804A-E58F55C588C9}']
function GetModel: ICompanyModelInterface;
procedure SetModel(const newModel: ICompanyModelInterface);
function GetProvider : IProviderInterface;
property Model: ICompanyModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
ILocationModelInterface = interface
['{64CD5D96-05B2-4FC1-9F57-CC0A49E70EF0}']
function GetAllLocations(const filter : string) : IObjectList;
function GetAllLocationsDS(const filter : string) : TObjectDataset;
procedure AddLocation(const newLocation: TLocation);
function GetLocation(const LocationId : Integer) : TLocation; overload;
function GetLocation(const LocationCode : string) : TLocation; overload;
procedure UpdateLocation(const Location: TLocation);
procedure DeleteLocation(const Location: TLocation);
end;
ILocationListViewModelInterface = interface
['{E15AEC96-6069-4577-AE1E-CBF62AF91B84}']
function GetModel: ILocationModelInterface;
procedure SetModel(const newModel: ILocationModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: ILocationModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
ILocationEditViewModelInterface = interface
['{401A00F9-6DCC-4D19-8B9F-DE03F9CD7E2D}']
function GetModel: ILocationModelInterface;
procedure SetModel(const newModel: ILocationModelInterface);
function GetProvider : IProviderInterface;
property Model: ILocationModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
ITitleModelInterface = interface
['{376122B3-6CF1-41AB-9F1F-54D55DCDF50F}']
function GetAllTitles(const acompanyId : Integer; const filter : string) : IObjectList;
function GetAllTitlesDS(const acompanyId : Integer; const filter : string) : TObjectDataset;
procedure AddTitle(const newTitle: TTitle);
function GetTitle(const TitleId : Integer) : TTitle;
procedure UpdateTitle(const Title: TTitle);
procedure DeleteTitle(const Title: TTitle);
end;
ITitleListViewModelInterface = interface
['{60B8BA0B-022E-404A-A5CD-7FA55B1DA7AA}']
function GetModel: ITitleModelInterface;
procedure SetModel(const newModel: ITitleModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: ITitleModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
ITitleEditViewModelInterface = interface
['{D1A13C61-D859-4E29-8E71-96B6AC4B7931}']
function GetModel: ITitleModelInterface;
procedure SetModel(const newModel: ITitleModelInterface);
function GetProvider : IProviderInterface;
property Model: ITitleModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
IDepartmentModelInterface = interface
['{C304D57C-CF4C-4516-AB4F-907E0B97B21B}']
function GetAllDepartments(const acompanyId : Integer; const filter : string) : IObjectList;
function GetAllDepartmentsDS(const acompanyId : Integer; const filter : string) : TObjectDataset;
procedure AddDepartment(const newDepartment: TDepartment);
function GetDepartment(const DepartmentId : Integer) : TDepartment; overload;
function GetDepartment(const DepartmentCode: string): TDepartment; overload;
procedure UpdateDepartment(const Department: TDepartment);
procedure DeleteDepartment(const Department: TDepartment);
end;
IDepartmentListViewModelInterface = interface
['{2FF12545-380B-4FD9-AA07-4E3C65B355C2}']
function GetModel: IDepartmentModelInterface;
procedure SetModel(const newModel: IDepartmentModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: IDepartmentModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
IDepartmentEditViewModelInterface = interface
['{FB1B517D-4FF6-4610-AD85-671D0BC6A61B}']
function GetModel: IDepartmentModelInterface;
procedure SetModel(const newModel: IDepartmentModelInterface);
function GetProvider : IProviderInterface;
property Model: IDepartmentModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
IRelationshipTypeModelInterface = interface
['{460EE780-B5F7-4D32-8B2D-A1C15753EC92}']
function GetAllRelationshipTypes(const filter : string) : IObjectList;
function GetAllRelationshipTypesDS(const filter : string) : TObjectDataset;
procedure AddRelationshipType(const newRelationshipType: TRelationshipType);
function GetRelationshipType(const RelationshipTypeId : Integer) : TRelationshipType;
procedure UpdateRelationshipType(const RelationshipType: TRelationshipType);
procedure DeleteRelationshipType(const RelationshipType: TRelationshipType);
end;
IRelationshipTypeListViewModelInterface = interface
['{FD5F718F-9DFA-4DE9-86FE-E0C62248D6BC}']
function GetModel: IRelationshipTypeModelInterface;
procedure SetModel(const newModel: IRelationshipTypeModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: IRelationshipTypeModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
IRelationshipTypeEditViewModelInterface = interface
['{A2CFFB0A-07C4-4944-A698-8C6C2D211DAF}']
function GetModel: IRelationshipTypeModelInterface;
procedure SetModel(const newModel: IRelationshipTypeModelInterface);
function GetProvider : IProviderInterface;
property Model: IRelationshipTypeModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
IBankModelInterface = interface
['{6FD7F66E-6E58-4FF5-84A3-5C0064268125}']
function GetAllBanks(const filter : string) : IObjectList;
function GetAllBanksDS(const filter : string) : TObjectDataset;
procedure AddBank(const newBank: TBank);
function GetBank(const BankId : Integer) : TBank; overload;
function GetBank(const BankCode : string) : TBank; overload;
procedure UpdateBank(const Bank: TBank);
procedure DeleteBank(const Bank: TBank);
end;
IBankListViewModelInterface = interface
['{F7802BB9-5005-4897-AFAB-392480C69B98}']
function GetModel: IBankModelInterface;
procedure SetModel(const newModel: IBankModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: IBankModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
IBankEditViewModelInterface = interface
['{F1A3BE58-4BCD-45B0-90D9-AE375321E9E9}']
function GetModel: IBankModelInterface;
procedure SetModel(const newModel: IBankModelInterface);
function GetProvider : IProviderInterface;
property Model: IBankModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
ICurrencyModelInterface = interface
['{4E132C82-C3AD-4D78-B1C2-3D8FC2BBD5D6}']
function GetAllCurrencies(const filter : string) : IObjectList;
function GetAllCurrenciesDS(const filter : string) : TObjectDataset;
procedure AddCurrency(const newCurrency: TCurrency);
function GetCurrency(const CurrencyId : Integer) : TCurrency;
procedure UpdateCurrency(const Currency: TCurrency);
procedure DeleteCurrency(const Currency: TCurrency);
end;
ICurrencyListViewModelInterface = interface
['{A2FBFC78-C6BF-4093-9BDA-64BAB1D98A86}']
function GetModel: ICurrencyModelInterface;
procedure SetModel(const newModel: ICurrencyModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: ICurrencyModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
ICurrencyEditViewModelInterface = interface
['{949E1A53-7A98-4667-96B0-2AFE0223B3DD}']
function GetModel: ICurrencyModelInterface;
procedure SetModel(const newModel: ICurrencyModelInterface);
function GetProvider : IProviderInterface;
property Model: ICurrencyModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
IPermissionModelInterface = interface
['{99622143-D36B-40DB-835E-AFB20B4CCE41}']
function GetAllPermissions(const filter : string) : IObjectList;
function GetAllPermissionsDS(const filter : string) : TObjectDataset;
procedure AddPermission(const newPermission: TPermission);
function GetPermission(const PermissionId : Integer) : TPermission;
procedure UpdatePermission(const Permission: TPermission);
procedure DeletePermission(const Permission: TPermission);
end;
IPermissionListViewModelInterface = interface
['{9FA185BC-BA0B-4A3C-B8EE-B73E5A63B0E1}']
function GetModel: IPermissionModelInterface;
procedure SetModel(const newModel: IPermissionModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: IPermissionModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
IPermissionEditViewModelInterface = interface
['{5B8A48EA-1FA3-4427-B636-00097F41D9F7}']
function GetModel: IPermissionModelInterface;
procedure SetModel(const newModel: IPermissionModelInterface);
function GetProvider : IProviderInterface;
property Model: IPermissionModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
IUserModelInterface = interface
['{75D0324E-5F52-486E-8704-1432F8B993F3}']
function GetAllUsers(const acompanyId : Integer; const filter : string) : IObjectList;
function GetAllUsersDS(const acompanyId : Integer; const filter : string) : TObjectDataset;
procedure AddUser(const newUser: TUser);
function GetUser(const UserId : Integer) : TUser;
procedure UpdateUser(const User: TUser);
procedure DeleteUser(const User: TUser);
end;
IUserListViewModelInterface = interface
['{97E22A43-463B-4BD3-AF35-775A57661D71}']
function GetModel: IUserModelInterface;
procedure SetModel(const newModel: IUserModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: IUserModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
IUserEditViewModelInterface = interface
['{14B90C7C-9CDF-4E0B-8A52-2E96C7627266}']
function GetModel: IUserModelInterface;
procedure SetModel(const newModel: IUserModelInterface);
function GetProvider : IProviderInterface;
property Model: IUserModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
IGroupModelInterface = interface
['{D13C093A-6678-4D0E-A8C4-2D163897A78D}']
function GetAllGroups(const acompanyId : Integer; const filter : string) : IObjectList;
function GetAllGroupsDS(const acompanyId : Integer; const filter : string) : TObjectDataset;
procedure AddGroup(const newGroup: TGroup);
function GetGroup(const GroupId : Integer) : TGroup;
procedure UpdateGroup(const Group: TGroup);
procedure DeleteGroup(const Group: TGroup);
end;
IGroupListViewModelInterface = interface
['{C6D5D9B0-A848-45C5-BFC2-CB5D9FC85458}']
function GetModel: IGroupModelInterface;
procedure SetModel(const newModel: IGroupModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: IGroupModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
IGroupEditViewModelInterface = interface
['{FF602366-38C1-4C01-A2A9-F8669ED4182C}']
function GetModel: IGroupModelInterface;
procedure SetModel(const newModel: IGroupModelInterface);
function GetProvider : IProviderInterface;
property Model: IGroupModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
IRoleModelInterface = interface
['{B2EA635D-B9C2-421E-99F2-4BEAE6A756CC}']
function GetAllRoles(const acompanyId : Integer; const filter : string) : IObjectList;
function GetAllRolesDS(const acompanyId : Integer; const filter : string) : TObjectDataset;
procedure AddRole(const newRole: TRole);
function GetRole(const RoleId : Integer) : TRole;
procedure UpdateRole(const Role: TRole);
procedure DeleteRole(const Role: TRole);
end;
IRoleListViewModelInterface = interface
['{F577CBA5-E9E7-4F43-B329-98DAB11379E3}']
function GetModel: IRoleModelInterface;
procedure SetModel(const newModel: IRoleModelInterface);
function GetProvider : IProviderInterface;
function GetSubscriberToEdit : ISubscriberInterface;
property Model: IRoleModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
property SubscriberToEdit : ISubscriberInterface read GetSubscriberToEdit;
end;
IRoleEditViewModelInterface = interface
['{E40E3EC2-4173-4703-B60D-4221DAA0DFFA}']
function GetModel: IRoleModelInterface;
procedure SetModel(const newModel: IRoleModelInterface);
function GetProvider : IProviderInterface;
property Model: IRoleModelInterface read GetModel write SetModel;
property Provider : IProviderInterface read GetProvider;
end;
IGroupUserModelInterface = interface
['{74FF89DE-D808-439C-A184-59DE41F5AF0D}']
function GetGroupsOfAUser(const aUserId : Integer; const filter : string) : IObjectList;
function GetUsersOfAGroup(const aGroupId : Integer; const filter : string) : IObjectList;
function GetGroupsOfAUserDS(const aUserId : Integer; const filter : string) : TObjectDataset;
function GetUsersOfAGroupDS(const aGroupId : Integer; const filter : string) : TObjectDataset;
function UpdateGroupUserList(aUserId, aGroupId : Integer; aGUDS : TDataset) : Boolean;
//AGUList : IList<TGroupUser>) : boolean;
function GetDifference(const SourcePrefix: string; SourceDS : TDataset;
const TargetPrefix: string; TargetDS : TDataset) : boolean;
end;
IRoleUserGroupModelInterface = interface
['{A7D60EE6-EDD1-4602-BA31-9201971C5AF4}']
function GetRolesOfAUser(const aUserId : Integer; const aCriterion : ICriterion) : IObjectList;
function GetRolesOfAGroup(const aGroupId : Integer; const aCriterion : ICriterion) : IObjectList;
function GetGroupsOfARole(const aRoleId : Integer; const aCriterion : ICriterion) : IObjectList;
function GetUsersOfARole(const aRoleId : Integer; const aCriterion : ICriterion) : IObjectList;
function GetRolesOfAUserDS(const aUserId : Integer; const aCriterion : ICriterion) : TObjectDataset;
function GetRolesOfAGroupDS(const aGroupId : Integer; const aCriterion : ICriterion) : TObjectDataset;
function GetGroupsOfARoleDS(const aRoleId : Integer; const aCriterion : ICriterion) : TObjectDataset;
function GetUsersOfARoleDS(const aRoleId : Integer; const aCriterion : ICriterion) : TObjectDataset;
function UpdateRoleUserGroupList(aRoleId, aUserId, aGroupId : Integer; ARUGList : IList<TRoleUserGroup>) : boolean;
function GetDifference(const SourcePrefix: string; SourceDS : TDataset;
const TargetPrefix: string; TargetDS : TDataset) : boolean;
end;
IRoleUserGroupPermissionModelInterface = interface
['{5DF6306F-7A6D-48FD-A3FD-D94F42407F89}']
function GetPermissionsOfAUser(const aUserId : Integer) : IObjectList;
function GetPermissionsOfAGroup(const aGroupId : Integer) : IObjectList;
function GetPermissionsOfARole(const aRoleId : Integer) : IObjectList;
function GetGroupsOfAPermission(const aPermissionId : Integer) : IObjectList;
function GetUsersOfAPermission(const aPermissionId : Integer) : IObjectList;
function GetRolesOfAPermission(const aPermissionId : Integer) : IObjectList;
function GetPermissionsOfAUserDS(const aUserId : Integer) : TObjectDataset;
function GetPermissionsOfAGroupDS(const aGroupId : Integer) : TObjectDataset;
function GetPermissionsOfARoleDS(const aRoleId : Integer) : TObjectDataset;
function GetGroupsOfAPermissionDS(const aPermissionId : Integer) : TObjectDataset;
function GetUsersOfAPermissionDS(const aPermissionId : Integer) : TObjectDataset;
function GetRolesOfAPermissionDS(const aPermissionId : Integer) : TObjectDataset;
function UpdateRoleUserGroupList(aRoleId, aUserId, aGroupId, aPermissionId : Integer; ARUGPList : IList<TRoleUserGroupPermission>) : boolean;
function GetDifference(const SourcePrefix: string; SourceDS : TDataset;
const TargetPrefix: string; TargetDS : TDataset) : boolean;
end;
implementation
end.
|
unit fmComentario;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, fmBase, StdCtrls, DBCtrls, ComCtrls, dmComentario,
richEditReadOnly, dmLector, ActnList, XPStyleActnCtrls,
ActnMan, ExtCtrls, JvComponentBase,
JvFormPlacement, TB2Item, SpTBXItem, TB2Dock, TB2Toolbar;
const
WM_AFTER_RESIZE = WM_USER + 1;
type
TfComentario = class(TfBase)
Comentario: TRichEditReadOnly;
Panel1: TPanel;
ActionManagerVoz: TActionManager;
VozReproducir: TAction;
VozPausa: TAction;
VozParar: TAction;
ToolbarVoz: TSpTBXToolbar;
TBXItem120: TSpTBXItem;
TBXItem119: TSpTBXItem;
TBXItem118: TSpTBXItem;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure VozReproducirExecute(Sender: TObject);
procedure VozPausaExecute(Sender: TObject);
procedure VozPararExecute(Sender: TObject);
private
PrimeraBaja: currency;
SegundaBaja: currency;
PrimeraAlza: currency;
SegundaAlza: currency;
dmComentario: TdComentario;
Lector: TLector;
VocesInicializadas: boolean;
procedure OnHablaFinalizada;
function comparar(valor1, valor2: currency): string;
function futurosPosibles(dinero1, dinero2, papel1, papel2: currency): string;
procedure situacionActual;
procedure futuros;
procedure observaciones;
procedure Titulo(cad: string);
procedure AfterResize(var message: TMessage); message WM_AFTER_RESIZE;
public
{ Public declarations }
end;
implementation
uses dmData, math, dmLectorImages;
{$R *.dfm}
procedure TfComentario.AfterResize(var message: TMessage);
begin
Comentario.Repaint;
end;
function TfComentario.comparar(valor1, valor2: currency): string;
begin
if (valor1 = valor2) then
result := 'repitió'
else
if (valor1 < valor2) then
result := 'subió'
else
result := 'bajó'
end;
procedure TfComentario.FormShow(Sender: TObject);
begin
inherited;
if Data.CotizacionEstadoDINERO_ALZA_SIMPLE.Value = 0 then begin
Comentario.Lines.Add('El sistema no puede comentar el gráfico porque en la' +
'sesión del día ' + Data.CotizacionFECHA.AsString + ' no se procesó.');
exit;
end;
PrimeraBaja := RoundTo(Data.CotizacionCIERRE.Value * (1-(Data.CotizacionEstadoVARIABILIDAD.Value / 100)), -2);
SegundaBaja := RoundTo(Data.CotizacionCIERRE.Value * (1-(2*Data.CotizacionEstadoVARIABILIDAD.Value / 100)), -2);
PrimeraAlza := RoundTo(Data.CotizacionCIERRE.Value * (1+ (Data.CotizacionEstadoVARIABILIDAD.Value / 100)), -2);
SegundaAlza := RoundTo(Data.CotizacionCIERRE.Value * (1+ (2*Data.CotizacionEstadoVARIABILIDAD.Value / 100)), -2);
Comentario.Paragraph.FirstIndent := 10;
Comentario.Paragraph.LeftIndent := 10;
Comentario.Paragraph.RightIndent := 10;
situacionActual;
futuros;
observaciones;
// Comentario.CaretPos := Point(0,0);
// Move to the first line:
Comentario.SelStart := Comentario.Perform(EM_LINEINDEX, 0, 0);
Comentario.Perform(EM_SCROLLCARET, 0, 0);
end;
procedure TfComentario.futuros;
var aux: string;
begin
Titulo('Futuros posibles');
Comentario.Paragraph.Numbering := nsBullet;
aux := 'Si el gráfico cayera ahora hasta el nivel ' +
CurrToStr(PrimeraBaja) +
' entonces la fuerza del dinero ';
aux := aux + futurosPosibles(Data.CotizacionEstadoDINERO_BAJA_SIMPLE.Value,
Data.CotizacionEstadoDINERO.Value, Data.CotizacionEstadoPAPEL_BAJA_SIMPLE.Value, Data.CotizacionEstadoPAPEL.Value);
aux := aux + ' (' + Data.CotizacionEstadoZONA_BAJA_SIMPLE_DESC.Value + ').';
Comentario.Lines.Add(aux);
aux := 'Si el gráfico cayera ahora hasta el nivel ' +
CurrToStr(SegundaBaja) +
' entonces la fuerza del dinero ';
aux := aux + futurosPosibles(Data.CotizacionEstadoDINERO_BAJA_DOBLE.Value,
Data.CotizacionEstadoDINERO.Value, Data.CotizacionEstadoPAPEL_BAJA_DOBLE.Value, Data.CotizacionEstadoPAPEL.Value);
aux := aux + ' (' + Data.CotizacionEstadoZONA_BAJA_DOBLE_DESC.Value + ').';
Comentario.Lines.Add(aux);
aux := 'Si el gráfico subiera ahora hasta el nivel ' +
CurrToStr(PrimeraAlza) +
' entonces la fuerza del dinero ';
aux := aux + futurosPosibles(Data.CotizacionEstadoDINERO_ALZA_SIMPLE.Value,
Data.CotizacionEstadoDINERO.Value, Data.CotizacionEstadoPAPEL_ALZA_SIMPLE.Value, Data.CotizacionEstadoPAPEL.Value);
aux := aux + ' (' + Data.CotizacionEstadoZONA_ALZA_SIMPLE_DESC.Value + ').';
Comentario.Lines.Add(aux);
aux := 'Si el gráfico subiera ahora hasta el nivel ' +
CurrToStr(SegundaAlza) +
' entonces la fuerza del dinero ';
aux := aux + futurosPosibles(Data.CotizacionEstadoDINERO_ALZA_DOBLE.Value,
Data.CotizacionEstadoDINERO.Value, Data.CotizacionEstadoPAPEL_ALZA_DOBLE.Value, Data.CotizacionEstadoPAPEL.Value);
aux := aux + ' (' + Data.CotizacionEstadoZONA_ALZA_DOBLE_DESC.Value + ').';
Comentario.Lines.Add(aux);
end;
function TfComentario.futurosPosibles(dinero1, dinero2, papel1, papel2: currency): string;
begin
result := '';
if dinero1 > dinero2 then
result := result + 'aumentaría hasta los ' + CurrToStr(dinero1) +
' grados'
else
if dinero1 < dinero2 then
result := result + 'retrocedería hasta los ' + CurrToStr(dinero1) +
' grados'
else
if dinero1 < dinero2 then
result := result + 'se mantendría en los ' + CurrToStr(dinero1) +
' grados';
result := result + ' y la fuerza del papel ';
if papel1 > papel2 then
result := result + 'aumentaría hasta los ' + CurrToStr(papel1) +
' grados'
else
if papel1 < papel2 then
result := result + 'retrocedería hasta los ' + CurrToStr(papel1) +
' grados'
else
if papel1 = papel2 then
result := result + 'se mantendría en los ' + CurrToStr(papel1) +
' grados';
end;
procedure TfComentario.observaciones;
var aux: string;
begin
Comentario.Lines.Add('');
aux := 'El máximo en intradía en la última sesión llegó hasta ' +
Data.CotizacionMAXIMO.AsString;
aux := aux + ' y el mínimo intradía se situó en el nivel ' +
Data.CotizacionMINIMO.AsString + ' inferior.';
Comentario.Lines.Add(aux);
Comentario.Lines.Add('');
aux := 'Los indicadores Dobson del gráfico actualmente ';
if (Data.CotizacionEstadoDOBSON_130.Value > Data.CotizacionEstadoDOBSON_100.Value) and
(Data.CotizacionEstadoDOBSON_100.Value > Data.CotizacionEstadoDOBSON_70.Value) and
(Data.CotizacionEstadoDOBSON_70.Value > Data.CotizacionEstadoDOBSON_40.Value) and
(Data.CotizacionEstadoDOBSON_40.Value > Data.CotizacionEstadoDOBSON_10.Value) then
aux := aux + 'están ordenados para acumulación.'
else
if (Data.CotizacionEstadoDOBSON_130.Value < Data.CotizacionEstadoDOBSON_100.Value) and
(Data.CotizacionEstadoDOBSON_100.Value < Data.CotizacionEstadoDOBSON_70.Value) and
(Data.CotizacionEstadoDOBSON_70.Value < Data.CotizacionEstadoDOBSON_40.Value) and
(Data.CotizacionEstadoDOBSON_40.Value < Data.CotizacionEstadoDOBSON_10.Value) then
aux := aux + 'están ordenados para distribución.'
else begin
aux := aux + ' no están ordenados para acumulación ni para distribución, ' +
'sólo muestran ';
if (Data.CotizacionEstadoDOBSON_130.Value = 0) and
(Data.CotizacionEstadoDOBSON_100.Value = 0) and
(Data.CotizacionEstadoDOBSON_70.Value = 0) and
(Data.CotizacionEstadoDOBSON_40.Value = 0) and
(Data.CotizacionEstadoDOBSON_10.Value = 0) then
aux := aux + 'que están todos a cero.'
else begin
aux := aux + 'la siguiente situación de las medias móviles:';
Comentario.Lines.Add(aux);
Comentario.Paragraph.Numbering := nsBullet;
aux := 'Media móvil de 130 días igual a ' + Data.CotizacionEstadoDOBSON_130.AsString;
if Data.CotizacionEstadoDOBSON_130.Value < 0 then
aux := aux + ' (rota)';
Comentario.Lines.Add(aux);
aux := 'Media móvil de 100 días igual a ' + Data.CotizacionEstadoDOBSON_100.AsString;
if Data.CotizacionEstadoDOBSON_100.Value < 0 then
aux := aux + ' (rota)';
Comentario.Lines.Add(aux);
aux := 'Media móvil de 70 días igual a ' + Data.CotizacionEstadoDOBSON_70.AsString;
if Data.CotizacionEstadoDOBSON_70.Value < 0 then
aux := aux + ' (rota)';
Comentario.Lines.Add(aux);
aux := 'Media móvil de 40 días igual a ' + Data.CotizacionEstadoDOBSON_40.AsString;
if Data.CotizacionEstadoDOBSON_40.Value < 0 then
aux := aux + ' (rota)';
Comentario.Lines.Add(aux);
aux := 'Media móvil de 10 días igual a ' + Data.CotizacionEstadoDOBSON_10.AsString;
if Data.CotizacionEstadoDOBSON_10.Value < 0 then
aux := aux + ' (rota)';
Comentario.Lines.Add(aux);
Comentario.Lines.Add('');
aux := 'Con lo cual, y desde el punto de vista de las medias móviles ' +
'se puede decir que ' + Data.ValoresNOMBRE.Value +
' (' + Data.ValoresSIMBOLO.Value + ') actualmente es ';
if Data.CotizacionEstadoDOBSON_130.Value = 0 then
aux := aux + 'neutro a largo plazo'
else
if Data.CotizacionEstadoDOBSON_130.Value > 0 then
aux := aux + 'alcista a largo plazo'
else
aux := aux + 'bajista a largo plazo';
aux := aux + ', ';
if Data.CotizacionEstadoDOBSON_70.Value = 0 then
aux := aux + 'neutro a medio plazo'
else
if Data.CotizacionEstadoDOBSON_70.Value > 0 then
aux := aux + 'alcista a medio plazo'
else
aux := aux + 'bajista a medio plazo';
aux := aux + ' y ';
if Data.CotizacionEstadoDOBSON_10.Value = 0 then
aux := aux + 'neutro a corto plazo.'
else
if Data.CotizacionEstadoDOBSON_10.Value > 0 then
aux := aux + 'alcista a corto plazo.'
else
aux := aux + 'bajista a corto plazo.';
end;
end;
Comentario.Lines.Add(aux);
Comentario.Lines.Add('');
aux := 'Además si el gráfico subiera hasta el nivel ' + CurrToStr(SegundaAlza) +
' los indicadores de Dobson ';
if (Data.CotizacionEstadoDOBSON_ALTO_130.Value > Data.CotizacionEstadoDOBSON_ALTO_100.Value) and
(Data.CotizacionEstadoDOBSON_ALTO_100.Value > Data.CotizacionEstadoDOBSON_ALTO_70.Value) and
(Data.CotizacionEstadoDOBSON_ALTO_70.Value > Data.CotizacionEstadoDOBSON_ALTO_40.Value) and
(Data.CotizacionEstadoDOBSON_ALTO_40.Value > Data.CotizacionEstadoDOBSON_ALTO_10.Value) then
aux := aux + 'están ordenados para acumulación.'
else
if (Data.CotizacionEstadoDOBSON_ALTO_130.Value < Data.CotizacionEstadoDOBSON_ALTO_100.Value) and
(Data.CotizacionEstadoDOBSON_ALTO_100.Value < Data.CotizacionEstadoDOBSON_ALTO_70.Value) and
(Data.CotizacionEstadoDOBSON_ALTO_70.Value < Data.CotizacionEstadoDOBSON_ALTO_40.Value) and
(Data.CotizacionEstadoDOBSON_ALTO_40.Value < Data.CotizacionEstadoDOBSON_ALTO_10.Value) then
aux := aux + 'están ordenados para distribución.'
else
aux := aux + ' no están ordenados para acumulación ni para distribución.';
aux := aux + 'Y si el gráfico bajara hasta el nivel ' + CurrToStr(SegundaBaja) +
' los indicadores de Dobson ';
if (Data.CotizacionEstadoDOBSON_BAJO_130.Value > Data.CotizacionEstadoDOBSON_BAJO_100.Value) and
(Data.CotizacionEstadoDOBSON_BAJO_100.Value > Data.CotizacionEstadoDOBSON_BAJO_70.Value) and
(Data.CotizacionEstadoDOBSON_BAJO_70.Value > Data.CotizacionEstadoDOBSON_BAJO_40.Value) and
(Data.CotizacionEstadoDOBSON_BAJO_40.Value > Data.CotizacionEstadoDOBSON_BAJO_10.Value) then
aux := aux + 'están ordenados para acumulación.'
else
if (Data.CotizacionEstadoDOBSON_BAJO_130.Value < Data.CotizacionEstadoDOBSON_BAJO_100.Value) and
(Data.CotizacionEstadoDOBSON_BAJO_100.Value < Data.CotizacionEstadoDOBSON_BAJO_70.Value) and
(Data.CotizacionEstadoDOBSON_BAJO_70.Value < Data.CotizacionEstadoDOBSON_BAJO_40.Value) and
(Data.CotizacionEstadoDOBSON_BAJO_40.Value < Data.CotizacionEstadoDOBSON_BAJO_10.Value) then
aux := aux + 'están ordenados para distribución.'
else
aux := aux + ' no están ordenados para acumulación ni para distribución.';
Comentario.Lines.Add(aux);
Comentario.Lines.Add('');
aux := 'Observamos también que ';
if Data.CotizacionEstadoVARIABILIDAD.Value = Data.CotizacionEstadoVOLATILIDAD.Value then
aux := aux + 'la volatilidad coincide con la variabilidad.'
else
if Data.CotizacionEstadoVARIABILIDAD.Value > Data.CotizacionEstadoVOLATILIDAD.Value then
aux := aux + 'la volatilidad es menor que la variabilidad.'
else
if Data.CotizacionEstadoVARIABILIDAD.Value < Data.CotizacionEstadoVOLATILIDAD.Value then begin
aux := aux + 'la volatilidad supera ahora la variabilidad';
if (Data.CotizacionEstadoVOLATILIDAD.Value / Data.CotizacionEstadoVARIABILIDAD.Value) > 2.5 then
aux := aux + ' y la proporción es tal que indica un próximo cambio ' +
'en la dirección del valor.'
else
aux := aux + '.';
end;
Comentario.Lines.Add(aux);
Comentario.Lines.Add('');
aux := 'Por otra parte el RSI corto a 14 dias es igual a ' +
Data.CotizacionEstadoRSI_14.AsString + ' y por tanto ';
if (Data.CotizacionEstadoRSI_14.Value = 69) or (Data.CotizacionEstadoRSI_14.Value = 70) then
aux := aux + 'si sube un poco más entrará en sobrecomprado'
else
if Data.CotizacionEstadoRSI_14.Value > 70 then
aux := aux + 'se encuentra en sobrecomprado'
else
if Data.CotizacionEstadoRSI_14.Value < 30 then
aux := aux + 'se encuentra en sobrevendido'
else
if (Data.CotizacionEstadoRSI_14.Value = 31) or (Data.CotizacionEstadoRSI_14.Value = 30) then
aux := aux + 'si baja un poco más entrará en sobrevendido'
else
if (Data.CotizacionEstadoRSI_14.Value > 31) and (Data.CotizacionEstadoRSI_14.Value < 69) then
aux := aux + 'se encuentra dentro de su zona neutra';
aux := aux + ' y el RSI largo a 140 dias vale actualmente ' +
Data.CotizacionEstadoRSI_140.AsString + ' lo cual significa que está ';
if Data.CotizacionEstadoRSI_140.Value = 50 then
aux := aux + 'equilibrado.'
else
if Data.CotizacionEstadoRSI_140.Value < 50 then
aux := aux + 'drenado o desequilibrado a la baja.'
else
aux := aux + 'hinchado o desequilibrado al alza.';
Comentario.Lines.Add(aux);
Comentario.Lines.Add('');
aux := 'Vemos también que la banda de Bollinger alta se encuentra situada ' +
'ahora en el nivel ' + Data.CotizacionEstadoBANDA_ALTA.AsString +
' y la banda baja en el nivel ' + Data.CotizacionEstadoBANDA_BAJA.AsString;
if SegundaBaja < Data.CotizacionEstadoBANDA_BAJA.Value then begin
aux := aux + ' y por tanto si el gráfico cae mañana hasta el nivel ';
aux := aux + CurrToStr(SegundaBaja) + ' la caída será altamente significativa';
end;
Comentario.Lines.Add(aux + '.');
end;
procedure TfComentario.OnHablaFinalizada;
begin
VozPausa.Enabled := false;
VozParar.Enabled := false;
VozReproducir.Enabled := true;
end;
procedure TfComentario.situacionActual;
var aux: string;
cambios: TCambios;
begin
cambios := dmComentario.getCambiosAnteriores(5);
Titulo('Situación actual');
Comentario.Lines.Add('El gráfico cerró el día ' + Data.CotizacionFECHA.AsString +
' a ' + Data.CotizacionCIERRE.AsString + ' y en este nivel del gráfico ' +
'la fuerza del dinero es de ' + Data.CotizacionEstadoDINERO.AsString + ' grados y ' +
'la fuerza del papel es de ' + Data.CotizacionEstadoPAPEL.AsString + ' grados (' +
Data.CotizacionEstadoZONA_DESC.Value + ').');
Comentario.Lines.Add('');
aux := 'Comparando estos datos con los de la sesión anterior ' +
'se observa lo siguiente: El gráfico ha ';
if cambios[0] = Data.CotizacionCIERRE.Value then
aux := 'repetido'
else begin
if cambios[0] < Data.CotizacionCIERRE.Value then
aux := aux + 'subido'
else
if cambios[0] > Data.CotizacionCIERRE.Value then
aux := aux + 'bajado';
aux := aux + ' ya que ha pasado de ' + CurrToStr(cambios[0]) + ' a ' +
Data.CotizacionCIERRE.AsString;
end;
dmComentario.Open(dmComentario.getOIDCotizacionDiaAnterior);
aux := aux + ' y en cuanto a los grados del dinero y los del papel se observa ' +
'que la fuerza del dinero ';
if Data.CotizacionEstadoDINERO.Value > dmComentario.EstadoAyerDINERO.Value then
aux := aux + 'aumenta ya que pasa de los ' + dmComentario.EstadoAyerDINERO.AsString +
' grados que tenía en la sesión anterior a los ' + Data.CotizacionEstadoDINERO.AsString +
' grados de la sesión actual'
else
if Data.CotizacionEstadoDINERO.Value < dmComentario.EstadoAyerDINERO.Value then
aux := aux + 'desciende ya que pasa de los ' + dmComentario.EstadoAyerDINERO.AsString +
' grados que tenía en la sesión anterior a los ' + Data.CotizacionEstadoDINERO.AsString +
' grados de la sesión actual'
else
aux := aux + 'se mantiene fijo en los ' + Data.CotizacionEstadoDINERO.AsString +
' grados';
aux := aux + ' y la fuerza del papel ';
if Data.CotizacionEstadoPAPEL.Value > dmComentario.EstadoAyerPAPEL.Value then
aux := aux + 'aumenta ya que pasa de los ' + dmComentario.EstadoAyerPAPEL.AsString +
' grados que tenía en la sesión anterior a los ' + Data.CotizacionEstadoPAPEL.AsString +
' grados de la sesión actual.'
else
if Data.CotizacionEstadoPAPEL.Value < dmComentario.EstadoAyerPAPEL.Value then
aux := aux + 'desciende ya que pasa de los ' + dmComentario.EstadoAyerPAPEL.AsString +
' grados que tenía en la sesión anterior a los ' + Data.CotizacionEstadoPAPEL.AsString +
' grados de la sesión actual.'
else
aux := aux + 'se mantiene fijo en los ' + Data.CotizacionEstadoPAPEL.AsString + ' grados.';
Comentario.Lines.Add(aux);
Comentario.Lines.Add('');
aux := 'Si ahora examinamos los cambios de las cuatro últimas sesiones observamos que ' +
'su evolución ha sido ';
if (cambios[3] < cambios[2]) and (cambios[2] < cambios[1]) and
(cambios[1] < cambios[0]) and (cambios[0] < Data.CotizacionCIERRE.Value) then
aux := aux + 'alcista ya que en todas ellas los cambios han subido y por tanto ' +
'una corrección a cortísimo plazo es más que probable (Regla de las siete sesiones).'
else
if (cambios[3] > cambios[2]) and (cambios[2] > cambios[1]) and
(cambios[1] > cambios[0]) and (cambios[0] > Data.CotizacionCIERRE.Value) then
aux := aux + 'bajista ya que en todas ellas los cambios han bajado y por tanto ' +
'una correción a cortísimo plazo es más que probable (Regla de las siete sesiones).'
else begin
aux := aux + 'la siguente: Hace cuatro sesiones ';
aux := aux + comparar(cambios[3], cambios[2]) + ' a ';
aux := aux + CurrToStr(cambios[2]) + ', hace tres sesiones ';
aux := aux + comparar(cambios[2], cambios[1]) + ' a ';
aux := aux + CurrToStr(cambios[1]) + ', dos sesiones atrás ';
aux := aux + comparar(cambios[1], cambios[0]) + ' a ';
aux := aux + CurrToStr(cambios[0]) + ' y finalmente en la sesión última ' +
'que estamos comentando, el cambio ha ';
aux := aux + comparar(cambios[0], Data.CotizacionCIERRE.Value) + ' a ';
aux := aux + Data.CotizacionCIERRE.AsString;
aux := aux + ' tal como se ha dicho anteriormente.';
end;
Comentario.Lines.Add(aux);
end;
procedure TfComentario.FormCreate(Sender: TObject);
begin
inherited;
dmComentario := TdComentario.Create(Self);
Lector := TLector.Create(Self);
TLectorImages.Create(Self);
VocesInicializadas := false;
end;
procedure TfComentario.FormResize(Sender: TObject);
begin
inherited;
PostMessage(Handle, WM_AFTER_RESIZE, 0, 0);
end;
procedure TfComentario.Titulo(cad: string);
begin
Comentario.Lines.Add('');
Comentario.SelAttributes.Color := clBlue;
Comentario.SelAttributes.Height := 16;
Comentario.Lines.Add(cad);
Comentario.SelAttributes.Color := clBlack;
end;
procedure TfComentario.VozPararExecute(Sender: TObject);
begin
inherited;
Lector.ParaDeHablar;
VozPausa.Enabled := false;
VozParar.Enabled := false;
VozReproducir.Enabled := true;
end;
procedure TfComentario.VozPausaExecute(Sender: TObject);
begin
inherited;
VozParar.Enabled := not VozParar.Enabled;
Lector.Pausa;
end;
procedure TfComentario.VozReproducirExecute(Sender: TObject);
begin
inherited;
if VocesInicializadas then begin
VozPausa.Enabled := true;
VozParar.Enabled := true;
VozReproducir.Enabled := false;
Lector.Habla(Comentario.Text);
end
else begin
try
// No se puede poner el InitializeVoices en el constructor del TLectorFP
// porque si tira una excepción esta no se porque no se coge en el except
Lector.InitializeVoices;
Lector.OnHablaFinalizada := OnHablaFinalizada;
VocesInicializadas := true;
VozReproducirExecute(Sender);
except
Lector.MostrarErrorVoz;
end;
end;
end;
end.
|
unit MainCode;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,math ;
type
TForm1 = class(TForm)
Edit1: TEdit;
Label1: TLabel;
Button1: TButton;
Button2: TButton;
Edit2: TEdit;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
//hex Convert To Integer
function HexToInt(HexStr : string) : Int64;
var RetVar : Int64;
i : byte;
begin
HexStr := UpperCase(HexStr);
if HexStr[length(HexStr)] = 'H' then
Delete(HexStr,length(HexStr),1);
RetVar := 0;
for i := 1 to length(HexStr) do begin
RetVar := RetVar shl 4;
if HexStr[i] in ['0'..'9'] then
RetVar := RetVar + (byte(HexStr[i]) - 48)
else
if HexStr[i] in ['A'..'F'] then
RetVar := RetVar + (byte(HexStr[i]) - 55)
else begin
Retvar := 0;
break;
end;
end;
Result := RetVar;
end;
function IEEE754DToF(const AData: DWORD): Single; //iEEE 754 convert FlaotValue / 32bit
var
S, M, E: Integer;
begin
try
S:= (AData and $80000000) shr 31;
E:= (AData and $7F800000) shr 23;
M:= AData and $7FFFFF;
Result:= Power(-1, S) * (1 + M/$7FFFFF) * Power(2, E-127);
except
Result:=0;
end;
end;
function IEEE75464DToF(const AData: UInt64): Double; //iEEE 754 convert FlaotValue / 64 bit
var
S, M, E: UInt64;
begin
try
S:= (AData and $8000000000000000) shr 63;
E:= (AData and $7FF0000000000000) shr 52;
M:= AData and $FFFFFFFFFFFFF;
Result:= Power(-1, S) * (1 + M/$FFFFFFFFFFFFF) * Power(2, E-1023);
except
Result:=0;
end;
end;
//---
procedure TForm1.FormCreate(Sender: TObject);
begin
self.Edit1.Clear;
self.Edit2.Clear;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
self.Edit1.Text := '3FA001E6'
end;
procedure TForm1.Button1Click(Sender: TObject);
var
FloSingle : double;
myDord : DWORD;
begin
if edit1.Text = '' then
begin
showmessage('Hex Code is empty');
self.Button2Click(Button2);
end
else
begin
myDord := HEXTOINT(edit1.Text); // hex String Convert To decimal (Integer)
FloSingle := IEEE754DToF(myDord); // Ieee754 Convert Flaot
// FloSingle := IEEE754DToF('$3FA001E6'); // Ieee754 Convert Flaot
edit2.Text := FloatToStr(FloSingle)
end;
end;
end.
|
//***************************************************************************
//
// ShortLink.pas
// 工具:RAD Studio XE6
// 日期:2015/01/29 15:51:21
// 作者:ying32
// QQ :396506155
// MSN :ying_32@live.cn
// E-mail:yuanfen3287@vip.qq.com
// Website:http://www.ying32.com
//
//---------------------------------------------------------------------------
//
// 备注: 快捷方式创建
//
//
//***************************************************************************
unit ShortLink;
interface
uses
Winapi.Windows,
Winapi.ShlObj,
Winapi.ActiveX,
System.Win.ComObj,
System.SysUtils;
function CreateDesktopLink(ANameStr, ExeFileName, ADescription, AArgs: string): Boolean;
implementation
function CreateDesktopLink(ANameStr, ExeFileName, ADescription, AArgs: string): Boolean;
var
tmpObject : IUnknown;
tmpSLink : IShellLink;
tmpPFile : IPersistFile;
PIDL : PItemIDList;
StartupDirectory : array[0..MAX_PATH] of Char;
StartupFilename : String;
LinkFilename : WideString;
begin
Result := False;
CoInitializeEx(nil, 0);
try
StartupFilename := ExeFileName;
tmpObject := CreateComObject(CLSID_ShellLink);
tmpSLink := tmpObject as IShellLink;
tmpPFile := tmpObject as IPersistFile;
tmpSLink.SetPath(PWideChar(StartupFilename));
tmpSLink.SetWorkingDirectory(pChar(ExtractFilePath(StartupFilename)));
SHGetSpecialFolderLocation(0,CSIDL_DESKTOPDIRECTORY,PIDL);
tmpSLink.SetDescription(PWideChar(ADescription));
tmpSLink.SetIconLocation(PWideChar(StartupFilename), 0);
tmpSLink.SetArguments(PChar(AArgs));
SHGetPathFromIDList(PIDL,StartupDirectory);
LinkFilename := WideString(string(StartupDirectory) + '\' + ANameStr + '.lnk');
Result := tmpPFile.Save(PWideChar(LinkFilename), FALSE) = S_OK;
finally
CoUninitialize;
end;
end;
end.
|
unit ITFReader;
{
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* Implemented by E. Spelt for Delphi
}
interface
uses
SysUtils, Generics.Collections, Math, OneDReader, BitArray, ReadResult,
DecodeHintType, ResultPoint, BarcodeFormat;
type
TArrInt = TArray<Integer>;
TMultiIntegerArray = TArray<TArrInt>;
type
TITFReader = class(TOneDReader)
const
LARGEST_DEFAULT_ALLOWED_LENGTH = 14;
N = 1;
W = 3;
private
PATTERNS: TMultiIntegerArray;
END_PATTERN_REVERSED: TArray<Integer>;
MAX_AVG_VARIANCE: Integer;
MAX_INDIVIDUAL_VARIANCE: Integer;
DEFAULT_ALLOWED_LENGTHS: TArray<Integer>;
START_PATTERN: TArray<Integer>;
narrowLineWidth: Integer;
function decodeDigit(counters: TArray<Integer>;
out bestMatch: Integer): boolean;
function decodeEnd(row: TBitArray): TArray<Integer>;
function skipWhiteSpace(row: TBitArray): Integer;
function findGuardPattern(row: TBitArray; rowOffset: Integer;
pattern: TArray<Integer>): TArray<Integer>;
function validateQuietZone(row: TBitArray; startPattern: Integer): boolean;
function decodeStart(row: TBitArray): TArray<Integer>;
function decodeMiddle(row: TBitArray; payloadStart: Integer;
payloadEnd: Integer; out resultString: TReadResult): boolean;
public
constructor Create;
function DecodeRow(rowNumber: Integer; row: TBitArray;
hints: TDictionary<TDecodeHintType, TObject>): TReadResult; override;
end;
implementation
uses
MathUtils;
{ TITFReader }
constructor TITFReader.Create;
begin
inherited;
narrowLineWidth := -1;
MAX_AVG_VARIANCE :=
Floor(TOneDReader.PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42);
MAX_INDIVIDUAL_VARIANCE :=
Floor(TOneDReader.PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.78);
END_PATTERN_REVERSED := [1, 1, 3];
DEFAULT_ALLOWED_LENGTHS := [6, 8, 10, 12, 14];
START_PATTERN := [1, 1, 1, 1];
PATTERNS := [[1, 1, 3, 3, 1], [3, 1, 1, 1, 3], [1, 3, 1, 1, 3],
[3, 3, 1, 1, 1], [1, 1, 3, 1, 3], [3, 1, 3, 1, 1], [1, 3, 3, 1, 1],
[1, 1, 1, 3, 3], [3, 1, 1, 3, 1], [1, 3, 1, 3, 1]];
end;
function TITFReader.decodeDigit(counters: TArray<Integer>;
out bestMatch: Integer): boolean;
var
bestVariance: Integer;
max: Integer;
i: Integer;
pattern: TArrInt;
variance: Integer;
begin
bestVariance := MAX_AVG_VARIANCE;
bestMatch := -1;
max := Length(PATTERNS);
i := 0;
while ((i < max)) do
begin
pattern := PATTERNS[i];
variance := TOneDReader.patternMatchVariance(counters, pattern,
MAX_INDIVIDUAL_VARIANCE);
if (variance < bestVariance) then
begin
bestVariance := variance;
bestMatch := i
end;
inc(i)
end;
Result := (bestMatch >= 0);
end;
function TITFReader.decodeEnd(row: TBitArray): TArray<Integer>;
var
endStart: Integer;
endPattern: TArray<Integer>;
temp: Integer;
begin
row.reverse;
endStart := skipWhiteSpace(row);
if (endStart < 0) then
begin
Exit(nil);
end;
endPattern := findGuardPattern(row, endStart, END_PATTERN_REVERSED);
if (endPattern = nil) then
begin
row.reverse;
begin
Exit(nil);
end
end;
if (not self.validateQuietZone(row, endPattern[0])) then
begin
row.reverse;
begin
Exit(nil);
end
end;
temp := endPattern[0];
endPattern[0] := (row.Size - endPattern[1]);
endPattern[1] := (row.Size - temp);
row.reverse;
Result := endPattern;
end;
function TITFReader.decodeMiddle(row: TBitArray;
payloadStart, payloadEnd: Integer; out resultString: TReadResult): boolean;
var
bestMatch: Integer;
counterDigit: Integer;
counterDigitPair: TArray<Integer>;
counterBlack: TArray<Integer>;
counterWhite: TArray<Integer>;
k: Integer;
twoK: Integer;
aString: string;
begin
SetLength(counterDigitPair, 10);
SetLength(counterBlack, 5);
SetLength(counterWhite, 5);
aString := '';
while ((payloadStart < payloadEnd)) do
begin
if (not TOneDReader.recordPattern(row, payloadStart, counterDigitPair)) then
begin
Exit(false);
end;
k := 0;
while ((k < 5)) do
begin
twoK := (k shl 1);
counterBlack[k] := counterDigitPair[twoK];
counterWhite[k] := counterDigitPair[(twoK + 1)];
inc(k)
end;
if (not decodeDigit(counterBlack, bestMatch)) then // @(bestMatch))) then
begin
Exit(false);
end;
aString := aString + IntToStr(bestMatch); // ((($30 + bestMatch) as Char));
if (not decodeDigit(counterWhite, bestMatch)) then // @(bestMatch))) then
begin
Exit(false);
end;
aString := aString + IntToStr(bestMatch); // ((($30 + bestMatch) as Char));
for counterDigit in counterDigitPair do
begin
inc(payloadStart, counterDigit);
end
end;
Result := true;
resultString := TReadResult.Create(aString, nil, nil, TBarcodeFormat.ITF);
end;
function TITFReader.DecodeRow(rowNumber: Integer; row: TBitArray;
hints: TDictionary<TDecodeHintType, TObject>): TReadResult;
var
allowedLength: Integer;
startRange: TArray<Integer>;
endRange: TArray<Integer>;
aResult: string;
allowedLengths: TArray<Integer>;
maxAllowedLength: Integer;
ilength: Integer;
lengthOK: boolean;
begin
startRange := decodeStart(row);
if (startRange = nil) then
begin
Exit(nil);
end;
endRange := self.decodeEnd(row);
if (endRange = nil) then
begin
Exit(nil);
end;
// result := StringBuilder.Create(20);
if (not decodeMiddle(row, startRange[1], endRange[0], Result)) then
begin
Exit(nil);
end;
aResult := Result.Text;
allowedLengths := nil;
maxAllowedLength := 14;
if ((hints <> nil) and hints.ContainsKey(DecodeHintType.ALLOWED_LENGTHS)) then
begin
allowedLengths := TArrInt(hints[DecodeHintType.ALLOWED_LENGTHS]);
maxAllowedLength := 0
end;
if (allowedLengths = nil) then
begin
allowedLengths := DEFAULT_ALLOWED_LENGTHS;
maxAllowedLength := 14
end;
ilength := Length(aResult);
lengthOK := (ilength > 14);
if (not lengthOK) then
begin
for allowedLength in allowedLengths do
begin
if (ilength = allowedLength) then
begin
lengthOK := true;
break;
end;
if (allowedLength > maxAllowedLength) then
begin
maxAllowedLength := allowedLength;
end;
end;
if (not lengthOK and (ilength > maxAllowedLength)) then
begin
lengthOK := true;
end;
if (not lengthOK) then
begin
Exit(nil);
end
end;
{
resultPointCallback := (if ((hints = nil) or not hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK)) then nil else (hints.Item[DecodeHintType.NEED_RESULT_POINT_CALLBACK] as ResultPointCallback));
if (resultPointCallback <> nil) then
begin
resultPointCallback.Invoke(ResultPoint.Create((startRange[1] as Single), (rowNumber as Single)));
resultPointCallback.Invoke(ResultPoint.Create((endRange[0] as Single), (rowNumber as Single)))
end;
begin
Result := Result.Create(resultString, nil, New(array[2] of ResultPoint, ( ( ResultPoint.Create((startRange[1] as Single), (rowNumber as Single)), ResultPoint.Create((endRange[0] as Single), (rowNumber as Single)) ) )), BarcodeFormat.ITF);
exit
end }
Result := TReadResult.Create(aResult, nil,
// New(array[2] of ResultPoint, ( ( ResultPoint.Create((startRange[1] as Single), (rowNumber as Single)), ResultPoint.Create((endRange[0] as Single), (rowNumber as Single)) ) )),
nil, BarcodeFormat.ITF);
end;
function TITFReader.decodeStart(row: TBitArray): TArray<Integer>;
var
endStart: Integer;
startPattern: TArray<Integer>;
begin
endStart := skipWhiteSpace(row);
if (endStart < 0) then
begin
Exit(nil);
end;
startPattern := findGuardPattern(row, endStart, START_PATTERN);
if (startPattern = nil) then
begin
Exit(nil);
end;
narrowLineWidth := TMathUtils.Asr(startPattern[1] - startPattern[0], 2);
// narrowLineWidth := ((startPattern[1] - startPattern[0]) shr 2);
if (not self.validateQuietZone(row, startPattern[0])) then
begin
Exit(nil);
end;
Result := startPattern;
end;
function TITFReader.findGuardPattern(row: TBitArray; rowOffset: Integer;
pattern: TArray<Integer>): TArray<Integer>;
var
patternLength: Integer;
counters: TArray<Integer>;
width: Integer;
isWhite: boolean;
counterPosition: Integer;
patternStart: Integer;
x: Integer;
l: Integer;
begin
Result := nil;
patternLength := Length(pattern);
SetLength(counters, patternLength);
width := row.Size;
isWhite := false;
counterPosition := 0;
patternStart := rowOffset;
x := rowOffset;
while ((x < width)) do
begin
if (row[x] xor isWhite) then
begin
if (Length(counters) > counterPosition) then
inc(counters[counterPosition]);
end
else
begin
if (counterPosition = (patternLength - 1)) then
begin
if (TOneDReader.patternMatchVariance(counters, pattern,
MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) then
begin
Result := [patternStart, x];
Exit(Result);
end;
if (Length(counters) > 1) then
begin
inc(patternStart, (counters[0] + counters[1]));
end;
counters := Copy(counters, 2, (patternLength - 2));
if (Length(counters) >= patternLength - 2) then
begin
counters[(patternLength - 2)] := 0;
counters[(patternLength - 1)] := 0;
end;
dec(counterPosition);
end
else
begin
inc(counterPosition);
end;
if (Length(counters) > counterPosition) then
begin
counters[counterPosition] := 1;
end;
isWhite := not isWhite
end;
inc(x)
end;
end;
function TITFReader.skipWhiteSpace(row: TBitArray): Integer;
var
width: Integer;
endStart: Integer;
begin
width := row.Size;
endStart := row.getNextSet(0);
if (endStart = width) then
begin
Result := -1;
end
else
begin
Result := endStart;
end
end;
function TITFReader.validateQuietZone(row: TBitArray;
startPattern: Integer): boolean;
var
quietCount: Integer;
i: Integer;
begin
quietCount := (self.narrowLineWidth * 10);
if (quietCount >= startPattern) then
begin
quietCount := startPattern;
end;
i := (startPattern - 1);
while (((quietCount > 0) and (i >= 0))) do
begin
if (row[i]) then
begin
break;
end;
dec(quietCount);
dec(i)
end;
if (quietCount <> 0) then
begin
Exit(false);
end;
Result := true;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, TAGraph, TASeries, TAFuncSeries, Forms, Controls,
Graphics, Dialogs, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Chart1: TChart;
Chart1FuncSeries1: TFuncSeries;
Chart1LineSeries1: TLineSeries;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
Edit1: TEdit;
Edit2: TEdit;
Edit4: TEdit;
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
Memo1: TMemo;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
const e=0.001; //погрешность
var
Form1: TForm1;
x,a,b: double;
implementation
{$R *.lfm}
{ TForm1 }
function f1(z: double): double; {Основная функция}
begin
f1:=z-(sin(z)/cos(z));
end;
function f2(z:double): double; {Производная от основной функции}
begin
f2:=(cos(2*z)-1)/(cos(2*z)+1) ;
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
Application.Terminate
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
Edit1.Text := '';
Edit2.Text := '';
Edit4.Text := '';
Memo1.Clear;
Checkbox1.Checked := False;
Checkbox2.Checked := False;
Checkbox3.Checked := False;
Chart1lineseries1.Clear;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if SaveDialog1.Execute then
memo1.Lines.SaveToFile(SaveDialog1.FileName);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if OpenDialog1.Execute then
memo1.Lines.LoadFromFile(OpenDialog1.FileName);
end;
procedure TForm1.Button3Click(Sender: TObject);
var
a, b, u: real;
y, x, p: real;
mes, nach, konec, pou: byte;
s: string;
begin
begin
val(Edit1.Text, a, nach);
if nach <> 0 then
mes := Application.MessageBox('Введите пожалуйста значение ', '', 0)
else
begin
val(Edit2.Text, b, konec);
if konec <> 0 then
mes := Application.MessageBox('Введите пожалуйста значение', '', 0)
else
begin
val(Edit4.Text, u, pou);
if pou <> 0 then
mes := Application.MessageBox('Ошибка ввода шага !!!', '', 0)
else
begin
if a > b then
ShowMessage('Предупреждение!!! A не должно быть больше чем B')
else
if checkbox2.Checked then
begin
if f1(a)*f2(a)<0 then x:=b
else x:=a;
while abs(f1(x))<e do
begin
x:=x-f1(x)/f2(x);
//memo1.Lines.Add('sqr- ' + Floattostrf(x, fffixed, 6, 2));
s := Floattostrf(x, fffixed, 6, 2) + ' ' + Floattostrf(y, fffixed, 10, 4);
if checkbox1.Checked then
memo1.Lines.Add(s);
if checkbox3.Checked then
Chart1LineSeries1.AddXY(x, y, '', clBlack);
x := x + u;
end;
end;
end;
end;
end;
end;
end;
end.
|
unit uAbonoFaltas;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFormCadBase, ImgList, DB, ComCtrls, ToolWin, Grids, DBGrids, StdCtrls, JvExStdCtrls, JvCombobox, JvExControls, JvXPCore, JvXPButtons,
JvEdit, ConstTipos, ZAbstractRODataset, ZAbstractDataset, ZDataset, uFuncoesGeral;
type
TfrmAbonoFaltas = class(TfrmCadBase)
sqlAbono: TZQuery;
sqlAbonoCodigo: TIntegerField;
sqlAbonoAnoLetivo: TStringField;
sqlAbonoMat: TStringField;
sqlAbonoNomeAluno: TStringField;
sqlAbonoBim: TStringField;
sqlAbonoDisc: TStringField;
sqlAbonoNomeDisciplina: TStringField;
sqlAbonoFaltas: TIntegerField;
sqlAbonoMotivo: TStringField;
procedure tbtn_ExcelClick(Sender: TObject);
procedure sqlAbonoBimGetText(Sender: TField; var Text: string; DisplayText: Boolean);
procedure tbtn_ExcluirClick(Sender: TObject);
procedure btn_PesquisarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
procedure Registro(Acao : TOperacao);
{ Public declarations }
end;
var
frmAbonoFaltas: TfrmAbonoFaltas;
implementation
uses uDMPrincipal, uAbonoFaltasCad, uDMAction;
{$R *.dfm}
{ TfrmAbonoFaltas }
procedure TfrmAbonoFaltas.btn_PesquisarClick(Sender: TObject);
var
sSQL : String;
const
campos : array[0..4] of string = ('af.Mat', 'a.Nome', 'af.Disc', 'd.Nome', 'af.Motivo');
begin
sSQL := ' SELECT af.Codigo, af.AnoLetivo, af.Mat, a.Nome as NomeAluno, '+
' af.Bim, af.Disc, d.Nome as NomeDisciplina, af.Faltas, af.Motivo '+
' FROM AbonoFaltas af '+
' INNER JOIN Alunos a ON af.Mat = a.Mat '+
' INNER JOIN Disciplina1 d ON af.Disc = d.Codigo '+
' WHERE af.AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) +
' AND d.AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) ;
if NOT isEmptyStr(edt_Pesquisa.Text) then
begin
if cb_Campo.ItemIndex in [0, 2] then
sSQL := sSQL + ' AND ' + Campos[cb_Campo.ItemIndex] + ' = ' + QuotedStr(edt_Pesquisa.Text)
else
sSQL := sSQL + ' AND ' + Campos[cb_Campo.Itemindex] + ' LIKE ' + QuotedStr('%' + edt_Pesquisa.Text + '%');
end;
sSQL := sSQL + ' ORDER BY ' + Campos[cb_Campo.Itemindex];
DMPrincipal.OpenSQL(sqlAbono, sSQL);
end;
procedure TfrmAbonoFaltas.FormCreate(Sender: TObject);
begin
inherited;
cb_Campo.ItemIndex := 0;
btn_Pesquisar.Click;
// sqlAbonoBim.DisplayLabel := sqlAbonoAbreviacao_Per.Value;
end;
procedure TfrmAbonoFaltas.Registro(Acao: TOperacao);
var
sSQL : String;
OK : Boolean;
begin
Application.CreateForm( TfrmAbonoFaltasCad, frmAbonoFaltasCad);
frmAbonoFaltasCad.Acao := Acao;
try
case Acao of
opIncluir : begin
sSQL := 'SELECT * FROM AbonoFaltas WHERE Codigo = 0';
DMPrincipal.OpenSQL(DMPrincipal.sqlAbonoFaltas, sSQL);
DMPrincipal.sqlAbonoFaltas.Append;
DMPrincipal.sqlAbonoFaltasAnoLetivo.Value := vUser.AnoLetivo;
end;
opAlterar,
opVisualizar : begin
sSQL := 'SELECT * FROM AbonoFaltas WHERE Codigo = 0' + sqlAbonoCodigo.AsString;
DMPrincipal.OpenSQL(DMPrincipal.sqlAbonoFaltas, sSQL);
frmAbonoFaltasCad.fraAluno.Matricula := DMPrincipal.sqlAbonoFaltasMat.Value;
frmAbonoFaltasCad.fraPeriodo.Periodo := DMPrincipal.sqlAbonoFaltasBim.AsInteger;
if Acao = opAlterar then
begin
DMPrincipal.Espiao.Esp_AlteracaoGuarda( Self.Caption, DMPrincipal.sqlAbonoFaltas);
DMPrincipal.sqlAbonoFaltas.Edit;
end else
begin
frmAbonoFaltasCad.somenteLeitura;
end;
end;
end;
OK := frmAbonoFaltasCad.ShowModal = mrOk;
if Acao <> opVisualizar then
begin
if Ok then
begin
DMPrincipal.sqlAbonoFaltasMat.Value := frmAbonoFaltasCad.fraAluno.Matricula;
DMPrincipal.sqlAbonoFaltasBim.AsInteger := frmAbonoFaltasCad.fraPeriodo.Periodo;
DMPrincipal.sqlAbonoFaltas.Post;
if Acao = opAlterar then
DMPrincipal.Espiao.Esp_AlteracaoVerifica( Self.Caption, 'Codigo', DMPrincipal.sqlAbonoFaltas,[ DMPrincipal.sqlAbonoFaltasCodigo.AsString ] );
if Acao = opIncluir then
DMPrincipal.Espiao.Esp_IncExc(Self.Caption, 'Incluir', DMPrincipal.sqlAbonoFaltas, ['Codigo','AnoLetivo','Mat','Bim','Disc']);
end else
DMPrincipal.sqlAbonoFaltas.Cancel;
end;
if Acao = opVisualizar then
DMPrincipal.Espiao.RegistraLog(Self.Caption, 'Visualizar', '');
finally
DMPrincipal.sqlAbonoFaltas.Close;
FreeAndNil(frmAbonoFaltasCad);
end;
btn_Pesquisar.Click;
end;
procedure TfrmAbonoFaltas.sqlAbonoBimGetText(Sender: TField; var Text: string; DisplayText: Boolean);
begin
inherited;
Text := DMPrincipal.Letivo.PeriodoToStr(Sender.AsString);
end;
procedure TfrmAbonoFaltas.tbtn_ExcelClick(Sender: TObject);
begin
inherited;
//
end;
procedure TfrmAbonoFaltas.tbtn_ExcluirClick(Sender: TObject);
begin
if MessageBox(handle, 'Deseja excluir este registro?', 'Atenção!', MB_ICONQUESTION + MB_YESNO) = IDYES then
begin
DMPrincipal.Espiao.Esp_IncExc(Self.Caption, 'Excluir', sqlAbono, ['Codigo','AnoLetivo','Mat','Bim','Disc']);
DMPrincipal.Zconn.ExecuteDirect(' DELETE '+
' FROM AbonoFaltas '+
' WHERE AnoLetivo = ' + QuotedStr(vUser.AnoLetivo) +
' AND Codigo = 0' + sqlAbonoCodigo.AsString );
btn_Pesquisar.Click;
end;
end;
end.
|
EDIT GETTOKTEST.PAS
C
PROCEDURE MyProgram;
{This procedure is to test GetTok. It will get the tokens and
write them to STDOUT}
VAR Token: String;
%INCLUDE 'umb$disk2:[math.cs210]gbfpbf.pas'
(*************************************************************************)
FUNCTION GetTok(var Token: String): Character;
{This function returns as it's value the first character of the
token string and returns the complete string as Token.}
VAR Counter: integer;
C: Character;
TokenCollected: Boolean;
BEGIN {GetTok}
Counter := 1;
TokenCollected := False;
REPEAT
Token[Counter] := GetPbcf(C,STDIN);
CASE Token[Counter] OF
BLANK: Token[Counter] := Getpbcf(C,STDIN);
1,2,3,4,5,6,7,8,9: BEGIN {CASE CONDITION}
WHILE getpbcf(C,STDIN) <> BLANK DO
BEGIN {WHILE}
Counter := Counter + 1;
Token[Counter] := C;
END; {WHILE}
TokenCollected := True;
END; {CASE CONDTION}
'!': BEGIN {CASE CONDTION}
WHILE getpbcf(C,STDIN) <> NEWLINE DO
BEGIN {WHILE}
Counter := Counter + 1;
Token[Counter] := C;
END; {While}
TokenCollected := True;
END; {CASE CONDITION}
'~','#','+','-','*','/','^','=','R','A','Q':
TokenCollected := True;
END; {CASE}
UNTIL TokenCollected;
Token[Counter + 1] := ENDSTR;
GetTok := Token[1];
END; {GetTok}
(************************* MAIN ****************************************)
BEGIN {MAIN}
Initio;
Message('GetTok TEST -- ERIC GATES -- 6/15/89');
Initpbf(STDIN)
WHILE GetTok(Token) <> 'Q' DO
BEGIN {WHILE}
Write('->');
PutStr(Token,STDOUT);
Writeln('<-');
END; {WHILE}
END; {MAIN}
|
unit BankAccountMovementTest;
interface
uses dbTest, dbMovementTest, ObjectTest;
type
TBankAccountMovementTest = class (TdbMovementTestNew)
published
procedure ProcedureLoad; override;
procedure Test; override;
end;
TBankAccountMovement = class(TMovementTest)
private
function InsertDefault: integer; override;
public
function InsertUpdateBankAccount(const Id: integer; InvNumber: String;
OperDate: TDateTime; Amount: Double;
FromId, ToId, CurrencyId, InfoMoneyId, BusinessId, ContractId, UnitId,
IncomeMovementId: integer): integer;
constructor Create; override;
end;
implementation
uses UtilConst, JuridicalTest, dbObjectTest, SysUtils, Db, TestFramework, dsdDB,
DBClient, BankAccountTest, InfoMoneyTest, UnitsTest, CurrencyTest;
{ TBankAccount }
constructor TBankAccountMovement.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_Movement_BankAccount';
spSelect := 'gpSelect_Movement_BankAccount';
spGet := 'gpGet_Movement_BankAccount';
spCompleteProcedure := 'gpComplete_Movement_BankAccount';
end;
function TBankAccountMovement.InsertDefault: integer;
var Id: Integer;
InvNumber: String;
OperDate: TDateTime;
Amount: Double;
FromId, ToId, InfoMoneyId, BusinessId, ContractId, UnitId, CurrencyId,IncomeMovementId: Integer;
begin
Id:=0;
InvNumber:='1';
OperDate:= Date;
FromId := TJuridical.Create.GetDefault;
ToId := TBankAccount.Create.GetDefault;
ContractId := 0;
InfoMoneyId := 0;
with TCurrency.Create.GetDataSet do begin
CurrencyId := FieldByName('Id').AsInteger;
end;
with TInfoMoney.Create.GetDataSet do begin
if Locate('Code', '10103', []) then
InfoMoneyId := FieldByName('Id').AsInteger;
end;
BusinessId := 0;
UnitId := TUnit.Create.GetDefault;
Amount := 265.68;
IncomeMovementId := 0;
result := InsertUpdateBankAccount(Id, InvNumber, OperDate, Amount,
FromId, ToId, CurrencyId, InfoMoneyId, BusinessId, ContractId, UnitId,
IncomeMovementId);
end;
function TBankAccountMovement.InsertUpdateBankAccount(const Id: integer; InvNumber: String;
OperDate: TDateTime; Amount: Double;
FromId, ToId, CurrencyId, InfoMoneyId, BusinessId, ContractId, UnitId,IncomeMovementId: integer): integer;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inInvNumber', ftString, ptInput, InvNumber);
FParams.AddParam('inOperDate', ftDateTime, ptInput, OperDate);
FParams.AddParam('inAmountIn', ftFloat, ptInput, Amount);
FParams.AddParam('inAmountOut', ftFloat, ptInput, 0);
FParams.AddParam('inAmountSumm', ftFloat, ptInput, 0);
FParams.AddParam('inBankAccountId', ftInteger, ptInput, FromId);
FParams.AddParam('inComment', ftString, ptInput, '');
FParams.AddParam('inMoneyPlaceId', ftInteger, ptInput, ToId);
FParams.AddParam('inIncomeMovementId', ftInteger, ptInput, IncomeMovementId);
FParams.AddParam('inContractId', ftInteger, ptInput, ContractId);
FParams.AddParam('inInfoMoneyId', ftInteger, ptInput, InfoMoneyId);
FParams.AddParam('inCurrencyId', ftInteger, ptInput, CurrencyId);
FParams.AddParam('inCurrencyPartnerValue', ftFloat, ptInput, 0);
FParams.AddParam('inParPartnerValue', ftFloat, ptInput, 0);
result := InsertUpdate(FParams);
end;
{ TBankAccountTest }
procedure TBankAccountMovementTest.ProcedureLoad;
begin
ScriptDirectory := LocalProcedurePath + 'Movement\BankAccount\';
inherited;
ScriptDirectory := LocalProcedurePath + 'MovementItemContainer\BankAccount\';
inherited;
end;
procedure TBankAccountMovementTest.Test;
var MovementBankAccount: TBankAccountMovement;
Id: Integer;
StoredProc: TdsdStoredProc;
AccountAmount, AccountAmountTwo: double;
begin
inherited;
AccountAmount := 0;
AccountAmountTwo := 0;
// Создаем документ
MovementBankAccount := TBankAccountMovement.Create;
// создание документа
Id := MovementBankAccount.InsertDefault;
// Проверяем остаток по счету кассы
StoredProc := TdsdStoredProc.Create(nil);
StoredProc.Params.AddParam('inStartDate', ftDateTime, ptInput, Date);
StoredProc.Params.AddParam('inEndDate', ftDateTime, ptInput, TDateTime(Date));
StoredProc.StoredProcName := 'gpReport_Balance';
StoredProc.DataSet := TClientDataSet.Create(nil);
StoredProc.OutputType := otDataSet;
StoredProc.Execute;
with StoredProc.DataSet do begin
if Locate('AccountCode', '40301', []) then
AccountAmount := FieldByName('AmountDebetEnd').AsFloat + FieldByName('AmountKreditEnd').AsFloat
end;
try
// проведение
//MovementBankAccount.DocumentComplete(Id);
//StoredProc.Execute;
// with StoredProc.DataSet do begin
// if Locate('AccountCode', '40301', []) then
// AccountAmountTwo := FieldByName('AmountDebetEnd').AsFloat - FieldByName('AmountKreditEnd').AsFloat;
// end;
// Check(abs(AccountAmount - (AccountAmountTwo + 265.68)) < 0.01, 'Провелось не правильно. Было ' + FloatToStr(AccountAmount) + ' стало ' + FloatToStr(AccountAmountTwo));
finally
// распроведение
//MovementBankAccount.DocumentUnComplete(Id);
StoredProc.Free;
end;
end;
initialization
TestFramework.RegisterTest('Документы', TBankAccountMovementTest.Suite);
end.
|
unit UHot1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
RTFUtils, StdCtrls, Spin;
type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
btnLoad: TButton;
btnSave: TButton;
Memo1: TMemo;
Memo2: TMemo;
Label1: TLabel;
edName: TEdit;
Label2: TLabel;
Label3: TLabel;
edDescription: TEdit;
edStart: TSpinEdit;
edLength: TSpinEdit;
Label4: TLabel;
btnAdd: TButton;
ListBox1: TListBox;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
edLinkTo: TEdit;
procedure btnLoadClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
HotItems : THotLinkItems;
procedure UpdateDetail;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.btnLoadClick(Sender: TObject);
begin
if FileExists(edit1.text)
then Memo1.Lines.LoadFromFile(edit1.text)
else Memo1.Lines.clear;
HotItems.LoadFromFile(edit1.text);
UpdateDetail;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
HotItems := THotLinkItems.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
HotItems.free;
end;
procedure TForm1.btnSaveClick(Sender: TObject);
begin
HotItems.SaveToFile(Edit2.text);
Memo2.Lines.loadFromFile(Edit2.text);
end;
procedure TForm1.UpdateDetail;
var
i : integer;
s : string;
begin
Listbox1.items.clear;
for i:=0 to HotItems.count-1 do
with HotItems[i] do
begin
s := name + ':' + IntToStr(Start)+':'+IntToStr(Length);
Listbox1.items.Add(s);
end;
end;
procedure TForm1.btnAddClick(Sender: TObject);
begin
with HotItems.AddItemName(edName.text) do
begin
Start := edStart.value;
Length := edLength.value;
Description := edDescription.text;
LinkTo := edLinkTo.Text;
end;
UpdateDetail;
end;
end.
|
(*----------------------------------------------------------------------*)
(* Übung 5: Feldverarbeitung *)
(* Entwickler: Neuhold Michael *)
(* Datum: 11.11.2018 *)
(* Lösungsidee: zwei arrays zusammenfügen, aber nur jene Zahlen *)
(* verwenden, die nicht in beiden Arrays vorkommen *)
(* und anschließend mit Bubble Sort sortieren *)
(*----------------------------------------------------------------------*)
PROGRAM Feldverarbeitung;
CONST
max = 10;
maxfinal = 20;
TYPE
Feld = ARRAY[1..max] OF INTEGER;
Final = ARRAY[1..maxfinal] OF INTEGER;
DoNot = ARRAY[1..max] OF INTEGER;
(* Define do not use numbers *)
PROCEDURE DublicateNumbers(n1,n2: INTEGER; a1, a2: ARRAY OF INTEGER; VAR doNotUse: DoNot; VAR countNot: INTEGER); // FELD
VAR
i,j : INTEGER;
BEGIN
FOR i := 0 TO n1-1 DO BEGIN
FOR j := 0 TO n2-1 DO BEGIN
IF a1[i] = a2[j] THEN BEGIN
doNotUse[countNot] := a1[i];
countNot := countNot + 1;
END;
END;
END;
END;
(* GET Boolean if this number should be used or not *)
FUNCTION NotToUse(doNotUse: DoNot; zahl, countNot: INTEGER): BOOLEAN;
VAR
i: INTEGER;
found: BOOLEAN;
BEGIN
i := 1;
repeat
IF doNotUse[i] = zahl THEN
found := TRUE
ELSE
found := FALSE;
i := i + 1;
until (found OR (i >= countNot));
NotToUse := found;
END;
(* swap *)
PROCEDURE Swap(VAR a,b: INTEGER);
VAR
h: INTEGER; (* help to swap to values *)
BEGIN
h := a;
a := b;
b := h;
END;
(* Bubble Sort *)
PROCEDURE Sort(VAR a: ARRAY OF INTEGER; countFinal: INTEGER);
VAR
i, j: INTEGER;
BEGIN
FOR i := countFinal-1 DOWNTO 1 DO BEGIN
FOR j := 0 TO i-1 DO BEGIN
IF (a[j] > a[j+1]) THEN BEGIN
Swap(a[j],a[j+1]);
END;
END;
END;
END;
(* write all non dublicate numbers in A3 *)
PROCEDURE WriteInA3(n1,n2: INTEGER; a1,a2: ARRAY OF INTEGER; VAR a3: Final; VAR countA3: INTEGER; countNot: INTEGER; doNotUse: DoNot); //Feld
VAR
i: INTEGER;
BEGIN
FOR i := 0 TO n1-1 DO BEGIN
IF not(NotToUse(doNotUse,a1[i],countNot)) THEN BEGIN
countA3 := countA3 + 1;
a3[countA3] := a1[i];
END;
END;
FOR i := 0 TO n2-1 DO BEGIN
IF not(NotToUse(doNotUse,a2[i],countNot)) THEN BEGIN
countA3 := countA3 + 1;
a3[countA3] := a2[i];
END;
END;
END;
(* Output for A3 *)
PROCEDURE Output(a: ARRAY OF INTEGER; n: INTEGER);
VAR
i: INTEGER;
BEGIN
FOR i := 0 TO n-1 DO BEGIN
Write(a[i]:8);
END;
END;
(* combine all procedures *)
PROCEDURE Merge(a1, a2: ARRAY OF INTEGER; VAR a3: ARRAY OF INTEGER; VAR n1,n2,n3: INTEGER);
VAR
doNotUse: DoNot;
countNot: INTEGER;
countA3, i: INTEGER;
BEGIN
countA3 := 0;
countNot := 1;
DublicateNumbers(n1,n2,a1,a2,doNotUse,countNot);
WriteInA3(n1,n2,a1,a2,a3,countA3,countNot, doNotUse);
Sort(a3,countA3);
IF countA3 > n3 THEN
WriteLn('Das Ergebnis Array ist größer als gewünscht!');
END;
VAR
a1, a2: Feld;
a3: Final;
n1, n2, n3,i: INTEGER;
(* Main *)
BEGIN
WriteLn('Wie viele Werte soll A1 besitzen? Max. 10');
ReadLn(n1);
WriteLn('Wie viele Werte soll A2 besitzen? Max. 10');
ReadLn(n2);
WriteLn('Wie viele Werte soll A3 max. besitzen?');
ReadLn(n3);
WriteLn('Eingabe für A1:');
FOR i := 1 TO n1 DO BEGIN
ReadLn(a1[i]);
END;
WriteLn('Eingabe für A2:');
FOR i := 1 TO n2 DO BEGIN
ReadLn(a2[i]);
END;
Merge(a1,a2,a3,n1,n2,n3);
Write('a3 = ');
Output(a3,n3);
WriteLn;
END. |
unit UPortBase;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2008 by Bradford Technologies, Inc. }
interface
uses
Classes, Windows, Messages, Controls, contnrs,
UMapUtils;
const
WM_PORTFINISHED = WM_APP + 1001;
WM_CLOSEPORT = WM_APP + 1002;
//Map page sizes
cMapLegalSize = 0;
cMapLetterSize= 1;
cMapHalfPgSize= 2;
//sketch areas IDs;
skArea1stFloor = 0;
skArea2ndFloor = 1;
skArea3rdFloor = 2;
skAreaGLA = 3;
skAreaBasement = 4;
skAreaGarage = 5;
nsketchAreas = 6;
type
//so we can send results back to managers
TResultsData = Class(TObject);
TResultsEvent = procedure(Sender: TObject; Data: TResultsData) of Object;
SubjSketchInfo = array of String; //we need id for APEX
ImageInfo = record
path: String;
imgType: Integer;
format: String;
end;
//base class for all specialized port objects
TPortBase = class(TObject)
private
FOwner: TWinControl; //window/ToolMgr who launched this port
FFileData: TMemoryStream; //for storing assoc file data in memory
FFileDataPath: String; //path to data file
FData: TObject; //for storing other data like lists
FOnFinish: TResultsEvent; //so port can notify caller when its finished
FAppName: String; //the application name it is interfacing with
FAppPath: String; //the path to the application
public
subjInfo: SubjSketchInfo;
Images: Array of ImageInfo;
constructor Create; virtual;
procedure Launch; virtual;
procedure Execute; virtual;
procedure LoadData(const filePath: String; Data: TMemoryStream); virtual;
procedure LoadSubjectInfo; virtual;
procedure PortIsFinished(Sender: TObject); virtual; //com server calls this when done
procedure ClosePort(Sender: TObject);
property OnFinish: TResultsEvent read FOnFinish write FOnFinish; //so port can notify Mgr
property Owner: TWinControl read FOwner write FOwner;
property FileDataPath: String read FFileDataPath write FFileDataPath;
property FileData: TMemoryStream Read FFileData write FFileData;
property Data: TObject read FData write FData;
property ApplicationName: String read FAppName write FAppName;
property ApplicationPath: String read FAppPath write FAppPath;
//yakovs
function OnCompleted: Boolean; virtual; //YF 06.18.02
procedure InitForm; virtual;//YF 06.19.02
end;
//generic mapping port
TPortMapper = class(TPortBase)
private
FMapSizeIndex: Integer;
FMapSize: TPoint;
FGeoCoded: Boolean; //has Lat/Long data
FGeoBounds: TGeoRect; //lat/Long Rect
FExportDir: String;
FExportName: String;
protected
function GetAddresses: TObjectList;
public
constructor Create; Override;
function ExportAddresses: Boolean; virtual;
procedure ZoomIn; virtual;
procedure ZoomOut; virtual;
procedure ZoomMap(Scale: Integer); virtual;
procedure UpdateMap(Offsets: TPoint); virtual;
procedure Revert; virtual;
property Addresses: TObjectList read GetAddresses;
property ExportDir: String read FExportDir write FExportDir;
property ExportName: String read FExportName write FExportName;
property MapSizeIndex: Integer read FMapSizeIndex write FMapSizeIndex;
property MapSize: TPoint read FMapSize write FMapSize;
property MapGeoCoded: Boolean read FGeoCoded write FGeoCoded;
property MapGeoRect: TGeoRect read FGeoBounds write FGeoBounds;
end;
TSketchResults = class(TResultsData)
public
FTitle: String;
FDataKind: String;
FDataStream: TMemoryStream;
FSketches: TObjectList;
FArea: Array of Double;
constructor Create;
destructor Destroy; override;
end;
TAddressData = class(TResultsData)
public
FLabel: String;
FStreetNo: String;
FStreetName: String;
FCity: String;
FState: String;
FZip: String;
FLongitude: String;
FLatitude: String;
FGeoCodeScore: String;
FProximity: String;
FCensusTract: String;
FFemaZone: String;
FFemaMapDate: String;
FFemaMapNum: String;
FFloodHazard: String;
FCompType: Integer;
FCompNum: Integer;
end;
implementation
uses
SysUtils, UUtil1, UStatus;
constructor TPortBase.Create;
begin
inherited;
FOwner := nil;
FOnFinish := nil;
FData := nil;
FFileData := nil;
FFileDataPath := '';
FAppName := ''; //the application name it is interfacing with
FAppPath := ''; //the path to the application
end;
procedure TPortBase.Launch;
begin
end;
procedure TPortBase.Execute;
begin
end;
procedure TPortBase.LoadSubjectInfo;
begin;
end;
procedure TPortBase.PortIsFinished(Sender: TObject);
begin
if Owner <> nil then
PostMessage(Owner.Handle, WM_PORTFINISHED, 0,0);
end;
procedure TPortBase.ClosePort(Sender: TObject);
begin
if Owner <> nil then
PostMessage(Owner.Handle, WM_CLOSEPORT, 0,0);
end;
procedure TPortBase.LoadData(const filePath: String; Data: TMemoryStream); //got it from portwinSketch
begin
FileDataPath := FilePath;
if FileDataPath = '' then
FileDataPath := IncludeTrailingPathDelimiter(GetTempFolderPath) + 'Untitled.skt';
//there is prev data, pass it to Sketch
if data <> nil then
try
if FileData = nil then
FileData := TMemoryStream.Create;
FileData.LoadFromStream(Data); //port now owns the data
FileData.SaveToFile(FileDataPath); //write it so Skt can read it
except
ShowNotice('The stored Sketch data could not be written.');
end;
end;
function TPortBase.OnCompleted: Boolean; //YF 06.18.02
begin
result := False;
end;
procedure TPortBase.InitForm;
begin
end;
{ TPortMapper }
constructor TPortMapper.Create;
begin
inherited Create;
FExportDir := '';
FExportName := '';
FMapSizeIndex := cMapLetterSize;
//for holding the bounds latitude and longitude of the map
FGeoCoded := False; //default to not having GeoCode data
// FMapLatTop := 0; //north
// FMapLatBot := 0; //south
// FMapLonLeft := 0; //west
// FMapLonRight := 0; //east
end;
function TPortMapper.ExportAddresses: Boolean;
begin
result := False;
end;
//getter so FData:TObject becomes TObjectList
function TPortMapper.GetAddresses: TObjectList;
begin
result := TObjectList(Data);
end;
procedure TPortMapper.ZoomIn;
begin
end;
procedure TPortMapper.ZoomOut;
begin
end;
procedure TPortMapper.ZoomMap(Scale: Integer);
begin
end;
procedure TPortMapper.UpdateMap (Offsets: TPoint);
begin
end;
procedure TPortMapper.Revert;
begin
end;
{ ******************************************************** }
{ Results Objects that are passed back to manager by Ports }
{ ******************************************************** }
{ TSketchResults }
constructor TSketchResults.Create;
begin
FSketches := TObjectList.Create;
FSketches.OwnsObjects := False; //do not delete images when we free list
FDataStream := nil; //data normally stored in the sketcher file
FTitle := ''; //Title that will be displayed in the results window
SetLength(FArea, 6); //we hold six areas
end;
destructor TSketchResults.Destroy;
begin
if assigned(FSketches) then
FSketches.Free; //free the list, not the objects
FArea := nil;
inherited;
end;
end.
|
{*******************************************************************************
作者: juner11212436@163.com 2019-04-26
描述: 选择手工录入批次号
*******************************************************************************}
unit UFormGetBatCode;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFormNormal, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, ComCtrls, cxCheckBox, Menus,
cxLabel, cxListView, cxTextEdit, cxMaskEdit, cxButtonEdit,
dxLayoutControl, StdCtrls;
type
TfFormGetBatCode = class(TfFormNormal)
ListBatCode: TcxListView;
dxLayout1Item6: TdxLayoutItem;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BtnOKClick(Sender: TObject);
procedure ListBatCodeKeyPress(Sender: TObject; var Key: Char);
procedure ListBatCodeDblClick(Sender: TObject);
private
{ Private declarations }
FStockNo: string;
function QueryBatCode(const nStockNo: string): Boolean;
//查询车辆
public
{ Public declarations }
class function CreateForm(const nPopedom: string = '';
const nParam: Pointer = nil): TWinControl; override;
class function FormID: integer; override;
end;
implementation
{$R *.dfm}
uses
IniFiles, ULibFun, UMgrControl, UFormBase, USysGrid, USysDB, USysConst,
USysBusiness, UDataModule, UFormInputbox;
class function TfFormGetBatCode.CreateForm(const nPopedom: string;
const nParam: Pointer): TWinControl;
var nP: PFormCommandParam;
begin
Result := nil;
if Assigned(nParam) then
nP := nParam
else Exit;
with TfFormGetBatCode.Create(Application) do
begin
Caption := '选择批次';
FStockNo := nP.FParamA;
QueryBatCode(FStockNo);
nP.FCommand := cCmd_ModalResult;
nP.FParamA := ShowModal;
if nP.FParamA = mrOK then
nP.FParamB := ListBatCode.Items[ListBatCode.ItemIndex].Caption;
Free;
end;
end;
class function TfFormGetBatCode.FormID: integer;
begin
Result := cFI_FormGetBatCode;
end;
procedure TfFormGetBatCode.FormCreate(Sender: TObject);
var nIni: TIniFile;
begin
nIni := TIniFile.Create(gPath + sFormConfig);
try
LoadFormConfig(Self, nIni);
LoadcxListViewConfig(Name, ListBatCode, nIni);
finally
nIni.Free;
end;
end;
procedure TfFormGetBatCode.FormClose(Sender: TObject;
var Action: TCloseAction);
var nIni: TIniFile;
begin
nIni := TIniFile.Create(gPath + sFormConfig);
try
SaveFormConfig(Self, nIni);
SavecxListViewConfig(Name, ListBatCode, nIni);
finally
nIni.Free;
end;
end;
//------------------------------------------------------------------------------
//Desc: 查询批次
function TfFormGetBatCode.QueryBatCode(const nStockNo: string): Boolean;
var nStr, nType: string;
begin
Result := False;
ListBatCode.Items.Clear;
nStr := 'Select * from %s Where D_Stock=''%s'' and D_Valid=''%s'' '+
'Order By D_UseDate';
nStr := Format(nStr, [sTable_BatcodeDoc, nStockNo, sFlag_BatchInUse]);
//xxxxxx
with FDM.QueryTemp(nStr) do
if RecordCount > 0 then
begin
First;
while not Eof do
begin
with ListBatCode.Items.Add do
begin
Caption := FieldByName('D_ID').AsString;
SubItems.Add(FieldByName('D_Name').AsString);
ImageIndex := 11;
StateIndex := ImageIndex;
end;
Next;
end;
end;
Result := ListBatCode.Items.Count > 0;
if Result then
begin
ActiveControl := ListBatCode;
ListBatCode.ItemIndex := 0;
ListBatCode.ItemFocused := ListBatCode.TopItem;
end;
end;
procedure TfFormGetBatCode.ListBatCodeKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
begin
Key := #0;
if ListBatCode.ItemIndex > -1 then
ModalResult := mrOk;
//xxxxx
end;
end;
procedure TfFormGetBatCode.ListBatCodeDblClick(Sender: TObject);
begin
if ListBatCode.ItemIndex > -1 then
ModalResult := mrOk;
//xxxxx
end;
procedure TfFormGetBatCode.BtnOKClick(Sender: TObject);
begin
if ListBatCode.ItemIndex > -1 then
ModalResult := mrOk
else ShowMsg('请在查询结果中选择', sHint);
end;
initialization
gControlManager.RegCtrl(TfFormGetBatCode, TfFormGetBatCode.FormID);
end.
|
unit main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, iniFiles, ShellApi;
type
TStarterForm = class(TForm)
MusicScrollbar: TScrollBar;
SoundScrollbar: TScrollBar;
FullScreenCheckBox: TCheckBox;
AlphaCheckBox: TCheckBox;
StartBtn: TButton;
SaveBtn: TButton;
MusicLabel: TLabel;
SoundLabel: TLabel;
CmdStartBtn: TButton;
EnvBtn: TButton;
EditorBtn: TButton;
procedure FormCreate(Sender: TObject);
procedure MusicScrollbarChange(Sender: TObject);
procedure SoundScrollbarChange(Sender: TObject);
procedure SaveBtnClick(Sender: TObject);
procedure StartBtnClick(Sender: TObject);
procedure CmdStartBtnClick(Sender: TObject);
procedure EnvBtnClick(Sender: TObject);
procedure EditorBtnClick(Sender: TObject);
private
function IsWOW64: BOOL;
public
function runExe(exeName, exePath: String; errorInfo: String = ''): Boolean;
procedure setupVCRedist();
procedure loadConfig();
procedure saveConfig();
procedure runGame(gName: string);
end;
var
StarterForm: TStarterForm;
starterPath: String = '';
const
configFileName = 'game\config.ini';
gameFileName = 'shf-cpp.exe';
cmdGameFileName = 'shf-cpp-cmd.exe';
gamePath = 'game\';
vcRedistPath = 'VCRedist\';
vcRedistExe64 = 'vc_redist.x64.exe';
vcRedistExe32 = 'vc_redist.x86.exe';
editorPath = 'Editor\';
editorFileName = 'shfEditor.exe';
implementation
{$R *.dfm}
function TStarterForm.runExe(exeName, exePath: String; errorInfo: String = ''): Boolean;
begin
if (not FileExists(exeName)) then
begin
ShowMessage('找不到文件:' + exeName + ' !');
Result := false;
exit;
end;
Result := (ShellExecute(0, 'open', PWideChar(exeName), nil, PWideChar(exePath), SW_NORMAL) >= 32);
if (not Result) then
if errorInfo = '' then
ShowMessage('程序:' + exeName + '启动失败!')
else
ShowMessage(errorInfo);
end;
procedure TStarterForm.loadConfig();
var
ini: TIniFile;
musicVolume, soundVolume: Integer;
fullScreen, playerAlpha: Boolean;
begin
if (not FileExists(configFileName)) then
begin
ShowMessage('找不到配置文件:' + configFileName + ' !');
end;
ini := TIniFile.Create(configFileName);
musicVolume := ini.ReadInteger('Game', 'MusicVolume', 100);
soundVolume := ini.ReadInteger('Game', 'SoundVolume', 100);
fullScreen := ini.ReadBool('Game', 'FullScreen', true);
playerAlpha := ini.ReadBool('Game', 'PlayerAlpha', true);
MusicScrollbar.Position := musicVolume;
SoundScrollbar.Position := soundVolume;
FullScreenCheckBox.Checked := fullScreen;
AlphaCheckBox.Checked := playerAlpha;
MusicScrollbarChange(self);
SoundScrollbarChange(self);
ini.Free;
end;
procedure TStarterForm.saveConfig();
var
ini: TIniFile;
musicVolume, soundVolume: Integer;
fullScreen, playerAlpha: Boolean;
begin
musicVolume := MusicScrollbar.Position;
soundVolume := SoundScrollbar.Position;
fullScreen := FullScreenCheckBox.Checked;
playerAlpha := AlphaCheckBox.Checked;
ini := TIniFile.Create(configFileName);
ini.WriteInteger('Game', 'MusicVolume', musicVolume);
ini.WriteInteger('Game', 'SoundVolume', soundVolume);
ini.WriteBool('Game', 'FullScreen', fullScreen);
ini.WriteBool('Game', 'PlayerAlpha', playerAlpha);
ini.Free;
end;
procedure TStarterForm.runGame(gName: string);
var
gameExeName: String;
gamePathName: String;
begin
gamePathName := starterPath + gamePath;
gameExeName := gamePathName + gName;
if (runExe(gameExeName, gamePathName, '游戏启动失败!')) then
Halt(0);
end;
procedure TStarterForm.setupVCRedist();
var
VCRedistExePath: String;
VCRedistExeName: String;
begin
VCRedistExePath := starterPath + VCRedistPath;
if isWOW64() then
VCRedistExeName := VCRedistExePath + VCRedistExe64
else
VCRedistExeName := VCRedistExePath + VCRedistExe32;
runExe(VCRedistExeName, VCRedistExePath, '安装程序启动失败!');
end;
procedure TStarterForm.CmdStartBtnClick(Sender: TObject);
begin
saveConfig();
runGame(cmdGameFileName);
end;
procedure TStarterForm.EditorBtnClick(Sender: TObject);
var
EditorExePath: String;
EditorExeName: String;
begin
EditorExePath := starterPath + EditorPath;
EditorExeName := EditorExePath + EditorFileName;
runExe(EditorExeName, EditorExePath, '编辑器启动失败!');
end;
procedure TStarterForm.EnvBtnClick(Sender: TObject);
begin
setupVCRedist();
end;
procedure TStarterForm.FormCreate(Sender: TObject);
begin
starterPath := ExtractFilePath(ParamStr(0));
loadConfig();
end;
procedure TStarterForm.MusicScrollbarChange(Sender: TObject);
begin
MusicLabel.Caption := '音乐音量:' + inttostr(MusicScrollbar.Position);
end;
procedure TStarterForm.SaveBtnClick(Sender: TObject);
begin
saveConfig();
end;
procedure TStarterForm.SoundScrollbarChange(Sender: TObject);
begin
SoundLabel.Caption := '音效音量:' + inttostr(SoundScrollbar.Position);
end;
procedure TStarterForm.StartBtnClick(Sender: TObject);
begin
saveConfig();
runGame(gameFileName);
end;
function TStarterForm.IsWOW64: BOOL;
begin
Result := False;
if GetProcAddress(GetModuleHandle(kernel32), 'IsWow64Process') <> nil then
IsWow64Process(GetCurrentProcess, Result);
end;
end.
|
{$MODESWITCH RESULT+}
{$GOTO ON}
(*************************************************************************
Copyright (c) 2007, Sergey Bochkanov (ALGLIB project).
>>> SOURCE LICENSE >>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation (www.fsf.org); either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************)
unit spline2d;
interface
uses Math, Sysutils, Ap, spline3, blas, reflections, creflections, hqrnd, matgen, ablasf, ablas, trfac, trlinsolve, safesolve, rcond, matinv, hblas, sblas, ortfac, rotations, bdsvd, svd, xblas, densesolver, linmin, minlbfgs, minlm, lsfit, apserv, spline1d;
type
(*************************************************************************
2-dimensional spline inteprolant
*************************************************************************)
Spline2DInterpolant = record
K : AlglibInteger;
C : TReal1DArray;
end;
procedure Spline2DBuildBilinear(X : TReal1DArray;
Y : TReal1DArray;
F : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
var C : Spline2DInterpolant);
procedure Spline2DBuildBicubic(X : TReal1DArray;
Y : TReal1DArray;
F : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
var C : Spline2DInterpolant);
function Spline2DCalc(const C : Spline2DInterpolant;
X : Double;
Y : Double):Double;
procedure Spline2DDiff(const C : Spline2DInterpolant;
X : Double;
Y : Double;
var F : Double;
var FX : Double;
var FY : Double;
var FXY : Double);
procedure Spline2DUnpack(const C : Spline2DInterpolant;
var M : AlglibInteger;
var N : AlglibInteger;
var Tbl : TReal2DArray);
procedure Spline2DLinTransXY(var C : Spline2DInterpolant;
AX : Double;
BX : Double;
AY : Double;
BY : Double);
procedure Spline2DLinTransF(var C : Spline2DInterpolant;
A : Double;
B : Double);
procedure Spline2DCopy(const C : Spline2DInterpolant;
var CC : Spline2DInterpolant);
procedure Spline2DSerialize(const C : Spline2DInterpolant;
var RA : TReal1DArray;
var RALen : AlglibInteger);
procedure Spline2DUnserialize(const RA : TReal1DArray;
var C : Spline2DInterpolant);
procedure Spline2DResampleBicubic(const A : TReal2DArray;
OldHeight : AlglibInteger;
OldWidth : AlglibInteger;
var B : TReal2DArray;
NewHeight : AlglibInteger;
NewWidth : AlglibInteger);
procedure Spline2DResampleBilinear(const A : TReal2DArray;
OldHeight : AlglibInteger;
OldWidth : AlglibInteger;
var B : TReal2DArray;
NewHeight : AlglibInteger;
NewWidth : AlglibInteger);
implementation
const
Spline2DVNum = 12;
procedure BicubicCalcDerivatives(const A : TReal2DArray;
const X : TReal1DArray;
const Y : TReal1DArray;
M : AlglibInteger;
N : AlglibInteger;
var DX : TReal2DArray;
var DY : TReal2DArray;
var DXY : TReal2DArray);forward;
(*************************************************************************
This subroutine builds bilinear spline coefficients table.
Input parameters:
X - spline abscissas, array[0..N-1]
Y - spline ordinates, array[0..M-1]
F - function values, array[0..M-1,0..N-1]
M,N - grid size, M>=2, N>=2
Output parameters:
C - spline interpolant
-- ALGLIB PROJECT --
Copyright 05.07.2007 by Bochkanov Sergey
*************************************************************************)
procedure Spline2DBuildBilinear(X : TReal1DArray;
Y : TReal1DArray;
F : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
var C : Spline2DInterpolant);
var
I : AlglibInteger;
J : AlglibInteger;
K : AlglibInteger;
TblSize : AlglibInteger;
Shift : AlglibInteger;
T : Double;
DX : TReal2DArray;
DY : TReal2DArray;
DXY : TReal2DArray;
begin
X := DynamicArrayCopy(X);
Y := DynamicArrayCopy(Y);
F := DynamicArrayCopy(F);
Assert((N>=2) and (M>=2), 'Spline2DBuildBilinear: N<2 or M<2!');
//
// Sort points
//
J:=0;
while J<=N-1 do
begin
K := J;
I:=J+1;
while I<=N-1 do
begin
if AP_FP_Less(X[I],X[K]) then
begin
K := I;
end;
Inc(I);
end;
if K<>J then
begin
I:=0;
while I<=M-1 do
begin
T := F[I,J];
F[I,J] := F[I,K];
F[I,K] := T;
Inc(I);
end;
T := X[J];
X[J] := X[K];
X[K] := T;
end;
Inc(J);
end;
I:=0;
while I<=M-1 do
begin
K := I;
J:=I+1;
while J<=M-1 do
begin
if AP_FP_Less(Y[J],Y[K]) then
begin
K := J;
end;
Inc(J);
end;
if K<>I then
begin
J:=0;
while J<=N-1 do
begin
T := F[I,J];
F[I,J] := F[K,J];
F[K,J] := T;
Inc(J);
end;
T := Y[I];
Y[I] := Y[K];
Y[K] := T;
end;
Inc(I);
end;
//
// Fill C:
// C[0] - length(C)
// C[1] - type(C):
// -1 = bilinear interpolant
// -3 = general cubic spline
// (see BuildBicubicSpline)
// C[2]:
// N (x count)
// C[3]:
// M (y count)
// C[4]...C[4+N-1]:
// x[i], i = 0...N-1
// C[4+N]...C[4+N+M-1]:
// y[i], i = 0...M-1
// C[4+N+M]...C[4+N+M+(N*M-1)]:
// f(i,j) table. f(0,0), f(0, 1), f(0,2) and so on...
//
C.K := 1;
TblSize := 4+N+M+N*M;
SetLength(C.C, TblSize-1+1);
C.C[0] := TblSize;
C.C[1] := -1;
C.C[2] := N;
C.C[3] := M;
I:=0;
while I<=N-1 do
begin
C.C[4+I] := X[I];
Inc(I);
end;
I:=0;
while I<=M-1 do
begin
C.C[4+N+I] := Y[I];
Inc(I);
end;
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
Shift := I*N+J;
C.C[4+N+M+Shift] := F[I,J];
Inc(J);
end;
Inc(I);
end;
end;
(*************************************************************************
This subroutine builds bicubic spline coefficients table.
Input parameters:
X - spline abscissas, array[0..N-1]
Y - spline ordinates, array[0..M-1]
F - function values, array[0..M-1,0..N-1]
M,N - grid size, M>=2, N>=2
Output parameters:
C - spline interpolant
-- ALGLIB PROJECT --
Copyright 05.07.2007 by Bochkanov Sergey
*************************************************************************)
procedure Spline2DBuildBicubic(X : TReal1DArray;
Y : TReal1DArray;
F : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
var C : Spline2DInterpolant);
var
I : AlglibInteger;
J : AlglibInteger;
K : AlglibInteger;
TblSize : AlglibInteger;
Shift : AlglibInteger;
T : Double;
DX : TReal2DArray;
DY : TReal2DArray;
DXY : TReal2DArray;
begin
X := DynamicArrayCopy(X);
Y := DynamicArrayCopy(Y);
F := DynamicArrayCopy(F);
Assert((N>=2) and (M>=2), 'BuildBicubicSpline: N<2 or M<2!');
//
// Sort points
//
J:=0;
while J<=N-1 do
begin
K := J;
I:=J+1;
while I<=N-1 do
begin
if AP_FP_Less(X[I],X[K]) then
begin
K := I;
end;
Inc(I);
end;
if K<>J then
begin
I:=0;
while I<=M-1 do
begin
T := F[I,J];
F[I,J] := F[I,K];
F[I,K] := T;
Inc(I);
end;
T := X[J];
X[J] := X[K];
X[K] := T;
end;
Inc(J);
end;
I:=0;
while I<=M-1 do
begin
K := I;
J:=I+1;
while J<=M-1 do
begin
if AP_FP_Less(Y[J],Y[K]) then
begin
K := J;
end;
Inc(J);
end;
if K<>I then
begin
J:=0;
while J<=N-1 do
begin
T := F[I,J];
F[I,J] := F[K,J];
F[K,J] := T;
Inc(J);
end;
T := Y[I];
Y[I] := Y[K];
Y[K] := T;
end;
Inc(I);
end;
//
// Fill C:
// C[0] - length(C)
// C[1] - type(C):
// -1 = bilinear interpolant
// (see BuildBilinearInterpolant)
// -3 = general cubic spline
// C[2]:
// N (x count)
// C[3]:
// M (y count)
// C[4]...C[4+N-1]:
// x[i], i = 0...N-1
// C[4+N]...C[4+N+M-1]:
// y[i], i = 0...M-1
// C[4+N+M]...C[4+N+M+(N*M-1)]:
// f(i,j) table. f(0,0), f(0, 1), f(0,2) and so on...
// C[4+N+M+N*M]...C[4+N+M+(2*N*M-1)]:
// df(i,j)/dx table.
// C[4+N+M+2*N*M]...C[4+N+M+(3*N*M-1)]:
// df(i,j)/dy table.
// C[4+N+M+3*N*M]...C[4+N+M+(4*N*M-1)]:
// d2f(i,j)/dxdy table.
//
C.K := 3;
TblSize := 4+N+M+4*N*M;
SetLength(C.C, TblSize-1+1);
C.C[0] := TblSize;
C.C[1] := -3;
C.C[2] := N;
C.C[3] := M;
I:=0;
while I<=N-1 do
begin
C.C[4+I] := X[I];
Inc(I);
end;
I:=0;
while I<=M-1 do
begin
C.C[4+N+I] := Y[I];
Inc(I);
end;
BicubicCalcDerivatives(F, X, Y, M, N, DX, DY, DXY);
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
Shift := I*N+J;
C.C[4+N+M+Shift] := F[I,J];
C.C[4+N+M+N*M+Shift] := DX[I,J];
C.C[4+N+M+2*N*M+Shift] := DY[I,J];
C.C[4+N+M+3*N*M+Shift] := DXY[I,J];
Inc(J);
end;
Inc(I);
end;
end;
(*************************************************************************
This subroutine calculates the value of the bilinear or bicubic spline at
the given point X.
Input parameters:
C - coefficients table.
Built by BuildBilinearSpline or BuildBicubicSpline.
X, Y- point
Result:
S(x,y)
-- ALGLIB PROJECT --
Copyright 05.07.2007 by Bochkanov Sergey
*************************************************************************)
function Spline2DCalc(const C : Spline2DInterpolant;
X : Double;
Y : Double):Double;
var
V : Double;
VX : Double;
VY : Double;
VXY : Double;
begin
Spline2DDiff(C, X, Y, V, VX, VY, VXY);
Result := V;
end;
(*************************************************************************
This subroutine calculates the value of the bilinear or bicubic spline at
the given point X and its derivatives.
Input parameters:
C - spline interpolant.
X, Y- point
Output parameters:
F - S(x,y)
FX - dS(x,y)/dX
FY - dS(x,y)/dY
FXY - d2S(x,y)/dXdY
-- ALGLIB PROJECT --
Copyright 05.07.2007 by Bochkanov Sergey
*************************************************************************)
procedure Spline2DDiff(const C : Spline2DInterpolant;
X : Double;
Y : Double;
var F : Double;
var FX : Double;
var FY : Double;
var FXY : Double);
var
N : AlglibInteger;
M : AlglibInteger;
T : Double;
DT : Double;
U : Double;
DU : Double;
IX : AlglibInteger;
IY : AlglibInteger;
L : AlglibInteger;
R : AlglibInteger;
H : AlglibInteger;
Shift1 : AlglibInteger;
S1 : AlglibInteger;
S2 : AlglibInteger;
S3 : AlglibInteger;
S4 : AlglibInteger;
SF : AlglibInteger;
SFX : AlglibInteger;
SFY : AlglibInteger;
SFXY : AlglibInteger;
Y1 : Double;
Y2 : Double;
Y3 : Double;
Y4 : Double;
V : Double;
T0 : Double;
T1 : Double;
T2 : Double;
T3 : Double;
U0 : Double;
U1 : Double;
U2 : Double;
U3 : Double;
begin
Assert((Round(C.C[1])=-1) or (Round(C.C[1])=-3), 'Spline2DDiff: incorrect C!');
N := Round(C.C[2]);
M := Round(C.C[3]);
//
// Binary search in the [ x[0], ..., x[n-2] ] (x[n-1] is not included)
//
L := 4;
R := 4+N-2+1;
while L<>R-1 do
begin
H := (L+R) div 2;
if AP_FP_Greater_Eq(C.C[H],X) then
begin
R := H;
end
else
begin
L := H;
end;
end;
T := (X-C.C[L])/(C.C[L+1]-C.C[L]);
DT := Double(1.0)/(C.C[L+1]-C.C[L]);
IX := L-4;
//
// Binary search in the [ y[0], ..., y[m-2] ] (y[m-1] is not included)
//
L := 4+N;
R := 4+N+(M-2)+1;
while L<>R-1 do
begin
H := (L+R) div 2;
if AP_FP_Greater_Eq(C.C[H],Y) then
begin
R := H;
end
else
begin
L := H;
end;
end;
U := (Y-C.C[L])/(C.C[L+1]-C.C[L]);
DU := Double(1.0)/(C.C[L+1]-C.C[L]);
IY := L-(4+N);
//
// Prepare F, dF/dX, dF/dY, d2F/dXdY
//
F := 0;
FX := 0;
FY := 0;
FXY := 0;
//
// Bilinear interpolation
//
if Round(C.C[1])=-1 then
begin
Shift1 := 4+N+M;
Y1 := C.C[Shift1+N*IY+IX];
Y2 := C.C[Shift1+N*IY+(IX+1)];
Y3 := C.C[Shift1+N*(IY+1)+(IX+1)];
Y4 := C.C[Shift1+N*(IY+1)+IX];
F := (1-T)*(1-U)*Y1+T*(1-U)*Y2+T*U*Y3+(1-T)*U*Y4;
FX := (-(1-U)*Y1+(1-U)*Y2+U*Y3-U*Y4)*DT;
FY := (-(1-T)*Y1-T*Y2+T*Y3+(1-T)*Y4)*DU;
FXY := (Y1-Y2+Y3-Y4)*DU*DT;
Exit;
end;
//
// Bicubic interpolation
//
if Round(C.C[1])=-3 then
begin
//
// Prepare info
//
T0 := 1;
T1 := T;
T2 := AP_Sqr(T);
T3 := T*T2;
U0 := 1;
U1 := U;
U2 := AP_Sqr(U);
U3 := U*U2;
SF := 4+N+M;
SFX := 4+N+M+N*M;
SFY := 4+N+M+2*N*M;
SFXY := 4+N+M+3*N*M;
S1 := N*IY+IX;
S2 := N*IY+(IX+1);
S3 := N*(IY+1)+(IX+1);
S4 := N*(IY+1)+IX;
//
// Calculate
//
V := +1*C.C[SF+S1];
F := F+V*T0*U0;
V := +1*C.C[SFY+S1]/DU;
F := F+V*T0*U1;
FY := FY+1*V*T0*U0*DU;
V := -3*C.C[SF+S1]+3*C.C[SF+S4]-2*C.C[SFY+S1]/DU-1*C.C[SFY+S4]/DU;
F := F+V*T0*U2;
FY := FY+2*V*T0*U1*DU;
V := +2*C.C[SF+S1]-2*C.C[SF+S4]+1*C.C[SFY+S1]/DU+1*C.C[SFY+S4]/DU;
F := F+V*T0*U3;
FY := FY+3*V*T0*U2*DU;
V := +1*C.C[SFX+S1]/DT;
F := F+V*T1*U0;
FX := FX+1*V*T0*U0*DT;
V := +1*C.C[SFXY+S1]/(DT*DU);
F := F+V*T1*U1;
FX := FX+1*V*T0*U1*DT;
FY := FY+1*V*T1*U0*DU;
FXY := FXY+1*V*T0*U0*DT*DU;
V := -3*C.C[SFX+S1]/DT+3*C.C[SFX+S4]/DT-2*C.C[SFXY+S1]/(DT*DU)-1*C.C[SFXY+S4]/(DT*DU);
F := F+V*T1*U2;
FX := FX+1*V*T0*U2*DT;
FY := FY+2*V*T1*U1*DU;
FXY := FXY+2*V*T0*U1*DT*DU;
V := +2*C.C[SFX+S1]/DT-2*C.C[SFX+S4]/DT+1*C.C[SFXY+S1]/(DT*DU)+1*C.C[SFXY+S4]/(DT*DU);
F := F+V*T1*U3;
FX := FX+1*V*T0*U3*DT;
FY := FY+3*V*T1*U2*DU;
FXY := FXY+3*V*T0*U2*DT*DU;
V := -3*C.C[SF+S1]+3*C.C[SF+S2]-2*C.C[SFX+S1]/DT-1*C.C[SFX+S2]/DT;
F := F+V*T2*U0;
FX := FX+2*V*T1*U0*DT;
V := -3*C.C[SFY+S1]/DU+3*C.C[SFY+S2]/DU-2*C.C[SFXY+S1]/(DT*DU)-1*C.C[SFXY+S2]/(DT*DU);
F := F+V*T2*U1;
FX := FX+2*V*T1*U1*DT;
FY := FY+1*V*T2*U0*DU;
FXY := FXY+2*V*T1*U0*DT*DU;
V := +9*C.C[SF+S1]-9*C.C[SF+S2]+9*C.C[SF+S3]-9*C.C[SF+S4]+6*C.C[SFX+S1]/DT+3*C.C[SFX+S2]/DT-3*C.C[SFX+S3]/DT-6*C.C[SFX+S4]/DT+6*C.C[SFY+S1]/DU-6*C.C[SFY+S2]/DU-3*C.C[SFY+S3]/DU+3*C.C[SFY+S4]/DU+4*C.C[SFXY+S1]/(DT*DU)+2*C.C[SFXY+S2]/(DT*DU)+1*C.C[SFXY+S3]/(DT*DU)+2*C.C[SFXY+S4]/(DT*DU);
F := F+V*T2*U2;
FX := FX+2*V*T1*U2*DT;
FY := FY+2*V*T2*U1*DU;
FXY := FXY+4*V*T1*U1*DT*DU;
V := -6*C.C[SF+S1]+6*C.C[SF+S2]-6*C.C[SF+S3]+6*C.C[SF+S4]-4*C.C[SFX+S1]/DT-2*C.C[SFX+S2]/DT+2*C.C[SFX+S3]/DT+4*C.C[SFX+S4]/DT-3*C.C[SFY+S1]/DU+3*C.C[SFY+S2]/DU+3*C.C[SFY+S3]/DU-3*C.C[SFY+S4]/DU-2*C.C[SFXY+S1]/(DT*DU)-1*C.C[SFXY+S2]/(DT*DU)-1*C.C[SFXY+S3]/(DT*DU)-2*C.C[SFXY+S4]/(DT*DU);
F := F+V*T2*U3;
FX := FX+2*V*T1*U3*DT;
FY := FY+3*V*T2*U2*DU;
FXY := FXY+6*V*T1*U2*DT*DU;
V := +2*C.C[SF+S1]-2*C.C[SF+S2]+1*C.C[SFX+S1]/DT+1*C.C[SFX+S2]/DT;
F := F+V*T3*U0;
FX := FX+3*V*T2*U0*DT;
V := +2*C.C[SFY+S1]/DU-2*C.C[SFY+S2]/DU+1*C.C[SFXY+S1]/(DT*DU)+1*C.C[SFXY+S2]/(DT*DU);
F := F+V*T3*U1;
FX := FX+3*V*T2*U1*DT;
FY := FY+1*V*T3*U0*DU;
FXY := FXY+3*V*T2*U0*DT*DU;
V := -6*C.C[SF+S1]+6*C.C[SF+S2]-6*C.C[SF+S3]+6*C.C[SF+S4]-3*C.C[SFX+S1]/DT-3*C.C[SFX+S2]/DT+3*C.C[SFX+S3]/DT+3*C.C[SFX+S4]/DT-4*C.C[SFY+S1]/DU+4*C.C[SFY+S2]/DU+2*C.C[SFY+S3]/DU-2*C.C[SFY+S4]/DU-2*C.C[SFXY+S1]/(DT*DU)-2*C.C[SFXY+S2]/(DT*DU)-1*C.C[SFXY+S3]/(DT*DU)-1*C.C[SFXY+S4]/(DT*DU);
F := F+V*T3*U2;
FX := FX+3*V*T2*U2*DT;
FY := FY+2*V*T3*U1*DU;
FXY := FXY+6*V*T2*U1*DT*DU;
V := +4*C.C[SF+S1]-4*C.C[SF+S2]+4*C.C[SF+S3]-4*C.C[SF+S4]+2*C.C[SFX+S1]/DT+2*C.C[SFX+S2]/DT-2*C.C[SFX+S3]/DT-2*C.C[SFX+S4]/DT+2*C.C[SFY+S1]/DU-2*C.C[SFY+S2]/DU-2*C.C[SFY+S3]/DU+2*C.C[SFY+S4]/DU+1*C.C[SFXY+S1]/(DT*DU)+1*C.C[SFXY+S2]/(DT*DU)+1*C.C[SFXY+S3]/(DT*DU)+1*C.C[SFXY+S4]/(DT*DU);
F := F+V*T3*U3;
FX := FX+3*V*T2*U3*DT;
FY := FY+3*V*T3*U2*DU;
FXY := FXY+9*V*T2*U2*DT*DU;
Exit;
end;
end;
(*************************************************************************
This subroutine unpacks two-dimensional spline into the coefficients table
Input parameters:
C - spline interpolant.
Result:
M, N- grid size (x-axis and y-axis)
Tbl - coefficients table, unpacked format,
[0..(N-1)*(M-1)-1, 0..19].
For I = 0...M-2, J=0..N-2:
K = I*(N-1)+J
Tbl[K,0] = X[j]
Tbl[K,1] = X[j+1]
Tbl[K,2] = Y[i]
Tbl[K,3] = Y[i+1]
Tbl[K,4] = C00
Tbl[K,5] = C01
Tbl[K,6] = C02
Tbl[K,7] = C03
Tbl[K,8] = C10
Tbl[K,9] = C11
...
Tbl[K,19] = C33
On each grid square spline is equals to:
S(x) = SUM(c[i,j]*(x^i)*(y^j), i=0..3, j=0..3)
t = x-x[j]
u = y-y[i]
-- ALGLIB PROJECT --
Copyright 29.06.2007 by Bochkanov Sergey
*************************************************************************)
procedure Spline2DUnpack(const C : Spline2DInterpolant;
var M : AlglibInteger;
var N : AlglibInteger;
var Tbl : TReal2DArray);
var
I : AlglibInteger;
J : AlglibInteger;
CI : AlglibInteger;
CJ : AlglibInteger;
K : AlglibInteger;
P : AlglibInteger;
Shift : AlglibInteger;
S1 : AlglibInteger;
S2 : AlglibInteger;
S3 : AlglibInteger;
S4 : AlglibInteger;
SF : AlglibInteger;
SFX : AlglibInteger;
SFY : AlglibInteger;
SFXY : AlglibInteger;
Y1 : Double;
Y2 : Double;
Y3 : Double;
Y4 : Double;
DT : Double;
DU : Double;
begin
Assert((Round(C.C[1])=-3) or (Round(C.C[1])=-1), 'SplineUnpack2D: incorrect C!');
N := Round(C.C[2]);
M := Round(C.C[3]);
SetLength(Tbl, (N-1)*(M-1)-1+1, 19+1);
//
// Fill
//
I:=0;
while I<=M-2 do
begin
J:=0;
while J<=N-2 do
begin
P := I*(N-1)+J;
Tbl[P,0] := C.C[4+J];
Tbl[P,1] := C.C[4+J+1];
Tbl[P,2] := C.C[4+N+I];
Tbl[P,3] := C.C[4+N+I+1];
DT := 1/(Tbl[P,1]-Tbl[P,0]);
DU := 1/(Tbl[P,3]-Tbl[P,2]);
//
// Bilinear interpolation
//
if Round(C.C[1])=-1 then
begin
K:=4;
while K<=19 do
begin
Tbl[P,K] := 0;
Inc(K);
end;
Shift := 4+N+M;
Y1 := C.C[Shift+N*I+J];
Y2 := C.C[Shift+N*I+(J+1)];
Y3 := C.C[Shift+N*(I+1)+(J+1)];
Y4 := C.C[Shift+N*(I+1)+J];
Tbl[P,4] := Y1;
Tbl[P,4+1*4+0] := Y2-Y1;
Tbl[P,4+0*4+1] := Y4-Y1;
Tbl[P,4+1*4+1] := Y3-Y2-Y4+Y1;
end;
//
// Bicubic interpolation
//
if Round(C.C[1])=-3 then
begin
SF := 4+N+M;
SFX := 4+N+M+N*M;
SFY := 4+N+M+2*N*M;
SFXY := 4+N+M+3*N*M;
S1 := N*I+J;
S2 := N*I+(J+1);
S3 := N*(I+1)+(J+1);
S4 := N*(I+1)+J;
Tbl[P,4+0*4+0] := +1*C.C[SF+S1];
Tbl[P,4+0*4+1] := +1*C.C[SFY+S1]/DU;
Tbl[P,4+0*4+2] := -3*C.C[SF+S1]+3*C.C[SF+S4]-2*C.C[SFY+S1]/DU-1*C.C[SFY+S4]/DU;
Tbl[P,4+0*4+3] := +2*C.C[SF+S1]-2*C.C[SF+S4]+1*C.C[SFY+S1]/DU+1*C.C[SFY+S4]/DU;
Tbl[P,4+1*4+0] := +1*C.C[SFX+S1]/DT;
Tbl[P,4+1*4+1] := +1*C.C[SFXY+S1]/(DT*DU);
Tbl[P,4+1*4+2] := -3*C.C[SFX+S1]/DT+3*C.C[SFX+S4]/DT-2*C.C[SFXY+S1]/(DT*DU)-1*C.C[SFXY+S4]/(DT*DU);
Tbl[P,4+1*4+3] := +2*C.C[SFX+S1]/DT-2*C.C[SFX+S4]/DT+1*C.C[SFXY+S1]/(DT*DU)+1*C.C[SFXY+S4]/(DT*DU);
Tbl[P,4+2*4+0] := -3*C.C[SF+S1]+3*C.C[SF+S2]-2*C.C[SFX+S1]/DT-1*C.C[SFX+S2]/DT;
Tbl[P,4+2*4+1] := -3*C.C[SFY+S1]/DU+3*C.C[SFY+S2]/DU-2*C.C[SFXY+S1]/(DT*DU)-1*C.C[SFXY+S2]/(DT*DU);
Tbl[P,4+2*4+2] := +9*C.C[SF+S1]-9*C.C[SF+S2]+9*C.C[SF+S3]-9*C.C[SF+S4]+6*C.C[SFX+S1]/DT+3*C.C[SFX+S2]/DT-3*C.C[SFX+S3]/DT-6*C.C[SFX+S4]/DT+6*C.C[SFY+S1]/DU-6*C.C[SFY+S2]/DU-3*C.C[SFY+S3]/DU+3*C.C[SFY+S4]/DU+4*C.C[SFXY+S1]/(DT*DU)+2*C.C[SFXY+S2]/(DT*DU)+1*C.C[SFXY+S3]/(DT*DU)+2*C.C[SFXY+S4]/(DT*DU);
Tbl[P,4+2*4+3] := -6*C.C[SF+S1]+6*C.C[SF+S2]-6*C.C[SF+S3]+6*C.C[SF+S4]-4*C.C[SFX+S1]/DT-2*C.C[SFX+S2]/DT+2*C.C[SFX+S3]/DT+4*C.C[SFX+S4]/DT-3*C.C[SFY+S1]/DU+3*C.C[SFY+S2]/DU+3*C.C[SFY+S3]/DU-3*C.C[SFY+S4]/DU-2*C.C[SFXY+S1]/(DT*DU)-1*C.C[SFXY+S2]/(DT*DU)-1*C.C[SFXY+S3]/(DT*DU)-2*C.C[SFXY+S4]/(DT*DU);
Tbl[P,4+3*4+0] := +2*C.C[SF+S1]-2*C.C[SF+S2]+1*C.C[SFX+S1]/DT+1*C.C[SFX+S2]/DT;
Tbl[P,4+3*4+1] := +2*C.C[SFY+S1]/DU-2*C.C[SFY+S2]/DU+1*C.C[SFXY+S1]/(DT*DU)+1*C.C[SFXY+S2]/(DT*DU);
Tbl[P,4+3*4+2] := -6*C.C[SF+S1]+6*C.C[SF+S2]-6*C.C[SF+S3]+6*C.C[SF+S4]-3*C.C[SFX+S1]/DT-3*C.C[SFX+S2]/DT+3*C.C[SFX+S3]/DT+3*C.C[SFX+S4]/DT-4*C.C[SFY+S1]/DU+4*C.C[SFY+S2]/DU+2*C.C[SFY+S3]/DU-2*C.C[SFY+S4]/DU-2*C.C[SFXY+S1]/(DT*DU)-2*C.C[SFXY+S2]/(DT*DU)-1*C.C[SFXY+S3]/(DT*DU)-1*C.C[SFXY+S4]/(DT*DU);
Tbl[P,4+3*4+3] := +4*C.C[SF+S1]-4*C.C[SF+S2]+4*C.C[SF+S3]-4*C.C[SF+S4]+2*C.C[SFX+S1]/DT+2*C.C[SFX+S2]/DT-2*C.C[SFX+S3]/DT-2*C.C[SFX+S4]/DT+2*C.C[SFY+S1]/DU-2*C.C[SFY+S2]/DU-2*C.C[SFY+S3]/DU+2*C.C[SFY+S4]/DU+1*C.C[SFXY+S1]/(DT*DU)+1*C.C[SFXY+S2]/(DT*DU)+1*C.C[SFXY+S3]/(DT*DU)+1*C.C[SFXY+S4]/(DT*DU);
end;
//
// Rescale Cij
//
CI:=0;
while CI<=3 do
begin
CJ:=0;
while CJ<=3 do
begin
Tbl[P,4+CI*4+CJ] := Tbl[P,4+CI*4+CJ]*Power(DT, CI)*Power(DU, CJ);
Inc(CJ);
end;
Inc(CI);
end;
Inc(J);
end;
Inc(I);
end;
end;
(*************************************************************************
This subroutine performs linear transformation of the spline argument.
Input parameters:
C - spline interpolant
AX, BX - transformation coefficients: x = A*t + B
AY, BY - transformation coefficients: y = A*u + B
Result:
C - transformed spline
-- ALGLIB PROJECT --
Copyright 30.06.2007 by Bochkanov Sergey
*************************************************************************)
procedure Spline2DLinTransXY(var C : Spline2DInterpolant;
AX : Double;
BX : Double;
AY : Double;
BY : Double);
var
I : AlglibInteger;
J : AlglibInteger;
N : AlglibInteger;
M : AlglibInteger;
V : Double;
X : TReal1DArray;
Y : TReal1DArray;
F : TReal2DArray;
TypeC : AlglibInteger;
begin
TypeC := Round(C.C[1]);
Assert((TypeC=-3) or (TypeC=-1), 'Spline2DLinTransXY: incorrect C!');
N := Round(C.C[2]);
M := Round(C.C[3]);
SetLength(X, N-1+1);
SetLength(Y, M-1+1);
SetLength(F, M-1+1, N-1+1);
J:=0;
while J<=N-1 do
begin
X[J] := C.C[4+J];
Inc(J);
end;
I:=0;
while I<=M-1 do
begin
Y[I] := C.C[4+N+I];
Inc(I);
end;
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
F[I,J] := C.C[4+N+M+I*N+J];
Inc(J);
end;
Inc(I);
end;
//
// Special case: AX=0 or AY=0
//
if AP_FP_Eq(AX,0) then
begin
I:=0;
while I<=M-1 do
begin
V := Spline2DCalc(C, BX, Y[I]);
J:=0;
while J<=N-1 do
begin
F[I,J] := V;
Inc(J);
end;
Inc(I);
end;
if TypeC=-3 then
begin
Spline2DBuildBicubic(X, Y, F, M, N, C);
end;
if TypeC=-1 then
begin
Spline2DBuildBilinear(X, Y, F, M, N, C);
end;
AX := 1;
BX := 0;
end;
if AP_FP_Eq(AY,0) then
begin
J:=0;
while J<=N-1 do
begin
V := Spline2DCalc(C, X[J], BY);
I:=0;
while I<=M-1 do
begin
F[I,J] := V;
Inc(I);
end;
Inc(J);
end;
if TypeC=-3 then
begin
Spline2DBuildBicubic(X, Y, F, M, N, C);
end;
if TypeC=-1 then
begin
Spline2DBuildBilinear(X, Y, F, M, N, C);
end;
AY := 1;
BY := 0;
end;
//
// General case: AX<>0, AY<>0
// Unpack, scale and pack again.
//
J:=0;
while J<=N-1 do
begin
X[J] := (X[J]-BX)/AX;
Inc(J);
end;
I:=0;
while I<=M-1 do
begin
Y[I] := (Y[I]-BY)/AY;
Inc(I);
end;
if TypeC=-3 then
begin
Spline2DBuildBicubic(X, Y, F, M, N, C);
end;
if TypeC=-1 then
begin
Spline2DBuildBilinear(X, Y, F, M, N, C);
end;
end;
(*************************************************************************
This subroutine performs linear transformation of the spline.
Input parameters:
C - spline interpolant.
A, B- transformation coefficients: S2(x,y) = A*S(x,y) + B
Output parameters:
C - transformed spline
-- ALGLIB PROJECT --
Copyright 30.06.2007 by Bochkanov Sergey
*************************************************************************)
procedure Spline2DLinTransF(var C : Spline2DInterpolant;
A : Double;
B : Double);
var
I : AlglibInteger;
J : AlglibInteger;
N : AlglibInteger;
M : AlglibInteger;
X : TReal1DArray;
Y : TReal1DArray;
F : TReal2DArray;
TypeC : AlglibInteger;
begin
TypeC := Round(C.C[1]);
Assert((TypeC=-3) or (TypeC=-1), 'Spline2DLinTransXY: incorrect C!');
N := Round(C.C[2]);
M := Round(C.C[3]);
SetLength(X, N-1+1);
SetLength(Y, M-1+1);
SetLength(F, M-1+1, N-1+1);
J:=0;
while J<=N-1 do
begin
X[J] := C.C[4+J];
Inc(J);
end;
I:=0;
while I<=M-1 do
begin
Y[I] := C.C[4+N+I];
Inc(I);
end;
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
F[I,J] := A*C.C[4+N+M+I*N+J]+B;
Inc(J);
end;
Inc(I);
end;
if TypeC=-3 then
begin
Spline2DBuildBicubic(X, Y, F, M, N, C);
end;
if TypeC=-1 then
begin
Spline2DBuildBilinear(X, Y, F, M, N, C);
end;
end;
(*************************************************************************
This subroutine makes the copy of the spline model.
Input parameters:
C - spline interpolant
Output parameters:
CC - spline copy
-- ALGLIB PROJECT --
Copyright 29.06.2007 by Bochkanov Sergey
*************************************************************************)
procedure Spline2DCopy(const C : Spline2DInterpolant;
var CC : Spline2DInterpolant);
var
N : AlglibInteger;
begin
Assert((C.K=1) or (C.K=3), 'Spline2DCopy: incorrect C!');
CC.K := C.K;
N := Round(C.C[0]);
SetLength(CC.C, N);
APVMove(@CC.C[0], 0, N-1, @C.C[0], 0, N-1);
end;
(*************************************************************************
Serialization of the spline interpolant
INPUT PARAMETERS:
B - spline interpolant
OUTPUT PARAMETERS:
RA - array of real numbers which contains interpolant,
array[0..RLen-1]
RLen - RA lenght
-- ALGLIB --
Copyright 17.08.2009 by Bochkanov Sergey
*************************************************************************)
procedure Spline2DSerialize(const C : Spline2DInterpolant;
var RA : TReal1DArray;
var RALen : AlglibInteger);
var
CLen : AlglibInteger;
begin
Assert((C.K=1) or (C.K=3), 'Spline2DSerialize: incorrect C!');
CLen := Round(C.C[0]);
RALen := 3+CLen;
SetLength(RA, RALen);
RA[0] := RALen;
RA[1] := Spline2DVNum;
RA[2] := C.K;
APVMove(@RA[0], 3, 3+CLen-1, @C.C[0], 0, CLen-1);
end;
(*************************************************************************
Unserialization of the spline interpolant
INPUT PARAMETERS:
RA - array of real numbers which contains interpolant,
OUTPUT PARAMETERS:
B - spline interpolant
-- ALGLIB --
Copyright 17.08.2009 by Bochkanov Sergey
*************************************************************************)
procedure Spline2DUnserialize(const RA : TReal1DArray;
var C : Spline2DInterpolant);
var
CLen : AlglibInteger;
begin
Assert(Round(RA[1])=Spline2DVNum, 'Spline2DUnserialize: corrupted array!');
C.K := Round(RA[2]);
CLen := Round(RA[3]);
SetLength(C.C, CLen);
APVMove(@C.C[0], 0, CLen-1, @RA[0], 3, 3+CLen-1);
end;
(*************************************************************************
Bicubic spline resampling
Input parameters:
A - function values at the old grid,
array[0..OldHeight-1, 0..OldWidth-1]
OldHeight - old grid height, OldHeight>1
OldWidth - old grid width, OldWidth>1
NewHeight - new grid height, NewHeight>1
NewWidth - new grid width, NewWidth>1
Output parameters:
B - function values at the new grid,
array[0..NewHeight-1, 0..NewWidth-1]
-- ALGLIB routine --
15 May, 2007
Copyright by Bochkanov Sergey
*************************************************************************)
procedure Spline2DResampleBicubic(const A : TReal2DArray;
OldHeight : AlglibInteger;
OldWidth : AlglibInteger;
var B : TReal2DArray;
NewHeight : AlglibInteger;
NewWidth : AlglibInteger);
var
Buf : TReal2DArray;
X : TReal1DArray;
Y : TReal1DArray;
C : Spline1DInterpolant;
I : AlglibInteger;
J : AlglibInteger;
MW : AlglibInteger;
MH : AlglibInteger;
begin
Assert((OldWidth>1) and (OldHeight>1), 'Spline2DResampleBicubic: width/height less than 1');
Assert((NewWidth>1) and (NewHeight>1), 'Spline2DResampleBicubic: width/height less than 1');
//
// Prepare
//
MW := Max(OldWidth, NewWidth);
MH := Max(OldHeight, NewHeight);
SetLength(B, NewHeight-1+1, NewWidth-1+1);
SetLength(Buf, OldHeight-1+1, NewWidth-1+1);
SetLength(X, Max(MW, MH)-1+1);
SetLength(Y, Max(MW, MH)-1+1);
//
// Horizontal interpolation
//
I:=0;
while I<=OldHeight-1 do
begin
//
// Fill X, Y
//
J:=0;
while J<=OldWidth-1 do
begin
X[J] := AP_Double(J)/(OldWidth-1);
Y[J] := A[I,J];
Inc(J);
end;
//
// Interpolate and place result into temporary matrix
//
Spline1DBuildCubic(X, Y, OldWidth, 0, Double(0.0), 0, Double(0.0), C);
J:=0;
while J<=NewWidth-1 do
begin
Buf[I,J] := Spline1DCalc(C, AP_Double(J)/(NewWidth-1));
Inc(J);
end;
Inc(I);
end;
//
// Vertical interpolation
//
J:=0;
while J<=NewWidth-1 do
begin
//
// Fill X, Y
//
I:=0;
while I<=OldHeight-1 do
begin
X[I] := AP_Double(I)/(OldHeight-1);
Y[I] := Buf[I,J];
Inc(I);
end;
//
// Interpolate and place result into B
//
Spline1DBuildCubic(X, Y, OldHeight, 0, Double(0.0), 0, Double(0.0), C);
I:=0;
while I<=NewHeight-1 do
begin
B[I,J] := Spline1DCalc(C, AP_Double(I)/(NewHeight-1));
Inc(I);
end;
Inc(J);
end;
end;
(*************************************************************************
Bilinear spline resampling
Input parameters:
A - function values at the old grid,
array[0..OldHeight-1, 0..OldWidth-1]
OldHeight - old grid height, OldHeight>1
OldWidth - old grid width, OldWidth>1
NewHeight - new grid height, NewHeight>1
NewWidth - new grid width, NewWidth>1
Output parameters:
B - function values at the new grid,
array[0..NewHeight-1, 0..NewWidth-1]
-- ALGLIB routine --
09.07.2007
Copyright by Bochkanov Sergey
*************************************************************************)
procedure Spline2DResampleBilinear(const A : TReal2DArray;
OldHeight : AlglibInteger;
OldWidth : AlglibInteger;
var B : TReal2DArray;
NewHeight : AlglibInteger;
NewWidth : AlglibInteger);
var
I : AlglibInteger;
J : AlglibInteger;
L : AlglibInteger;
C : AlglibInteger;
T : Double;
U : Double;
begin
SetLength(B, NewHeight-1+1, NewWidth-1+1);
I:=0;
while I<=NewHeight-1 do
begin
J:=0;
while J<=NewWidth-1 do
begin
L := I*(OldHeight-1) div (NewHeight-1);
if L=OldHeight-1 then
begin
L := OldHeight-2;
end;
U := AP_Double(I)/(NewHeight-1)*(OldHeight-1)-L;
C := J*(OldWidth-1) div (NewWidth-1);
if C=OldWidth-1 then
begin
C := OldWidth-2;
end;
T := AP_Double(J*(OldWidth-1))/(NewWidth-1)-C;
B[I,J] := (1-T)*(1-U)*A[L,C]+T*(1-U)*A[L,C+1]+T*U*A[L+1,C+1]+(1-T)*U*A[L+1,C];
Inc(J);
end;
Inc(I);
end;
end;
(*************************************************************************
Internal subroutine.
Calculation of the first derivatives and the cross-derivative.
*************************************************************************)
procedure BicubicCalcDerivatives(const A : TReal2DArray;
const X : TReal1DArray;
const Y : TReal1DArray;
M : AlglibInteger;
N : AlglibInteger;
var DX : TReal2DArray;
var DY : TReal2DArray;
var DXY : TReal2DArray);
var
I : AlglibInteger;
J : AlglibInteger;
XT : TReal1DArray;
FT : TReal1DArray;
C : TReal1DArray;
S : Double;
DS : Double;
D2S : Double;
begin
SetLength(DX, M-1+1, N-1+1);
SetLength(DY, M-1+1, N-1+1);
SetLength(DXY, M-1+1, N-1+1);
//
// dF/dX
//
SetLength(XT, N-1+1);
SetLength(FT, N-1+1);
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
XT[J] := X[J];
FT[J] := A[I,J];
Inc(J);
end;
BuildCubicSpline(XT, FT, N, 0, Double(0.0), 0, Double(0.0), C);
J:=0;
while J<=N-1 do
begin
SplineDifferentiation(C, X[J], S, DS, D2S);
DX[I,J] := DS;
Inc(J);
end;
Inc(I);
end;
//
// dF/dY
//
SetLength(XT, M-1+1);
SetLength(FT, M-1+1);
J:=0;
while J<=N-1 do
begin
I:=0;
while I<=M-1 do
begin
XT[I] := Y[I];
FT[I] := A[I,J];
Inc(I);
end;
BuildCubicSpline(XT, FT, M, 0, Double(0.0), 0, Double(0.0), C);
I:=0;
while I<=M-1 do
begin
SplineDifferentiation(C, Y[I], S, DS, D2S);
DY[I,J] := DS;
Inc(I);
end;
Inc(J);
end;
//
// d2F/dXdY
//
SetLength(XT, N-1+1);
SetLength(FT, N-1+1);
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
XT[J] := X[J];
FT[J] := DY[I,J];
Inc(J);
end;
BuildCubicSpline(XT, FT, N, 0, Double(0.0), 0, Double(0.0), C);
J:=0;
while J<=N-1 do
begin
SplineDifferentiation(C, X[J], S, DS, D2S);
DXY[I,J] := DS;
Inc(J);
end;
Inc(I);
end;
end;
end. |
unit TaxCorrectiveTest;
interface
uses dbTest, dbMovementTest, ObjectTest;
type
TTaxCorrectiveTest = class (TdbMovementTestNew)
published
procedure ProcedureLoad; override;
procedure Test; override;
end;
TTaxCorrective = class(TMovementTest)
private
function InsertDefault: integer; override;
public
function InsertUpdateTaxCorrective(Id: Integer; InvNumber, InvNumberPartner,InvNumberBranch: String; OperDate: TDateTime;
Checked, Document, PriceWithVAT: Boolean;
VATPercent: double;
FromId, ToId, PartnerId, ContractId, DocumentTaxKindId: Integer
): integer;
constructor Create; override;
end;
implementation
uses UtilConst, dbObjectMeatTest, JuridicalTest, DocumentTaxKindTest,
dbObjectTest, SysUtils, Db, TestFramework, PartnerTest, Contracttest;
{ TTaxCorrective }
constructor TTaxCorrective.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_Movement_TaxCorrective';
spSelect := 'gpSelect_Movement_TaxCorrective';
spGet := 'gpGet_Movement_TaxCorrective';
end;
function TTaxCorrective.InsertDefault: integer;
var Id: Integer;
InvNumber,InvNumberPartner,InvNumberBranch: String;
OperDate: TDateTime;
Checked, Document, PriceWithVAT: Boolean;
VATPercent: double;
FromId, ToId, PartnerId, ContractId, DocumentTaxKindId : Integer;
begin
Id:=0;
InvNumber:='1';
InvNumberPartner:='123';
InvNumberBranch:='456';
OperDate:= Date;
Checked:=true;
Document:=true;
PriceWithVAT:=true;
VATPercent:=20;
FromId := TJuridical.Create.GetDefault;
ToId :=TJuridical.Create.GetDefault;
PartnerId := TPartner.Create.GetDefault;
DocumentTaxKindId := TDocumentTaxKind.Create.GetDefault;
ContractId := TContract.Create.GetDefault;
result := InsertUpdateTaxCorrective(Id, InvNumber, InvNumberPartner,InvNumberBranch, OperDate,
Checked, Document, PriceWithVAT,
VATPercent,
FromId, ToId, PartnerId, ContractId, DocumentTaxKindId);
end;
function TTaxCorrective.InsertUpdateTaxCorrective(Id: Integer; InvNumber, InvNumberPartner,InvNumberBranch: String; OperDate: TDateTime;
Checked, Document, PriceWithVAT: Boolean;
VATPercent: double;
FromId, ToId, PartnerId, ContractId, DocumentTaxKindId: Integer
): integer;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inInvNumber', ftString, ptInput, InvNumber);
FParams.AddParam('inInvNumberPartner', ftString, ptInput, InvNumber);
FParams.AddParam('inInvNumberBranch', ftString, ptInput, InvNumberBranch);
FParams.AddParam('inOperDate', ftDateTime, ptInput, OperDate);
FParams.AddParam('inChecked', ftBoolean, ptInput, Checked);
FParams.AddParam('inDocument', ftBoolean, ptInput, Document);
FParams.AddParam('inPriceWithVAT', ftBoolean, ptInput, PriceWithVAT);
FParams.AddParam('inVATPercent', ftFloat, ptInput, VATPercent);
FParams.AddParam('inFromId', ftInteger, ptInput, FromId);
FParams.AddParam('inToId', ftInteger, ptInput, ToId);
FParams.AddParam('inPartnerId', ftInteger, ptInput, PartnerId);
FParams.AddParam('inContractId', ftInteger, ptInput, ContractId);
FParams.AddParam('inDocumentTaxKindId', ftInteger, ptInput, DocumentTaxKindId);
result := InsertUpdate(FParams);
end;
{ TTaxCorrectiveTest }
procedure TTaxCorrectiveTest.ProcedureLoad;
begin
ScriptDirectory := ProcedurePath + 'Movement\TaxCorrective\';
inherited;
ScriptDirectory := ProcedurePath + 'MovementItem\TaxCorrective\';
inherited;
ScriptDirectory := ProcedurePath + 'MovementItemContainer\TaxCorrective\';
inherited;
end;
procedure TTaxCorrectiveTest.Test;
var MovementTaxCorrective: TTaxCorrective;
Id: Integer;
begin
inherited;
// Создаем документ
MovementTaxCorrective := TTaxCorrective.Create;
Id := MovementTaxCorrective.InsertDefault;
// создание документа
try
// редактирование
finally
MovementTaxCorrective.Delete(Id);
end;
end;
initialization
TestFramework.RegisterTest('Документы', TTaxCorrectiveTest.Suite);
end.
|
unit JsonHelperCore;
{- Unit Info----------------------------------------------------------------------------
Unit Name : JsonHelperCore
Created By : Barış Atalay 28/10/2014
Last Change By :
Web Site: http://brsatalay.blogspot.com.tr/
Notes:
----------------------------------------------------------------------------------------}
interface
Uses
System.Classes,System.SysUtils,
Generics.Collections,
FMX.Listbox,FMX.Forms,
XSuperObject,
IdHttp;
const
NotActive = 'JSON Helper not is not active!';
NoItem = 'Items not found!';
FieldName = 'Field name must not be null!';
NoJson = 'Unsupported json format! Must JSON Array like this [{..},{..}]';
NoWhere = 'Unsupported where clause! Must where clause like this ''manga:"naruto", aktive:0 ... ''';
DataNull = 'Response data is null.';
HT = 'http';
VA = 'Value';
NullLJson = 'JSON is null!';
NotSort = 'Is not sort able';
type
TJSONHelper = class;
TJSONHelper = class(TComponent)
private
FTimeOut: Integer;
FActive: Boolean;
WhereJSON,
FData: ISuperObject;
FFieldObject: TObjectList<TDictionary<String,Variant>>;
FValues: TDictionary<String,Variant>;
FIndex: Integer;
SFList: String;
FSortField: String;
FJSON: TStringList;
FOwner: TForm;
procedure SetActive(const Value: Boolean);
procedure Get;
function GetFieldBy(const Name: String): Variant;
procedure SetRaise(T:String);
procedure SetFieldBy(const Name: String; const Value: Variant);
function GetCount: Integer;
function SAGet: String;
function SFGet: String;
procedure SFSet(const Value: String);
procedure AktifKontrol;
procedure DoSort;
function GetsJSON: TStringList;
procedure SetJSON(const Value: TStringList);
procedure Where(Params: String);
function AradanSec( text, ilk, son:String ): String;
function ClearAbidikGubidik(Text, ClearItem: String): String;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure First;
procedure Last;
function EOF:Boolean;
function BOF: Boolean;
procedure Next;
procedure Previous;
function GetJson:String;
property Count: Integer read GetCount;
property FieldByName[const Name: String] : Variant read GetFieldBy write SetFieldBy;
property RecNo: Integer read FIndex write FIndex;
procedure SaveFile(AFile: String);
function FromFile(AFile: String): String;
published
property JSON: TStringList read GetsJSON write SetJSON ;
property Active: Boolean read FActive write SetActive;
property TimeOut: Integer read FTimeOut write FTimeOut;
property SortAble: String read SAGet;
property SortField: String read SFGet write SFSet;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Android', [TJsonHelper]);
end;
{ TMangaCore }
procedure TJSONHelper.AktifKontrol;
begin
if not FActive then SetRaise(NotActive);
end;
function TJSONHelper.AradanSec(text, ilk, son: String): String;
begin
Delete(Text, 1, pos(ilk, Text) + Length(ilk)-1);
Result := Copy(Text, 1, Pos(Son, Text)-1);
end;
function TJsonHelper.BOF: Boolean;
begin
AktifKontrol;
Result := False;
if FIndex = 0 then
Result := True
else if FIndex > 0 then
Result := False;
end;
function TJSONHelper.ClearAbidikGubidik(Text, ClearItem: String): String;
begin
Result := Text;
StringReplace(Result, ClearItem, '', [rfReplaceAll,rfIgnoreCase]);
end;
constructor TJsonHelper.Create(AOwner: TComponent);
begin
inherited;
FOwner := AOwner as TForm;
FTimeOut := 5000;
FFieldObject := TObjectList<TDictionary<String,Variant>>.Create;
FJSON := TStringList.Create;
end;
destructor TJsonHelper.Destroy;
begin
FJSON.Free;
FFieldObject.Free;
// FValues.Free; 06.01.2015
inherited;
end;
procedure TJSONHelper.DoSort;
var
AMember,
OMember: IMember;
begin
if Trim(FSortField) <> '' then
FData.A[VA].Sort(function(const Left, Right: ICast): Integer begin //SORT OLAYI BRADA
Result := CompareText(Left.AsObject.S[FSortField], Right.AsObject.S[FSortField]);
end);
FFieldObject.Clear;
for AMember in FData.A[VA] do
begin
FValues := TDictionary<String,Variant>.Create;
for OMember in AMember.AsObject do
FValues.Add(OMember.Name,OMember.AsString);
FFieldObject.Add(FValues);
end;
First;
end;
function TJsonHelper.EOF: Boolean;
begin
AktifKontrol;
Result := False;
if FIndex = FFieldObject.Count + 1 then
begin
Result := True;
Dec(FIndex);
end else
if FIndex < FFieldObject.Count then
Result := False;
end;
procedure TJsonHelper.First;
begin
FIndex := 1;
end;
function TJSONHelper.FromFile(AFile: String): String;
{$REGION 'ParseStream'}
function ParseStream(Stream: TStream): String;
var
Strm: TStringStream;
begin
Strm := TStringStream.Create;
try
Strm.LoadFromStream(Stream);
Result := Strm.DataString ;
finally
Strm.Free;
end;
end;
{$ENDREGION}
var
Strm: TFileStream;
begin
Strm := TFileStream.Create(AFile, fmOpenRead, fmShareDenyWrite);
try
Result := ParseStream(Strm);
finally
Strm.Free;
end;
end;
procedure TJsonHelper.Get;
var
T: String;
AMember,
OMember: IMember;
Q: Integer;
begin
AktifKontrol;
with TIdHTTP.Create(nil) do
begin
try
ConnectTimeout := FTimeOut;
ReadTimeout := FTimeOut;
T := Copy(Trim(FJSON.Text),1,6);
if Pos(HT,T) > 0 then
begin
T := Get(Trim(FJSON.text));
if Pos('<body>',T) > 0 then
begin
T := String(AradanSec(T,'<body>','</body>'));
T := StringReplace(trim(T), '#$A', '', [rfReplaceAll]);
end;
if T.Trim = '' then
SetRaise(DataNull);
end else
T := FJSON.Text;
finally
Disconnect;
Free;
end;
end;
FIndex := 1;
{$IFDEF ANDROID}
if (T[0] <> '[') and (T[Length(T)] <> ']') then
SetRaise(NoJson);
{$ELSE}
if (T[1] <> '[') and (T[Length(T)] <> ']') then
SetRaise(NoJson);
{$ENDIF}
T := '{ "' + VA + '":' + T;
T := T + '}';
if Pos('#$D',T) > 0 then
T := T.Replace(#$D, '\r');
if Pos('#$A',T) > 0 then
T := T.Replace(#$D, '\r');
FData := SO(T{.Replace(#$D, '\r').Replace(#$A, '\n')});
Q := 0;
for AMember in FData.A[VA] do
begin
if Q = 1 then Break;
for OMember in AMember.AsObject do
begin
if not SFList.IsEmpty then SFList := SFList + ',';
SFList := SFList + OMember.Name;
end;
Inc(Q);
end;
DoSort;
end;
function TJsonHelper.GetCount: Integer;
begin
Result := FFieldObject.Count;
end;
function TJsonHelper.GetFieldBy(const Name: String): Variant;
begin
AktifKontrol;
Result := '';
if Trim(Name) = '' then
SetRaise(FieldName);
if (FFieldObject.Count) < FIndex then
SetRaise(NoItem);
Result := FFieldObject.Items[FIndex - 1].Items[Name];
end;
function TJSONHelper.GetJSON: String;
var
X:ISuperArray;
XY:ISuperObject;
K,
I: Integer;
Key: String;
begin
X := SA;
with FFieldObject do
begin
for I := 0 to Count -1 do
begin
XY := SO;
for Key in Items[I].Keys do
XY.S[Key]:= Items[I].Items[Key];
X.Add(XY);
end;
end;
Result := X.AsJSON;
end;
function TJSONHelper.GetsJSON: TStringList;
begin
Result := FJSON;
end;
procedure TJsonHelper.Last;
begin
AktifKontrol;
FIndex := FFieldObject.Count - 1 ;
end;
procedure TJsonHelper.Next;
begin
AktifKontrol;
if FIndex <= FFieldObject.Count then
Inc(FIndex);
end;
procedure TJsonHelper.Previous;
begin
AktifKontrol;
if 1 < FIndex then
Dec(FIndex);
end;
function TJSONHelper.SAGet: String;
begin
Result := SFList;
end;
procedure TJSONHelper.SaveFile(AFile: String);
var
X: ISuperArray;
begin
X := SA(GetJSON);
X.SaveTo(AFile);
end;
procedure TJsonHelper.SetActive(const Value: Boolean);
begin
FActive := Value;
if Value = True then
begin
if Trim(FJSON.Text) = '' then
begin
SetRaise(NullLJson);
FSortField := '';
SFList := '';
Exit;
end;
Get;
end else
begin
FFieldObject.Clear;
FSortField := '';
SFList := '';
end;
end;
procedure TJsonHelper.SetFieldBy(const Name: String; const Value: Variant);
begin
if Trim(Name) = '' then
SetRaise(FieldName );
if (FFieldObject.Count) < FIndex then
SetRaise(NoItem);
FFieldObject.Items[FIndex - 1].Items[Name] := Value;
end;
procedure TJSONHelper.SetJSON(const Value: TStringList);
begin
FJSON.Clear;
FJSON.Assign(Value);
end;
procedure TJsonHelper.SetRaise(T: String);
begin
raise Exception.Create(T);
end;
function TJSONHelper.SFGet: String;
begin
Result := FSortField;
end;
procedure TJSONHelper.SFSet(const Value: String);
begin
if (Pos(Value,SFList) = 0) and not (Trim(Value) = '') then
SetRaise(NotSort);
FSortField := Value;
DoSort;
end;
procedure TJSONHelper.Where(Params: String);//Example manga: "naruto" , ....
var
AMember: IMember;
X: ISuperObject;
begin
try
Params := '{ ' + Params;
Params := Params + ' }';
X := SO(Params);
for AMember in X do
AMember.AsString;
finally
SetRaise(NoWhere);
end;
end;
end.
|
unit uPesquisa;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Data.DB,
ZAbstractRODataset, ZAbstractDataset, ZDataset, Vcl.Grids, Vcl.DBGrids,
RDprint, Vcl.Imaging.pngimage, Vcl.ExtCtrls, System.ImageList, Vcl.ImgList,
PngImageList, Vcl.ComCtrls, Vcl.ToolWin;
type
TfrmPesquisa = class(TForm)
edtCodigo: TEdit;
edtDescricao: TEdit;
lblCodigo: TLabel;
lblDescricao: TLabel;
DBGrid1: TDBGrid;
ToolBar1: TToolBar;
btnVoltar: TToolButton;
btnVisualizar: TToolButton;
btnPesquisar: TToolButton;
btnImprimir: TToolButton;
btnPrint: TToolButton;
PngImageList1: TPngImageList;
Panel1: TPanel;
lblRegistro: TLabel;
Bevel1: TBevel;
Label1: TLabel;
procedure btnVoltarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure btnVisualizarClick(Sender: TObject);
procedure btnImprimirClick(Sender: TObject);
procedure btnPrintClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure FormPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmPesquisa: TfrmPesquisa;
implementation
{$R *.dfm}
uses uCadastro, uRelatorio, uDm, Controls;
//Botão Imprimir
procedure TfrmPesquisa.btnImprimirClick(Sender: TObject);
begin
Tcontrols.BotaoImprimir();
end;
//Botão Pesquisar
procedure TfrmPesquisa.btnPesquisarClick(Sender: TObject);
begin
Tcontrols.BotaoPesquisar2(edtCodigo.Text ,edtdescricao.Text);
edtCodigo.Clear;
edtDescricao.Clear;
end;
// Botão Visualizar
procedure TfrmPesquisa.btnVisualizarClick(Sender: TObject);
begin
Tcontrols.BotaoVisualizar;
Tcontrols.SetVoltarOuVisualizar(true);
end;
//Botão Voltar
procedure TfrmPesquisa.btnVoltarClick(Sender: TObject);
begin
Tcontrols.SetVoltarOuVisualizar(false);
Tcontrols.BotaoVoltar2;
end;
//Zebrar DBGrid
procedure TfrmPesquisa.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
Tcontrols.ZebrarDBGrid(Sender, Rect,DataCol, column, state);
end;
// Botão Print
procedure TfrmPesquisa.btnPrintClick(Sender: TObject);
begin
Tcontrols.BotaoPrint;
end;
procedure TfrmPesquisa.FormCreate(Sender: TObject);
begin
DBGrid1.Columns[0].Width := -1;
DBGrid1.Columns[1].Width := 100;
DBGrid1.Columns[2].Width := 440;
end;
//Teclas de atalho
procedure TfrmPesquisa.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
Tcontrols.TeclasAtalhos2(key);
end;
//Selecionar numero de registros do banco de dados
procedure TfrmPesquisa.FormPaint(Sender: TObject);
begin
lblRegistro.Caption := inttostr(DBGrid1.DataSource.DataSet.RecordCount);
end;
// Exibindo o Formulário
procedure TfrmPesquisa.FormShow(Sender: TObject);
begin
Tcontrols.CriacaoForm;
end;
end.
|
unit LoadFarmacyReportTest;
interface
uses
TestFramework, frxClass, frxDBSet, Classes, frxDesgn;
type
TLoadReportTest = class (TTestCase)
private
Stream: TStringStream;
Report: TfrxReport;
OKPO : array of string;
procedure LoadReportFromFile(ReportName, ReportPath: string);
procedure LoadFileFromFile(FileName, FilePath: string);
procedure TStrArrAdd(const A : array of string);
protected
// подготавливаем данные для тестирования
procedure SetUp; override;
// возвращаем данные для тестирования
procedure TearDown; override;
published
procedure LoadAllReportFormTest;
procedure LoadAllBlankFormTest;
procedure LoadAllWAVFormTest;
end;
implementation
uses Authentication, FormStorage, CommonData, Storage, UtilConst;
const
ReportPath = '..\Reports\Farmacy';
FarmacyBlankPath = '..\Reports\FarmacyBlank';
FarmacyWAVPath = '..\Reports\FarmacyWAV';
{ TLoadReportTest }
procedure TLoadReportTest.TStrArrAdd(const A : array of string);
var i : integer;
begin
SetLength(OKPO, Length(a));
for i := Low(A) to High(A) do
OKPO[i] := A[i];
end;
procedure TLoadReportTest.LoadReportFromFile(ReportName, ReportPath: string);
begin
// Загрузка из файла в репорт
Report.LoadFromFile(ReportPath);
// Сохранение отчета в базу
Stream.Clear;
Report.SaveToStream(Stream);
Stream.Position := 0;
TdsdFormStorageFactory.GetStorage.SaveReport(Stream, ReportName);
// Считывание отчета из базы
Report.LoadFromStream(TdsdFormStorageFactory.GetStorage.LoadReport(ReportName));
end;
procedure TLoadReportTest.LoadFileFromFile(FileName, FilePath: string);
begin
// Сохранение файла в базу
Stream.Clear;
Stream.LoadFromFile(FilePath);
Stream.Position := 0;
TdsdFormStorageFactory.GetStorage.SaveReport(Stream, FileName);
// Считывание отчета из базы
Stream.LoadFromStream(TdsdFormStorageFactory.GetStorage.LoadReport(FileName));
end;
procedure TLoadReportTest.LoadAllReportFormTest;
var
i : integer;
begin
LoadReportFromFile('Перемещение под фильтром', ReportPath + '\Перемещение под фильтром.fr3');
{ LoadReportFromFile('Pеестр по постановлению 1303(медцентр 3)', ReportPath + '\Pеестр по постановлению 1303(медцентр 3).fr3');
LoadReportFromFile('Счет к безналу предприятия', ReportPath + '\Счет к безналу предприятия.fr3');
LoadReportFromFile('Печать наклеек для доставки по СУН', ReportPath + '\Печать наклеек для доставки по СУН.fr3');
LoadReportFromFile('Акт по претензии Бадм', ReportPath + '\Акт по претензии Бадм.fr3');
LoadReportFromFile('Счет для страховой компании', ReportPath + '\Счет для страховой компании.fr3');
LoadReportFromFile('Возвратная ТТН', ReportPath + '\Возвратная ТТН.fr3');
Exit;
LoadReportFromFile('Коммерческое предложение', ReportPath + '\Коммерческое предложение.fr3');
Exit;
LoadReportFromFile('Счет соц.проект', ReportPath + '\Счет соц.проект.fr3');
//доп. соглащения Соц. проект
LoadReportFromFile('PrintReport_CheckSP_8513005', ReportPath + '\PrintReport_CheckSP_8513005.fr3');
LoadReportFromFile('PrintReport_CheckSP_9102200', ReportPath + '\PrintReport_CheckSP_9102200.fr3');
LoadReportFromFile('PrintReport_CheckSP_9089478', ReportPath + '\PrintReport_CheckSP_9089478.fr3');
LoadReportFromFile('PrintReport_CheckSP_9126996', ReportPath + '\PrintReport_CheckSP_9126996.fr3');
LoadReportFromFile('PrintReport_CheckSP_4474509', ReportPath + '\PrintReport_CheckSP_4474509.fr3');
LoadReportFromFile('PrintReport_CheckSP_4474508', ReportPath + '\PrintReport_CheckSP_4474508.fr3');
LoadReportFromFile('PrintReport_CheckSP_4474307', ReportPath + '\PrintReport_CheckSP_4474307.fr3');
LoadReportFromFile('PrintReport_CheckSP_4474556', ReportPath + '\PrintReport_CheckSP_4474556.fr3');
LoadReportFromFile('PrintReport_CheckSP_4212299', ReportPath + '\PrintReport_CheckSP_4212299.fr3');
LoadReportFromFile('Реестр лекарственных препаратов', ReportPath + '\Реестр лекарственных препаратов.fr3');
LoadReportFromFile('Счет постановление 1303', ReportPath + '\Счет постановление 1303.fr3');
LoadReportFromFile('Pеестр по постановлению 1303', ReportPath + '\Pеестр по постановлению 1303.fr3');
LoadReportFromFile('Pеестр по постановлению 1303(счет)', ReportPath + '\Pеестр по постановлению 1303(счет).fr3');
LoadReportFromFile('Pеестр по постановлению 1303(накладная)', ReportPath + '\Pеестр по постановлению 1303(накладная).fr3');
LoadReportFromFile('Pеестр по постановлению 1303(Расчет)', ReportPath + '\Pеестр по постановлению 1303(Расчет).fr3');
exit;
LoadReportFromFile('Отчет по продажам Соц.проекта', ReportPath + '\Отчет по продажам Соц.проекта.fr3');
LoadReportFromFile('Отчет по продажам Соц.проекта(пост.152)', ReportPath + '\Отчет по продажам Соц.проекта(пост.152).fr3');
exit;
LoadReportFromFile('PrintReport_CheckSP_4474558', ReportPath + '\PrintReport_CheckSP_4474558.fr3');
exit;
LoadReportFromFile('Печать стикера самоклейки', ReportPath + '\Печать стикера самоклейки.fr3');
LoadReportFromFile('Копия чека клиенту', ReportPath + '\Копия чека клиенту.fr3');
LoadReportFromFile('Копия чека клиенту(продажа)', ReportPath + '\Копия чека клиенту(продажа).fr3');
exit;
// Другие
LoadReportFromFile('Расходная_накладная', ReportPath + '\Расходная_накладная.fr3');
LoadReportFromFile('Расходная_накладная_для_менеджера', ReportPath + '\Расходная_накладная_для_менеджера.fr3');
LoadReportFromFile('Инвентаризация', ReportPath + '\Инвентаризация.fr3');
LoadReportFromFile('Списание', ReportPath + '\Списание.fr3');
LoadReportFromFile('Перемещение', ReportPath + '\Перемещение.fr3');
exit;
LoadReportFromFile('Продажа', ReportPath + '\Продажа.fr3');
LoadReportFromFile('Оплаты', ReportPath + '\Оплаты.fr3');
LoadReportFromFile('Возвратная_накладная(Оптима)', ReportPath + '\Возвратная_накладная(Оптима).fr3');
LoadReportFromFile('Возвратная_накладная', ReportPath + '\Возвратная_накладная.fr3');
LoadReportFromFile('Отчет по продажам на кассах', ReportPath + '\Отчет по продажам на кассах.fr3');
LoadReportFromFile('Отчет Доходности', ReportPath + '\Отчет Доходности.fr3');
}
end;
procedure TLoadReportTest.LoadAllBlankFormTest;
begin
LoadFileFromFile('ИНВЕНТ_ОПИСЬ_на_каждый_месяц.doc', FarmacyBlankPath + '\ИНВЕНТ ОПИСЬ на каждый месяц.doc');
LoadFileFromFile('Шаблон заявления на возврат товара.doc', FarmacyBlankPath + '\Шаблон заявления на возврат товара.doc');
end;
procedure TLoadReportTest.LoadAllWAVFormTest;
begin
LoadFileFromFile('Bell0001.wav', FarmacyWAVPath + '\Bell0001.wav');
end;
procedure TLoadReportTest.SetUp;
begin
inherited;
TAuthentication.CheckLogin(TStorageFactory.GetStorage, 'Админ', gc_AdminPassword, gc_User);
Report := TfrxReport.Create(nil);
Stream := TStringStream.Create;
end;
procedure TLoadReportTest.TearDown;
begin
inherited;
Report.Free;
Stream.Free
end;
initialization
TestFramework.RegisterTest('Загрузка отчетов', TLoadReportTest.Suite);
end.
|
{
TWMISQL Component Version 1.9b - Suite GLib
Copyright (©) 2009, by Germán Estévez (Neftalí)
Componente para acceder de forma genérica a las propiedades de WMI.
Component for access to WMI properties (all components).
Utilización/Usage:
Basta con "soltar" el componente y activarlo.
Rellenar la clase WMI y la condicion WHERE (o la sentencia SQL)
Place the component in the form and active it.
Fill the class and WHERE properties (or the SQL)
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones,
errores y/o cualquier otro tipo de sugerencia envíame un mail a:
german_ral@hotmail.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion send a mail to:
german_ral@hotmail.com
=========================================================================
@author Germán Estévez (Neftalí)
@web http://neftali.clubDelphi.com - http://neftali-mirror.site11.com/
@cat Package GLib
}
unit CWMISQL;
{
=========================================================================
CWMISQL.pas
Componente
========================================================================
Historia de las Versiones
------------------------------------------------------------------------
14/04/2010 * Creación.
=========================================================================
Errores detectados no corregidos
=========================================================================
}
//=========================================================================
//
// I N T E R F A C E
//
//=========================================================================
interface
uses
Classes, Controls, CWMIBase;
type
//: Implementación para el acceso vía WMI a la clase Win32_Environment
TWMISQL = class(TWMIBase)
private
FSQL: string;
FProperties: TStrings;
procedure SetProperties(const Value: TStrings);
protected
function GetWMIClass: string; override;
//: Rellenar las propiedades.
procedure FillProperties(AIndex:integer); override;
// propiedad Active
procedure SetActive(const Value: Boolean); override;
//: SQL Para acceder a la información de WMI
function GetWMISQL():string; override;
//: Obtener el root.
function GetWMIRoot():string; override;
//: Limpiar las propiedades
procedure ClearProps(); override;
public
// redefinido el constructor
constructor Create(AOwner: TComponent); override;
//: destructor
destructor Destroy; override;
published
//: Propiedades devueltas por la consulta para el objeto actual.
property Properties:TStrings{TStringList} read FProperties write SetProperties;
//: Propiedad con la SQL del componente.
property SQL:string read FSQL write FSQL;
end;
//=========================================================================
//
// I M P L E M E N T A T I O N
//
//=========================================================================
implementation
uses
{Generales} Forms, Types, Windows, SysUtils,
{GLib} UProcedures, UConstantes, Dialogs;
{ TWMISQL }
{-------------------------------------------------------------------------------}
//: SQL Para acceder a la información de WMI.
function TWMISQL.GetWMISQL():string;
begin
Result := FSQL;
end;
// Limpiar las propiedades.
procedure TWMISQL.ClearProps();
begin
// Limpiar las propiedades
Self.FProperties.Clear;
end;
//: Constructor del componente
constructor TWMISQL.Create(AOwner: TComponent);
begin
inherited;
// Crear la lista de propiedades
Self.FProperties := TStringList.Create();
// Accesoa la documentación
Self.MSDNHelp := 'http://msdn.microsoft.com/en-us/library/aa394554(VS.85).aspx';
end;
// destructor del componente
destructor TWMISQL.Destroy();
begin
// liberar
Self.FProperties.Free;
inherited;
end;
// Obtener la clase
function TWMISQL.GetWMIClass(): string;
begin
Result := Self.FSQL;
end;
// Obtener Root
function TWMISQL.GetWMIRoot(): string;
begin
Result := STR_CIM2_ROOT;
end;
// Active
procedure TWMISQL.SetActive(const Value: Boolean);
begin
// método heredado
inherited;
end;
//: Rellenar las propiedades del componente.
procedure TWMISQL.FillProperties(AIndex: integer);
var
TS:TStrings;
begin
// Llamar al heredado (importante)
inherited;
TS := TStringList.Create();
try
TS.Text := Self.AllProperties[AIndex - 1];
// Rellenar propiedades...
ExtractAllProperties(TS, Self.FProperties);
finally
TS.Free;
end;
end;
procedure TWMISQL.SetProperties(const Value: TStrings);
begin
// Nada
end;
end.
|
unit ADC_Const;
interface
const
// Setup particular value IRQ
ADC_SETUP_IRQ_MESSAGE = $80000000;
// m_nStartOf values
ADCPARAM_START_PROGRAMM = 1;
ADCPARAM_START_TIMER = 2;
ADCPARAM_START_EXT = 4;
ADCPARAM_START_COMP = 8;
// m_nIntOf values
ADCPARAM_INT_READY = 1;
ADCPARAM_INT_TC = 2;
ADCPARAM_INT_EXT = 3;
ADCPARAM_INT_COMP = 4;
ADCPARAM_INT_TIMER = 5;
//----------------------------------------------------------------------
// Timer numbers
ADCPARAM_TIMER0 = 0;
ADCPARAM_TIMER1 = 1;
ADCPARAM_TIMER2 = 2;
// Timer Modes
ADCPARAM_TIMER_MODE_0 = 0;
ADCPARAM_TIMER_MODE_1 = 1;
ADCPARAM_TIMER_MODE_2 = 2;
ADCPARAM_TIMER_MODE_3 = 3;
ADCPARAM_TIMER_MODE_4 = 4;
ADCPARAM_TIMER_MODE_5 = 5;
// Get <mode> code
ADC_GET_READY = 0;
ADC_GET_DATA = 1;
ADC_GET_DMACOUNTER = 2;
ADC_GET_DMACOUNTER0 = 2;
ADC_GET_DMACOUNTER1 = 3;
ADC_GET_INTERRUPT_READY = 4;
ADC_GET_INTERRUPT_TC = 5;
ADC_GET_INTERRUPT_EXT = 6;
ADC_GET_ADCMODE = 7;
ADC_GET_STATUS = 8;
ADC_GET_COMP = 9;
ADC_GET_BASE = 10;
ADC_GET_IRQ = 11;
ADC_GET_DRQ = 12;
ADC_GET_DRQ0 = 12;
ADC_GET_DRQ1 = 13;
ADC_GET_CLOCK = 14;
ADC_GET_NAME = 15;
ADC_CALIBRATE = 16;
ADC_GET_CAPABILITY = 17;
ADC_GET_CAPABILITY_EX = 21;
ADC_GET_BASELIST = 18;
ADC_GET_IRQLIST = 19;
ADC_GET_DRQLIST = 20;
ADC_GET_DEFAULTBASEINDEX = 22;
ADC_GET_DEFAULTIRQINDEX = 23;
ADC_GET_DEFAULTDRQINDEX = 24;
ADC_GET_MINFREQ = 25;
ADC_GET_MAXFREQ = 26;
ADC_GET_MINAMP = 27;
ADC_GET_MAXAMP = 28;
ADC_GET_FREQLIST = 29;
ADC_GET_DATASIZE = 30;
ADC_GET_DATABITS = 31;
ADC_GET_DATAMASK = 32;
ADC_GET_CHANNELMASK = 33;
ADC_GET_IRQMASK = 34;
ADC_GET_DRQMASK = 35;
ADC_GET_XC_STAT = 36;
ADC_GET_NCHANNEL = 37;
ADC_GET_SIZELIST = 38;
ADC_GET_SIZELIST_SIZE = 39;
ADC_GET_FREQLIST_SIZE = 40;
ADC_GET_BASELIST_SIZE = 41;
ADC_GET_IRQLIST_SIZE = 42;
ADC_GET_DRQLIST_SIZE = 43;
ADC_GET_GAINLIST = 44;
ADC_GET_GAINLIST_SIZE = 45;
ADC_GET_DATA_LSHIFT = 46;
ADC_GET_DATA_RSHIFT = 47;
ADC_GET_MEMORYSIZE = 48;
ADC_GET_PREHISTORY_SIZE = 49;
ADC_ZERO_CALIBRATE = 50;
ADC_GET_DATA_EXT = 51;
ADC_GET_DRQ_MODE = 52;
ADC_GET_RANGE_BIPOLAR = 53;
ADC_GET_RANGE_UNIPOLAR = 54;
ADC_GET_ADDRESS = 55;
ADC_GET_PREHISTORY_INDEX = 56;
ADC_GET_PACKETLIST = 57;
ADC_GET_PACKETLIST_SIZE = 58;
ADC_GET_SYNCHRO_OFFSET = 59;
ADC_GET_EXTSYNC_GAINLIST = 60;
ADC_GET_EXTSYNC_GAINLIST_SIZE = 61;
ADC_GET_GAINLIST_FLOAT = 62;
ADC_GET_GAINLIST_FLOAT_SIZE = 63;
ADC_GET_EXTSYNC_GAINLIST_FLOAT = 64;
ADC_GET_EXTSYNC_GAINLIST_FLOAT_SIZE = 65;
ADC_GET_PACKET_SIZE = 66;
// Get[Set] <mode> code
ADC_SET_ADCMODE_END = 1000;
ADC_SET_ADCMODE_START = 1001;
ADC_SET_DRQ_MODE_SINGLE = 1002;
ADC_SET_DRQ_MODE_DEMAND = 1003;
ADC_SET_ADCMODE_DIFF = 1004;
ADC_CLEARANDENABLE_IRQ = 1020;
ADC_SET_ACTIVE_CHANNELL = 1021;
ADC_SET_MODE_SLAVE = 1022;
ADC_SET_CLOCK_MODE = 1023;
ADC_SET_TOGGLELOADXILINX = 2001;
ADC_SET_TOGGLECOMPATMODE = 2002;
ADC_SET_TOGGLELOADCUSTOM = 2003;
ADC_SET_FORCERELOADXILINX = 2004;
ADC_SET_POWER_ON = 2005;
ADC_SET_POWER_OFF = 2006;
ADC_SET_TOGGLERACRESET = 2007;
ADC_SET_FORCERACRESET = 2008;
ADC_SET_LOADXILINX = 2009;
ADC_SET_DONOTLOADXILINX = 2010;
ADC_SET_LOADCUSTOM = 2011;
ADC_SET_LOADSTANDARD = 2012;
ADC_SET_RACRESET_ON = 2013;
ADC_SET_RACRESET_OFF = 2014;
ADC_SET_RELOADXILINX = 2015;
ADC_SET_ADDRESS = 2016;
ADC_SET_RESET_RAC = 2017;
ADC_GET_ISLABPCP = 2018;
ADC_SET_DMA_BUSMASTER_ENABLE = 2020;
// LOWORD is major version, HIWORD is minor version
ADC_GET_VERSION = 2000;
// ADC_GET_CAPABILITY codes
ADC_CAPS_DMA = $00000001;
ADC_CAPS_DMA0 = $00000001;
ADC_CAPS_DMA1 = $00000002;
ADC_CAPS_DMAHALF = $00000004;
ADC_CAPS_DMASWITCH = $00000008;
ADC_CAPS_INTERRUPT = $00000010;
ADC_CAPS_INTERRUPT0 = $00000010;
ADC_CAPS_INTERRUPT1 = $00000020;
ADC_CAPS_INTERRUPT_READY = $00000040;
ADC_CAPS_INTERRUPT_TC = $00000080;
ADC_CAPS_INTERRUPT_EXT = $00000100;
ADC_CAPS_GENERATOR = $00000200;
ADC_CAPS_TIMER3 = $00000400;
ADC_CAPS_TIMER8254 = $00000400;
ADC_CAPS_EXTSTART = $00000800;
ADC_CAPS_MEMORY = $00001000;
ADC_CAPS_MEMORYPERCHANNEL = $00002000;
ADC_CAPS_FREQLIST = $00004000;
ADC_CAPS_SIZELIST = $00008000;
ADC_CAPS_DIGITAL_IN = $00010000;
ADC_CAPS_DIGITAL_OUT = $00020000;
ADC_CAPS_DIGITAL_16 = $00040000;
ADC_CAPS_DIGITAL_32 = $00080000;
ADC_CAPS_GAINSLIST = $00100000;
ADC_CAPS_PREHISTORY = $00200000;
ADC_CAPS_GAINSPERCHANNEL = $00400000;
ADC_CAPS_GAINSFLOAT = $00800000;
ADC_CAPS_SYNCHROLEVEL = $01000000;
ADC_CAPS_SYNCHROLOW = $02000000;
ADC_CAPS_SYNCHROHIGH = $04000000;
ADC_CAPS_SYNCHRO2 = $08000000;
ADC_CAPS_CHANNELDIR_GROWTH = $10000000;
ADC_CAPS_CHANNELDIR_DECREASE = $20000000;
ADC_CAPS_CHANNELDIR_FREE = $40000000;
ADC_CAPS_CALIBRATE = $80000000;
// ADC_GET_CAPABILITY_EX codes
ADC_CAPS1_PCI = $00000000;
ADC_CAPS1_PCISLAVE = $00000001;
ADC_CAPS1_PCIMASTER = $00000002;
ADC_CAPS2_MEMORY = $00000001;
ADC_CAPS2_MEMORY1 = $00000002;
ADC_CAPS2_FIFO = $00000004;
ADC_CAPS2_XXX = $00000000;
ADC_CAPS3_XXX = $00000000;
// Init <mode> code
ADC_INIT_MODE_CHECK = 0;
ADC_INIT_MODE_INIT = 1;
// GetData <mode> code
ADC_DATA_MODE_DATAFROMDMA = $00000000;
ADC_DATA_MODE_DATAFROMDMA0 = $00000000;
ADC_DATA_MODE_DATAFROMDMA1 = $80000000;
ADC_DATA_MODE_DATAFROMMEM = $00000000;
ADC_DATA_MODE_DATAASIS = $40000000;
ADC_DATA_MODE_DATACH0 = $20000000;
ADC_DATA_MODE_DATACH1 = $10000000;
ADC_DATA_MODE_DATABOTH = $00000000;
ADC_DATA_MODE_DATASWAP = $08000000;
ADC_DATA_MODE_DATAWRITE = $04000000;
ADC_DATA_MODE_CONVERT2INT16 = 1;
ADC_DATA_MODE_CONVERT2INT16M = 2;
ADC_DATA_MODE_CONVERT2INT32 = 3;
ADC_DATA_MODE_CONVERT2INT32M = 4;
// PortIO <mode> code
ADC_PORTIO_OUTB = 1;
ADC_PORTIO_INB = -1;
ADC_PORTIO_OUTW = 2;
ADC_PORTIO_INW = -2;
ADC_PORTIO_OUTD = 3;
ADC_PORTIO_IND = -3;
ADC_PORTIO_OUTB_PORT2 = 4;
ADC_PORTIO_INB_PORT2 = -4;
// ERROR code
ADC_ERROR_NOTSUPPORTED = 0;
ADC_ERROR_NOTINITIALIZE = -1;
ADC_ERROR_INVALIDPARAMETERS = -2;
// Codes for ERROR determination
ADC_ERROR_INVALIDBASE = -3;
ADC_ERROR_INVALIDIRQ = -4;
ADC_ERROR_INVALIDDRQ = -5;
ADC_ERROR_DRQ_ALLREADY_USED = -6;
ADC_ERROR_IRQ_ALLREADY_USED = -7;
ADC_ERROR_VXD_NOTLOADED = -10;
ADC_ERROR_VXD_INVALIDVERSION = -11;
ADC_ERROR_LOADXILINX = -12;
ADC_ERROR_NO_CONFIG_INFO = -13;
ADC_ERROR_CANTLOADXILINXFILES = -14;
ADC_ERROR_LOAD_ADSP = -15;
ADC_ERROR_LOAD_ADSP_FILE = -16;
// ERROR Start code
ADC_ERROR_DRQ_NOTSETUP = -20;
//----------------------------------------------------------------------
ADC_CONTROL_M2 = $0100;
ADC_CONTROL_DIFS = $0080;
ADC_CONTROL_DIF1 = $0040;
ADC_CONTROL_DIF0 = $0020;
ADC_CONTROL_FSW = $0010;
ADC_CONTROL_ESW = $0008;
ADC_CONTROL_SYNC_CH0 = $0000;
ADC_CONTROL_SYNC_CH1 = $0001;
ADC_CONTROL_SYNC_TTL = $0002;
ADC_CONTROL_SYNC_FRONT = $0004;
ADC_CONTROL_SYNC_DECLINE = $0000;
ADC_CONTROL_SYNC_FRONT2 = $0200;
ADC_CONTROL_SYNC_DECLINE2 = $0000;
ADC_CONTROL_SYNC_TTL2 = $0400;
ADC_CONTROL_SYNC_STOP = $0800;
ADC_CONTROL_SYNC_STOP2 = $1000;
ADC_CONTROL_SYNC_COMPARATOR = $0000;
ADC_CONTROL_SYNC_COMPARATOR2 = $2000;
ADC_CONTROL_SYNC_COMPARATOR1 = $4000;
ADC_CONTROL_SYNC_KD0 = $00000000;
ADC_CONTROL_SYNC_KD1 = $00010000;
ADC_CONTROL_SYNC_HYSTER0 = $00000000;
ADC_CONTROL_SYNC_HYSTER1 = $00020000;
ADC_CONTROL_SYNC_NOFILTER = $00000000;
ADC_CONTROL_SYNC_HIFILTER = $00040000;
ADC_CONTROL_SYNC_LOFILTER = $00080000;
//----------------------------------------------------------------------
ADC_DMAEX_CONTROL_CHANNEL = $00000000;
ADC_DMAEX_CONTROL_GAIN = $00000001;
ADC_DMAEX_CONTROL_MODE1 = $00000000;
ADC_DMAEX_CONTROL_MODEDIFF = $00000002;
ADC_DMAEX_CONTROL_CB_MASK = $0000FF00;
ADC_DMAEX_CONTROL_CC_MASK = $00FF0000;
//----------------------------------------------------------------------
ADC_DMA_TYPE = 1;
ADC_DMA1_TYPE = 2;
ADC_TIMER_TYPE = 3;
ADC_DMAEX_TYPE = 4;
ADC_MEMORY_TYPE = 5;
ADC_SINGLE_TYPE = 6;
ADC_SLOW_TYPE = 7;
ADC_OLDLABP_TYPE = 8;
ADC_SINGLEEX_TYPE = 9;
ADC_MEMORYEX_TYPE = 20;
ADC_MEMORY1_TYPE = 21;
//----------------------------------------------------------------------*/
ADC_PORT_TYPE = 10;
ADC_PORT_TIMER_TYPE = 11;
ADC_PORT_DMA_TYPE = 12;
ADC_PORT_INTERRUPT_TYPE = 13;
//----------------------------------------------------------------------*/
ADC_PORT_READ = 1;
ADC_PORT_WRITE = 2;
ADC_PORT_MASK = 3;
ADC_PORT_TIMER_READ = 1;
ADC_PORT_TIMER_WRITE = 2;
ADC_PORT_DMA_READ = 1;
ADC_PORT_DMA_WRITE = 2;
ADC_PORT_INTERRUPT_DMA = $00000001;
ADC_PORT_INTERRUPT_ADC = $00000002;
implementation
end.
|
unit SecondForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DemoInterfaces, Vcl.StdCtrls;
type
TAnotherForm = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
FLogger : ILogger;
protected
public
{ Public declarations }
constructor Create(AOwner : TComponent; const logger : ILogger);reintroduce;
end;
var
AnotherForm: TAnotherForm;
implementation
{$R *.dfm}
{ TForm1 }
procedure TAnotherForm.Button1Click(Sender: TObject);
begin
FLogger.Log(Error, 'Oh dear, an error occured in AnotherForm');
end;
constructor TAnotherForm.Create(AOwner: TComponent; const logger: ILogger);
begin
inherited Create(AOwner);
FLogger := logger;
end;
end.
|
unit ConnectedDevice;
{$mode objfpc}{$H+}
interface
uses
ftd2xx, Classes, SysUtils, SdpoSerial,ComCtrls,ExtCtrls, contnrs,
SharedLogger, filechannel;
type
TDeviceState = (STATE_SEARCHING, STATE_CONNECTED);
TReceiveState = (STATE_START, STATE_CMD, STATE_ADDR, STATE_DATA, STATE_PROCESSING);
const MAX_NUM_SERIAL_NUMBER_CHARS = 50;
type TSerialNumber = array [0..(MAX_NUM_SERIAL_NUMBER_CHARS - 1)] of Char;
type PSerialNumber = ^TSerialNumber;
TConnectedDevice = Class(TComponent)
private
fDevice : TFtd2xxDevice;
fOnDeviceConnect: TNotifyEvent;
fOnDeviceDisconnect: TNotifyEvent;
connectTimer : TTimer;
fDeviceState : TDeviceState;
procedure onDeviceTimer(Sender: TObject);
protected
function getComPortNumber(): Integer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
//FTDI DLL Functions
function isConnected: Boolean;
function getSerialNumber : String;
function GetDeviceCount: DWord;
published
property onDeviceConnected: TNotifyEvent read fOnDeviceConnect write fOnDeviceConnect;
property onDeviceDisconnected: TNotifyEvent read fOnDeviceDisconnect write fOnDeviceDisconnect;
property comPortNumber: Integer read getComPortNumber;
end;
implementation
Constructor TConnectedDevice.Create(AOwner: TComponent);
begin
inherited Create(aOwner);
fDevice := TFtd2xxDevice.create;
//Logger.Send('[TConnectedDevice] created');
fDeviceState := STATE_SEARCHING; // initial device state
connectTimer := TTimer.Create(self); // device connection timer
connectTimer.OnTimer:= @onDeviceTimer;
connectTimer.Interval:=1000; // 1 second
connectTimer.Enabled:=true; // start the timer
end;
Destructor TConnectedDevice.Destroy;
begin
connectTimer.Free;
fDevice.Free;
inherited;
end;
function TConnectedDevice.GetDeviceCount: DWord;
begin
result := fDevice.getNumDevices();
end;
function TConnectedDevice.getComPortNumber(): Integer;
begin
if (fDevice.isConnected) then
result := fDevice.GetComPortNumber()
else
result := 0;
end;
function TConnectedDevice.GetSerialNumber: String;
begin
Result := fDevice.getSerialNumber();
end;
function TConnectedDevice.isConnected: Boolean;
begin
result := fDevice.isConnected();
end;
procedure TConnectedDevice.onDeviceTimer(Sender: TObject);
begin
//Logger.send('[TConnectedDevice.onDeviceTimer]');
case fDeviceState of
STATE_SEARCHING:
begin
if (isConnected) then
begin
fDeviceState := STATE_CONNECTED;
if assigned(fOnDeviceConnect) then
fOnDeviceConnect(self); // Send Notification Event
end
end;
STATE_CONNECTED:
begin
if (not(isConnected)) then
begin
fDeviceState := STATE_SEARCHING;
if assigned(fOnDeviceDisconnect) then
fOnDeviceDisconnect(self); // Send Notification Event
end
end;
end;
end;
end.
|
unit UUADGridCondition;
{ ClickForms Application }
{ Bradford Technologies, Inc. }
{ All Rights Reserved }
{ Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc. }
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, Dialogs, UCell, UContainer, UEditor, UGlobals, UStatus,
ExtCtrls, UForms, UUADUtils;
type
TdlgUADGridCondition = class(TAdvancedForm)
bbtnCancel: TBitBtn;
bbtnOK: TBitBtn;
rgRating: TRadioGroup;
bbtnHelp: TBitBtn;
bbtnClear: TButton;
procedure FormShow(Sender: TObject);
procedure bbtnHelpClick(Sender: TObject);
procedure bbtnOKClick(Sender: TObject);
procedure bbtnClearClick(Sender: TObject);
private
{ Private declarations }
function IsSubject: Boolean;
public
FCell: TBaseCell;
procedure SaveToCell;
procedure Clear;
end;
var
dlgUADGridCondition: TdlgUADGridCondition;
implementation
{$R *.dfm}
uses
UPage, UStrings;
procedure TdlgUADGridCondition.bbtnHelpClick(Sender: TObject);
begin
ShowUADHelp('FILE_HELP_UAD_CONDITION_RATING', Caption);
end;
procedure TdlgUADGridCondition.FormShow(Sender: TObject);
var
Cntr: Integer;
RatingText: String;
begin
rgRating.ItemIndex := -1;
RatingText := FCell.Text;
if Trim(RatingText) <> '' then
begin
Cntr := -1;
repeat
Cntr := Succ(Cntr);
if RatingText = Copy(rgRating.Items.Strings[Cntr], 1, 2) then
rgRating.ItemIndex := Cntr;
until (rgRating.ItemIndex > -1) or (Cntr = 5);
end;
if rgRating.ItemIndex = -1 then
rgRating.ItemIndex := 0;
rgRating.SetFocus;
end;
procedure TdlgUADGridCondition.bbtnOKClick(Sender: TObject);
begin
if rgRating.ItemIndex < 0 then
begin
ShowAlert(atWarnAlert, 'A property condition rating must be selected.');
rgRating.SetFocus;
Exit;
end;
SaveToCell;
ModalResult := mrOK;
end;
function TdlgUADGridCondition.IsSubject: Boolean;
begin
Result := (FCell.FContextID <> 0);
end;
procedure TdlgUADGridCondition.SaveToCell;
var
SubjCondCell: TBaseCell;
begin
// Remove any legacy data - no longer used
FCell.GSEData := '';
// Save the cleared or formatted text
if (rgRating.ItemIndex >= 0) then
begin
FCell.SetText(Copy(rgRating.Items.Strings[rgRating.ItemIndex], 1, 2));
if IsSubject then
begin
SubjCondCell := TContainer(CellContainerObj(FCell)).GetCellByID(520);
if Assigned(SubjCondCell) then
SetDisplayUADText(SubjCondCell, (FCell.Text + Copy(SubjCondCell.GetText, 3, Length(SubjCondCell.GetText))));
end;
end
else
FCell.SetText('');
end;
procedure TdlgUADGridCondition.Clear;
begin
rgRating.ItemIndex := -1;
end;
procedure TdlgUADGridCondition.bbtnClearClick(Sender: TObject);
begin
if WarnOK2Continue(msgUAGClearDialog) then
begin
Clear;
SaveToCell;
ModalResult := mrOK;
end;
end;
end.
|
unit ConnectionInfo;
interface
type
TConnectionInfo = record
HostName: String;
Port: Integer;
DatabaseName: String;
UserName: String;
Password: String;
constructor Create(
HostName: String;
Port: Integer;
DatabaseName: String;
UserName: String;
Password: String
);
end;
implementation
{ TConnectionInfo }
constructor TConnectionInfo.Create(HostName: String; Port: Integer;
DatabaseName, UserName, Password: String);
begin
Self.HostName := HostName;
Self.Port := Port;
Self.DatabaseName := DatabaseName;
Self.UserName := UserName;
Self.Password := Password;
end;
end.
|
{******************************************************************************}
{ }
{ WiRL: RESTful Library for Delphi }
{ }
{ Copyright (c) 2015-2019 WiRL Team }
{ }
{ https://github.com/delphi-blocks/WiRL }
{ }
{******************************************************************************}
unit WiRL.Core.Cache;
interface
uses
System.Classes, System.SysUtils, Generics.Collections, System.Rtti,
System.SyncObjs;
type
TWiRLCacheItem = class
private
FCriticalSection: TCriticalSection;
FLastReadAccess: TDateTime;
FLastWriteAccess: TDateTime;
FDuration: TDateTime;
FValue: TValue;
function GetExpiration: TDateTime;
function GetIsExpired: Boolean;
function GetValue: TValue;
procedure SetValue(const Value: TValue);
protected
public
constructor Create;
destructor Destroy; override;
property LastReadAccess: TDateTime read FLastReadAccess;
property LastWriteAccess: TDateTime read FLastWriteAccess;
property Duration: TDateTime read FDuration write FDuration;
property Expiration: TDateTime read GetExpiration;
property IsExpired: Boolean read GetIsExpired;
property Value: TValue read GetValue write SetValue;
property CriticalSection: TCriticalSection read FCriticalSection;
end;
TWiRLCache = class
private
FStorage: TDictionary<string, TWiRLCacheItem>;
FCriticalSection: TCriticalSection;
protected
public
constructor Create; virtual;
destructor Destroy; override;
procedure SetValue(const AName: string; const AValue: TValue);
function Contains(const AName: string): Boolean;
function GetValue(const AName: string): TValue;
function Use(const AName: string; const ADoSomething: TProc<TValue>): Boolean;
end;
function CacheManager: TWiRLCache;
implementation
uses
System.DateUtils, System.Math;
var
_Cache: TWiRLCache;
procedure AcquireAndDo(ACRiticalSection: TCriticalSection; const ADoSomething: TProc);
begin
ACRiticalSection.Enter;
try
ADoSomething();
finally
ACRiticalSection.Leave;
end;
end;
function CacheManager: TWiRLCache;
begin
if not Assigned(_Cache) then
_Cache := TWiRLCache.Create;
Result := _Cache;
end;
{ TCache }
procedure TWiRLCache.SetValue(const AName: string; const AValue: TValue);
var
LValue: TValue;
begin
LValue := AValue;
AcquireAndDo(FCriticalSection,
procedure
var
LItem: TWiRLCacheItem;
begin
if FStorage.TryGetValue(AName, LItem) then
begin
AcquireAndDo(LItem.CriticalSection,
procedure
begin
LItem.Value := LValue;
end
);
end
else
begin
LItem := TWiRLCacheItem.Create;
try
LItem.Value := LValue;
FStorage.Add(AName, LItem);
except
LItem.Free;
raise;
end;
end;
end);
end;
function TWiRLCache.Use(const AName: string;
const ADoSomething: TProc<TValue>): Boolean;
var
LItem: TWiRLCacheItem;
LFound: Boolean;
begin
Result := False;
FCriticalSection.Enter;
try
LFound := FStorage.TryGetValue(AName, LItem);
finally
FCriticalSection.Leave;
end;
if LFound then
begin
Result := True;
AcquireAndDo(LItem.CriticalSection,
procedure
begin
ADoSomething(LItem.Value);
end);
end;
end;
function TWiRLCache.Contains(const AName: string): Boolean;
var
LResult: Boolean;
begin
AcquireAndDo(FCriticalSection,
procedure
begin
LResult := FStorage.ContainsKey(AName);
end);
Result := LResult;
end;
constructor TWiRLCache.Create;
begin
inherited Create;
FStorage := TDictionary<string, TWiRLCacheItem>.Create;
FCriticalSection := TCriticalSection.Create;
end;
destructor TWiRLCache.Destroy;
begin
FCriticalSection.Free;
FStorage.Free;
inherited;
end;
function TWiRLCache.GetValue(const AName: string): TValue;
var
LItem: TWiRLCacheItem;
LResult: TValue;
begin
Result := TValue.Empty;
AcquireAndDo(FCriticalSection,
procedure
begin
if FStorage.TryGetValue(AName, LItem) then
begin
AcquireAndDo(LItem.CriticalSection,
procedure
begin
LResult := LItem.Value;
end
);
end;
end);
Result := LResult;
end;
{ TCacheItem }
constructor TWiRLCacheItem.Create;
begin
inherited Create;
FCriticalSection := TCriticalSection.Create;
FLastReadAccess := Now;
FLastWriteAccess := Now;
FDuration := 1 / HoursPerDay;
FValue := TValue.Empty;
end;
destructor TWiRLCacheItem.Destroy;
begin
FCriticalSection.Free;
inherited;
end;
function TWiRLCacheItem.GetExpiration: TDateTime;
begin
Result := Max(LastReadAccess, LastWriteAccess) + Duration;
end;
function TWiRLCacheItem.GetIsExpired: Boolean;
begin
Result := Now > Expiration;
end;
function TWiRLCacheItem.GetValue: TValue;
begin
Result := FValue;
FLastReadAccess := Now;
end;
procedure TWiRLCacheItem.SetValue(const Value: TValue);
begin
FValue := Value;
FLastWriteAccess := Now;
end;
end.
|
{
Sobre o autor:
Guinther Pauli
Delphi Certified Professional - 3,5,6,7,2005,2006,Delphi Web,Kylix,XE
Microsoft Certified Professional - MCP,MCAD,MCSD.NET,MCTS,MCPD (C#, ASP.NET, Arquitetura)
Colaborador Editorial Revistas .net Magazine e ClubeDelphi
MVP (Most Valuable Professional) - Embarcadero Technologies - US
http://gpauli.com
http://www.facebook.com/guintherpauli
http://www.twitter.com/guintherpauli
http://br.linkedin.com/in/guintherpauli
}
unit uFramework;
interface
type
Mediator = class; //forward
// Colleague (abstract)
Colega = class abstract
protected _mediator: Mediator;
//Construtor
public constructor Create (mediator: Mediator);
end;
// Concrete Colleague
Suporte = class(Colega)
public constructor Create(mediator: Mediator);
public procedure Enviar(mensagem: string);
public procedure Notificar(mensagem: string);
end;
// Concrete Colleague
Usuario = class(Colega)
public
public constructor Create(mediator: Mediator);
public procedure Enviar(mensagem: string);
public procedure Notificar(mensagem: string);
end;
// Mediator
Mediator = class abstract
public procedure Enviar(mensagem: string; colega: Colega); virtual; abstract;
end;
// Concrete Mediator
ConcreteMediator = class(Mediator)
private _suporte: Suporte;
private _usuario: Usuario;
public property Suporte: Suporte write _suporte;
public property Usuario: Usuario write _usuario;
public procedure Enviar(mensagem: string; colega: Colega); override;
end;
implementation
// Concrete Mediator
procedure ConcreteMediator.Enviar(mensagem: string; colega: Colega);
begin
if colega = _usuario then
_suporte.Notificar(mensagem)
else
_usuario.Notificar(mensagem);
end;
// Abstract Colleague (Colega)
constructor Colega.Create(mediator: Mediator);
begin
self._mediator := mediator;
end;
// Concrete Colleague (Suporte)
constructor Suporte.Create(mediator: Mediator);
begin
inherited Create(mediator);
end;
procedure Suporte.Enviar(mensagem: string);
begin
_mediator.Enviar(mensagem, self);
end;
procedure Suporte.Notificar(mensagem: string);
begin
WriteLn('Suporte recebeu a mensagem: ' + mensagem);
end;
// Concrete Colleague (Usuario)
constructor Usuario.Create(mediator: Mediator);
begin
inherited Create(mediator);
end;
procedure Usuario.Enviar(mensagem: string);
begin
_mediator.Enviar(mensagem, self);
end;
procedure Usuario.Notificar(mensagem: string);
begin
WriteLn('Usuário recebeu a mensagem: ' + mensagem)
end;
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2015 Vincent Parrett & Contributors }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.Windows.Console;
interface
{$I DUnitX.inc}
{$IFNDEF MSWINDOWS}
This unit should not ne included in your project, it works on windows only
{$ENDIF}
uses
{$IFDEF USE_NS}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
DUnitX.ConsoleWriter.Base;
type
TDUnitXWindowsConsoleWriter = class(TDUnitXConsoleWriterBase)
private
FDefaultForeground : Word;
FDefaultBackground : Word;
FLastForeground : TConsoleColour;
FLastBackground : TConsoleColour;
FStdOut : THandle;
function GetForegroundColourCode(const cc: TConsoleColour): Word;
function GetBackgroundColourCode(const cc: TConsoleColour): Word;
function GetConsoleWidth : Integer;
protected
procedure InternalWriteLn(const s : String); override;
procedure InternalWrite(const s : String); override;
public
procedure SetColour(const foreground: TConsoleColour; const background: TConsoleColour = ccDefault); override;
constructor Create;override;
destructor Destroy; override;
end;
implementation
uses
{$IFDEF MSWINDOWS}
{$IFDEF USE_NS}
WinAPI.Windows, // Delphi XE2 (CompilerVersion 23) added scopes in front of unit names
{$ELSE}
Windows,
{$ENDIF}
{$ENDIF}
DUnitX.Utils,
DUnitX.IoC;
constructor TDUnitXWindowsConsoleWriter.Create;
var
dummy : Cardinal;
consoleInfo : _CONSOLE_SCREEN_BUFFER_INFO;
begin
inherited;
FStdOut := GetStdHandle(STD_OUTPUT_HANDLE);
if not GetConsoleMode(FStdOut, dummy) then // Not a console handle
Self.RedirectedStdOut := True;
Self.ConsoleWidth := GetConsoleWidth;
FLastForeground := ccDarkYellow; // Just to ensure the first colour change goes through
FLastBackground := ccDarkYellow;
//Save the current console colour settings so we can restore them:
if GetConsoleScreenBufferInfo(FStdOut, consoleInfo) then
begin
FDefaultForeground := consoleInfo.wAttributes and (FOREGROUND_BLUE or FOREGROUND_GREEN or FOREGROUND_RED or FOREGROUND_INTENSITY);
FDefaultBackground := consoleInfo.wAttributes and (BACKGROUND_BLUE or BACKGROUND_GREEN or BACKGROUND_RED or BACKGROUND_INTENSITY);
end
else
begin
FDefaultForeground := GetForegroundColourCode(ccWhite);
FDefaultBackground := GetBackgroundColourCode(ccBlack);
end;
end;
procedure TDUnitXWindowsConsoleWriter.SetColour(const foreground, background: TConsoleColour);
begin
if (FLastForeground <> foreground) or (FLastBackground <> background) then
begin
SetConsoleTextAttribute(FStdOut,
GetForegroundColourCode(foreground) or
GetBackgroundColourCode(background));
FLastForeground := foreground;
FLastBackground := background;
end;
end;
function TDUnitXWindowsConsoleWriter.GetForegroundColourCode(const cc : TConsoleColour) : Word;
begin
case cc of
ccDefault : Result := FDefaultForeground;
ccBrightRed : Result := FOREGROUND_RED or FOREGROUND_INTENSITY;
ccDarkRed : Result := FOREGROUND_RED;
ccBrightBlue : Result := FOREGROUND_BLUE or FOREGROUND_INTENSITY;
ccDarkBlue : Result := FOREGROUND_BLUE;
ccBrightGreen : Result := FOREGROUND_GREEN or FOREGROUND_INTENSITY;
ccDarkGreen : Result := FOREGROUND_GREEN;
ccBrightYellow : Result := FOREGROUND_GREEN or FOREGROUND_RED or FOREGROUND_INTENSITY;
ccDarkYellow : Result := FOREGROUND_GREEN or FOREGROUND_RED;
ccBrightAqua : Result := FOREGROUND_GREEN or FOREGROUND_BLUE or FOREGROUND_INTENSITY;
ccDarkAqua : Result := FOREGROUND_GREEN or FOREGROUND_BLUE;
ccBrightPurple : Result := FOREGROUND_BLUE or FOREGROUND_RED or FOREGROUND_INTENSITY;
ccDarkPurple : Result := FOREGROUND_BLUE or FOREGROUND_RED;
ccGrey : Result := FOREGROUND_INTENSITY;
ccBlack : Result := 0;
ccBrightWhite : Result := FOREGROUND_BLUE or FOREGROUND_GREEN or FOREGROUND_RED or FOREGROUND_INTENSITY;
ccWhite : Result := FOREGROUND_BLUE or FOREGROUND_GREEN or FOREGROUND_RED;
else
Result := 0;
end;
end;
procedure TDUnitXWindowsConsoleWriter.InternalWrite(const s: String);
var
output : string;
dummy : Cardinal;
begin
//Add the indenting.
output := TStrUtils.PadString(s, length(s)+ Self.CurrentIndentLevel, True, ' ');
if Self.RedirectedStdOut then
System.Write(output)
else
WriteConsoleW(FStdOut, PWideChar(output), Length(output), dummy, nil);
end;
procedure TDUnitXWindowsConsoleWriter.InternalWriteLn(const s: String);
var
output : string;
dummy : Cardinal;
begin
//Add the indenting.
output := TStrUtils.PadString(s, length(s)+ Self.CurrentIndentLevel, True, ' ');
//If we are already going to wrap around to the next line. No need to add CRLF
if Length(output) < ConsoleWidth then
output := output + #13#10;
if Self.RedirectedStdOut then
System.Write(output)
else
WriteConsoleW(FStdOut, PWideChar(output), Length(output), dummy, nil);
end;
destructor TDUnitXWindowsConsoleWriter.Destroy;
begin
SetColour(ccDefault); // Restore default console colours
inherited;
end;
function TDUnitXWindowsConsoleWriter.GetBackgroundColourCode(const cc : TConsoleColour) : Word;
begin
case cc of
ccDefault : Result := FDefaultBackground;
ccBrightRed : Result := BACKGROUND_RED or BACKGROUND_INTENSITY;
ccDarkRed : Result := BACKGROUND_RED;
ccBrightBlue : Result := BACKGROUND_BLUE or BACKGROUND_INTENSITY;
ccDarkBlue : Result := BACKGROUND_BLUE;
ccBrightGreen : Result := BACKGROUND_GREEN or BACKGROUND_INTENSITY;
ccDarkGreen : Result := BACKGROUND_GREEN;
ccBrightYellow : Result := BACKGROUND_GREEN or BACKGROUND_RED or BACKGROUND_INTENSITY;
ccDarkYellow : Result := BACKGROUND_GREEN or BACKGROUND_RED;
ccBrightAqua : Result := BACKGROUND_GREEN or BACKGROUND_BLUE or BACKGROUND_INTENSITY;
ccDarkAqua : Result := BACKGROUND_GREEN or BACKGROUND_BLUE;
ccBrightPurple : Result := BACKGROUND_BLUE or BACKGROUND_RED or BACKGROUND_INTENSITY;
ccDarkPurple : Result := BACKGROUND_BLUE or BACKGROUND_RED;
ccGrey : Result := BACKGROUND_INTENSITY;
ccBlack : Result := 0;
ccBrightWhite : Result := BACKGROUND_BLUE or BACKGROUND_GREEN or BACKGROUND_RED or BACKGROUND_INTENSITY;
ccWhite : Result := BACKGROUND_BLUE or BACKGROUND_GREEN or BACKGROUND_RED;
else
Result := 0;
end;
end;
function TDUnitXWindowsConsoleWriter.GetConsoleWidth: Integer;
var
info : CONSOLE_SCREEN_BUFFER_INFO;
begin
Result := High(Integer); // Default is unlimited width
if GetConsoleScreenBufferInfo(FStdOut, info) then
Result := info.dwSize.X;
end;
{$IFDEF MSWINDOWS}
initialization
//Refer to IoC.pas for why the double generic class function isn't being used.
{$IFDEF DELPHI_2010_UP}
TDUnitXIoC.DefaultContainer.RegisterType<IDUnitXConsoleWriter,TDUnitXWindowsConsoleWriter>;
{$ELSE}
TDUnitXIoC.DefaultContainer.RegisterType<IDUnitXConsoleWriter>(
function : IDUnitXConsoleWriter
begin
Result := TDUnitXWindowsConsoleWriter.Create;
end
);
{$ENDIF}
{$ENDIF}
end.
|
program intuitext;
{$IFNDEF HASAMIGA}
{$FATAL This source is compatible with Amiga, AROS and MorphOS only !}
{$ENDIF}
{
Project : intuitext
Topic : program to show the use of an Intuition IntuiText object.
Source : RKRM
}
{$MODE OBJFPC}{$H+}{$HINTS ON}
{$UNITPATH ../../../Base/CHelpers}
{$UNITPATH ../../../Base/Trinity}
Uses
Exec, AmigaDOS, AGraphics, Intuition, utility,
{$IFDEF AMIGA}
SystemVarTags,
{$ENDIF}
CHelpers,
Trinity;
const
MYTEXT_LEFT = (0);
MYTEXT_TOP = (0);
{*
** main routine. Open required library and window and draw the images.
** This routine opens a very simple window with no IDCMP. See the
** chapters on "Windows" and "Input and Output Methods" for more info.
** Free all resources when done.
*}
procedure Main(argc: Integer; argv: PPChar);
var
screen : PScreen;
drawinfo : PDrawInfo;
win : PWindow;
myIText : TIntuiText;
myTextAttr : TTextAttr;
myTEXTPEN : ULONG;
myBACKGROUNDPEN : ULONG;
begin
{$IFDEF MORPHOS}
IntuitionBase := PIntuitionBase(OpenLibrary('intuition.library', 37));
if assigned(IntuitionBase) then
{$ENDIF}
begin
if SetAndTest(screen, LockPubScreen(nil)) then
begin
if SetAndtest(drawinfo, GetScreenDrawInfo(screen)) then
begin
{* Get a copy of the correct pens for the screen.
** This is very important in case the user or the
** application has the pens set in a unusual way.
*}
myTEXTPEN := PWORD(drawinfo^.dri_Pens)[TEXTPEN];
myBACKGROUNDPEN := PWORD(drawinfo^.dri_Pens)[BACKGROUNDPEN];
//* create a TextAttr that matches the specified font. */
myTextAttr.ta_Name := drawinfo^.dri_Font^.tf_Message.mn_Node.ln_Name;
myTextAttr.ta_YSize := drawinfo^.dri_Font^.tf_YSize;
myTextAttr.ta_Style := drawinfo^.dri_Font^.tf_Style;
myTextAttr.ta_Flags := drawinfo^.dri_Font^.tf_Flags;
{* open a simple window on the workbench screen for displaying
** a text string. An application would probably never use such a
** window, but it is useful for demonstrating graphics...
*}
if SetAndTest(win, OpenWindowTags(nil,
[
TAG_(WA_PubScreen) , TAG_(screen),
TAG_(WA_RMBTrap) , TAG_(TRUE),
TAG_END
])) then
begin
myIText.FrontPen := myTEXTPEN;
myIText.BackPen := myBACKGROUNDPEN;
myIText.DrawMode := JAM2;
myIText.LeftEdge := MYTEXT_LEFT;
myIText.TopEdge := MYTEXT_TOP;
myIText.ITextFont := @myTextAttr;
myIText.IText := 'Hello, World. ;-)';
myIText.NextText := nil;
//* Draw the text string at 10,10 */
PrintIText(win^.RPort, @myIText,10,10);
{* Wait a bit, then quit.
** In a real application, this would be an event loop,
** like the one described in the Intuition Input and
** Output Methods chapter.
*}
DOSDelay(200);
CloseWindow(win);
end;
FreeScreenDrawInfo(screen, drawinfo);
end;
UnlockPubScreen(nil, screen);
end;
{$IFDEF MORPHOS}
CloseLibrary(PLibrary(IntuitionBase));
{$ENDIF}
end;
end;
begin
Main(Argc, ArgV);
end.
|
unit fmPreviewPatterns;
interface
uses
RLFilters, RLPDFFilter, RLReport, ServerModule, krUtil,
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, uniGUITypes, uniGUIAbstractClasses,
uniGUIClasses, uniGUIForm, fmFormPatterns, uniBitBtn, uniButton, uniPanel,
uniGUIBaseClasses, uniURLFrame, Menus, uniMainMenu, uniMenuButton,
RLXLSXFilter, RLHTMLFilter, RLRichFilter, RLPreviewForm;
type
TfrmPreviewPatterns = class(TfrmFormPatterns)
UniURLFrame1: TUniURLFrame;
UniPanel1: TUniPanel;
btClose: TUniBitBtn;
UniPopupMenu1: TUniPopupMenu;
mnXLS: TUniMenuItem;
mnXLSX: TUniMenuItem;
UniPanel2: TUniPanel;
UniMenuButton1: TUniMenuButton;
mnHTML: TUniMenuItem;
mnRTF: TUniMenuItem;
procedure btCloseClick(Sender: TObject);
procedure UniFormShow(Sender: TObject);
procedure mnXLSClick(Sender: TObject);
procedure mnXLSXClick(Sender: TObject);
procedure mnHTMLClick(Sender: TObject);
procedure mnRTFClick(Sender: TObject);
private
RLReport01:TRLReport;
FRLReport: TRLReport;
FTitle: string;
procedure SetRLReport(const Value: TRLReport);
procedure SetTitle(const Value: string);
{ Private declarations }
public
procedure GerarPDF(Button:TUniBitBtn; Ext:String='.pdf');
property RLReport:TRLReport read FRLReport write SetRLReport;
property Title :string read FTitle write SetTitle;
{ Public declarations }
end;
function frmPreviewPatterns: TfrmPreviewPatterns;
implementation
{$R *.dfm}
uses
MainModule, uniGUIApplication;
function frmPreviewPatterns: TfrmPreviewPatterns;
begin
Result := TfrmPreviewPatterns(UniMainModule.GetFormInstance(TfrmPreviewPatterns));
end;
procedure TfrmPreviewPatterns.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TfrmPreviewPatterns.GerarPDF(Button:TUniBitBtn; Ext:String='.pdf');
Var
aFilename:String;
URL :String;
RLRichFilter:TRLRichFilter;
RLPDFFilter:TRLPDFFilter;
RLHTMLFilter:TRLHTMLFilter;
Begin
Button.Enabled := False;
aFilename:=UniServerModule.LocalCachePath + GerarNomeArquivo + Ext;
URL:='http://'+uniGUIApplication.UniSession.Host+'/'+UniServerModule.LocalCacheURL;
//
Try
Try
if Uppercase(Ext) = '.PDF' then
Begin
RLPDFFilter:=TRLPDFFilter.Create(self);
RLPDFFilter.DocumentInfo.Clear;
RLPDFFilter.DocumentInfo.Title := Title;
RLPDFFilter.DocumentInfo.Author := 'Jairo dos Santos Gurgel';
RLPDFFilter.DocumentInfo.Creator:= 'Polícia Civil do Ceará';
RLPDFFilter.FileName := aFilename;
End;
if Uppercase(Ext) = '.HTM' then
Begin
RLHTMLFilter:=TRLHTMLFilter.Create(self);
RLHTMLFilter.FileName := aFilename;
End;
if Uppercase(Ext) = '.RTF' then
Begin
RLRichFilter:=TRLRichFilter.Create(self);
RLRichFilter.FileName := aFilename;
End;
//
RLReport.ShowProgress := false;
RLReport.PrintDialog := false;
RLReport.ShowTracks := false;
RLReport.SaveToFile(aFilename);
Finally
if Uppercase(Ext) = '.PDF' then FreeAndNil(RLPDFFilter);
if Uppercase(Ext) = '.HTML' then FreeAndNil(RLHTMLFilter);
if Uppercase(Ext) = '.RTF' then FreeAndNil(RLRichFilter);
End;
Except
Button.Enabled := True;
End;
if (FileExists(aFilename)) and (Ext = '.pdf') then
UniURLFrame1.URL := URL + ExtractFileName(aFilename);
Show();
Button.Enabled := True;
End;
procedure TfrmPreviewPatterns.mnHTMLClick(Sender: TObject);
begin
inherited;
GerarPDF(btClose, '.htm');
end;
procedure TfrmPreviewPatterns.mnRTFClick(Sender: TObject);
begin
inherited;
GerarPDF(btClose, '.rtf');
end;
procedure TfrmPreviewPatterns.mnXLSClick(Sender: TObject);
begin
inherited;
GerarPDF(btClose, '.xls');
end;
procedure TfrmPreviewPatterns.mnXLSXClick(Sender: TObject);
begin
inherited;
GerarPDF(btClose, '.xlsx');
end;
procedure TfrmPreviewPatterns.SetRLReport(const Value: TRLReport);
begin
FRLReport := Value;
end;
procedure TfrmPreviewPatterns.SetTitle(const Value: string);
begin
FTitle := Value;
end;
procedure TfrmPreviewPatterns.UniFormShow(Sender: TObject);
begin
inherited;
WindowState := wsMaximized;
Width := Screen.Width;
end;
end.
{
Verônica
//7411 -> Vanessa DPM
}
|
PROGRAM AverageScore(INPUT, OUTPUT);
CONST
NumberOfScores = 4;
ClassSize = 4;
Base = 10;
HalfBase = Base DIV 2;
MinimumScore = 0;
MaximumScore = 100;
TYPE
Score = MinimumScore .. MaximumScore;
VAR
WhichScore: 1 .. NumberOfScores;
Student: 1 .. ClassSize;
NextScore: Score;
Ave, TotalScore, ClassTotal: INTEGER;
PROCEDURE SecondName(VAR InputFile: TEXT);
VAR
Ch1, Ch2: CHAR;
BEGIN
Ch1 := '-';
Ch2 := '-';
IF NOT EOLN(InputFile)
THEN
BEGIN
READ(InputFile, Ch2);
WHILE (Ch2 <> ' ')
DO
BEGIN
Ch1 := Ch2;
READ(InputFile, Ch2);
WRITE(Ch1)
END;
WRITE(' ')
END
END;
BEGIN {AverageScore}
ClassTotal := 0;
WRITELN('Student averages:');
Student := 1;
WHILE Student <= ClassSize
DO
BEGIN {Student <= ClassSize}
TotalScore := 0;
WhichScore := 1;
SecondName(INPUT);
WHILE WhichScore <= NumberOfScores
DO
BEGIN {WhichScore <= NumberOfScores}
READ(NextScore);
TotalScore := TotalScore + NextScore;
WhichScore := WhichScore + 1
END; {WhichScore <= NumberOfScores}
TotalScore := TotalScore * Base;
Ave := TotalScore DIV NumberOfScores;
IF Ave MOD Base >= HalfBase
THEN
WRITELN(Ave DIV Base + 1, ' ')
ELSE
WRITELN(Ave DIV Base, ' ');
ClassTotal := ClassTotal + TotalScore;
Student := Student + 1;
READLN
END; {Student <= ClassSize}
WRITELN;
WRITELN ('Class average:');
ClassTotal := ClassTotal DIV (ClassSize *NumberOfScores);
WRITELN(ClassTotal DIV Base, '.', ClassTotal MOD Base:1)
END. {AverageScore}
|
unit GoodsPartnerCode;
interface
uses
DataModul, Winapi.Windows, ParentForm, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxEdit, Data.DB, cxDBData, cxCurrencyEdit, cxCheckBox,
dsdAddOn, dsdDB, dsdAction, System.Classes, Vcl.ActnList, dxBarExtItems,
dxBar, cxClasses, cxPropertiesStore, Datasnap.DBClient, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridCustomView,
Vcl.Controls, cxGrid, AncestorGuides, cxPCdxBarPopupMenu, Vcl.Menus, cxPC,
dxSkinsCore, dxSkinsDefaultPainters, cxContainer, cxTextEdit, cxMaskEdit,
cxButtonEdit, cxLabel, dsdGuides, cxSplitter, Vcl.DBActns, dxBarBuiltInMenu,
cxNavigator, ExternalLoad, dxSkinscxPCPainter, dxSkinsdxBarPainter,
dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee,
dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast,
dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky,
dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue,
dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver,
dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, Vcl.ExtCtrls;
type
TGoodsPartnerCodeForm = class(TAncestorGuidesForm)
GoodsCodeInt: TcxGridDBColumn;
GoodsName: TcxGridDBColumn;
edPartnerCode: TcxButtonEdit;
cxLabel1: TcxLabel;
PartnerCodeGuides: TdsdGuides;
GoodsCode: TcxGridDBColumn;
RefreshDispatcher: TRefreshDispatcher;
mactDelete: TMultiAction;
GoodsMainName: TcxGridDBColumn;
GoodsMainCode: TcxGridDBColumn;
MakerName: TcxGridDBColumn;
spDeleteLink: TdsdStoredProc;
actDeleteLink: TdsdExecStoredProc;
DataSetPost: TDataSetPost;
mactSetLink: TMultiAction;
DataSetEdit: TDataSetEdit;
OpenChoiceForm: TOpenChoiceForm;
spInserUpdateGoodsLink: TdsdStoredProc;
actSetLink: TdsdExecStoredProc;
bbSetLink: TdxBarButton;
bbLabel: TdxBarControlContainerItem;
bbPartnerCode: TdxBarControlContainerItem;
dsdUpdateDataSet: TdsdUpdateDataSet;
MinimumLot: TcxGridDBColumn;
spUpdate_Goods_MinimumLot: TdsdStoredProc;
spDelete_ObjectFloat_Goods_MinimumLot: TdsdStoredProc;
actStartLoad: TMultiAction;
actDelete_ObjectFloat_Goods_MinimumLot: TdsdExecStoredProc;
actDoLoad: TExecuteImportSettingsAction;
spGetImportSetting_Goods_MinimumLot: TdsdStoredProc;
actGetImportSetting_Goods_MinimumLot: TdsdExecStoredProc;
bbStartLoad: TdxBarButton;
FormParams: TdsdFormParams;
IsUpload: TcxGridDBColumn;
spUpdate_Goods_IsUpload: TdsdStoredProc;
spGetImportSetting_Goods_IsUpload: TdsdStoredProc;
spDelete_ObjectBoolean_Goods_IsUpload: TdsdStoredProc;
actStartLoadIsUpload: TMultiAction;
actGetImportSetting_Goods_IsUpload: TdsdExecStoredProc;
actDelete_ObjectFloat_Goods_IsUpload: TdsdExecStoredProc;
actDoLoadIsUpload: TExecuteImportSettingsAction;
dxBarButton2: TdxBarButton;
spUpdate_Goods_Promo: TdsdStoredProc;
UpdateName: TcxGridDBColumn;
UpdateDate: TcxGridDBColumn;
spUpdate_Goods_IsSpecCondition: TdsdStoredProc;
isSpecCondition: TcxGridDBColumn;
actDoLoadIsSpecCondition: TExecuteImportSettingsAction;
actDelete_ObjectFloat_Goods_IsSpecCondition: TdsdExecStoredProc;
actGetImportSetting_Goods_IsSpecCondition: TdsdExecStoredProc;
actStartLoadIsSpecCondition: TMultiAction;
bbSpecCondition: TdxBarButton;
spGetImportSetting_Goods_IsSpecCondition: TdsdStoredProc;
spDelete_ObjectBoolean_Goods_IsSpecCondition: TdsdStoredProc;
actShowErased: TBooleanStoredProcAction;
spErasedUnErasedGoods: TdsdStoredProc;
dsdSetErasedGoogs: TdsdUpdateErased;
dsdSetUnErasedGoods: TdsdUpdateErased;
bbSetErasedGoogs: TdxBarButton;
bbSetUnErasedGoods: TdxBarButton;
bbShowErased: TdxBarButton;
isErased: TcxGridDBColumn;
CommonCode: TcxGridDBColumn;
ConditionsKeepChoiceForm: TOpenChoiceForm;
actDoLoadConditionsKeep: TExecuteImportSettingsAction;
actGetImportSetting_Goods_ConditionsKeep: TdsdExecStoredProc;
actStartLoadConditionsKeep: TMultiAction;
spUpdate_Goods_ConditionsKeep: TdsdStoredProc;
spGetImportSetting_Goods_ConditionsKeep: TdsdStoredProc;
bbStartLoadConditionsKeep: TdxBarButton;
bbIsUpdate: TdxBarControlContainerItem;
cbUpdate: TcxCheckBox;
spUpdate_Goods_isUploadBadm: TdsdStoredProc;
isUploadTeva: TcxGridDBColumn;
spUpdate_Goods_isUploadTeva: TdsdStoredProc;
AreaName: TcxGridDBColumn;
Panel: TPanel;
cxLabel6: TcxLabel;
edArea: TcxButtonEdit;
GuidesArea: TdsdGuides;
ProtocolOpenTwoForm: TdsdOpenForm;
bbProtocolOpenTwoForm: TdxBarButton;
spUpdate_Goods_isUploadYuriFarm: TdsdStoredProc;
isUploadYuriFarm: TcxGridDBColumn;
spUpdate_Goods_Promo_True: TdsdStoredProc;
spUpdate_Goods_Promo_False: TdsdStoredProc;
actUpdate_Goods_Promo_True: TMultiAction;
actExecUpdate_Goods_Promo_True: TdsdExecStoredProc;
actUpdate_Goods_Promo_False: TMultiAction;
actExecUpdate_Goods_Promo_False: TdsdExecStoredProc;
bbUpdate_Goods_Promo_True: TdxBarButton;
bbUpdate_Goods_Promo_False: TdxBarButton;
DiscountExternalName: TcxGridDBColumn;
DiscountExternalChoiceForm: TOpenChoiceForm;
spUpdate_Goods_DiscountExternal: TdsdStoredProc;
dxBarSubItem1: TdxBarSubItem;
actStartLoadAction: TMultiAction;
actGetImportSetting_Goods_Action: TdsdExecStoredProc;
actDoLoadAction: TExecuteImportSettingsAction;
spGetImportSetting_Goods_Ąction: TdsdStoredProc;
dxBarButton1: TdxBarButton;
PromoBonus: TcxGridDBColumn;
PromoBonusName: TcxGridDBColumn;
dxBarButton3: TdxBarButton;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TGoodsPartnerCodeForm);
end.
|
unit UCL.TUScrollBox;
interface
uses
FlatSB,
UCL.Classes, UCL.TUThemeManager, UCL.IntAnimation,
System.Classes, System.SysUtils, System.TypInfo,
Winapi.Messages, Winapi.Windows,
VCL.Controls, VCL.Forms;
type
TUScrollBox = class(TScrollBox, IUThemeControl)
private
FThemeManager: TUThemeManager;
FIsScrolling: Boolean;
FScrollLength: Integer;
FScrollTime: Integer;
FScrollOrientation: TUOrientation;
FShowScrollBar: Boolean;
// Setters
procedure SetThemeManager(const Value: TUThemeManager);
// Messages
procedure WM_MouseWheel(var Msg: TWMMouseWheel); message WM_MOUSEWHEEL;
procedure WM_Paint(var Msg: TWMPaint); message WM_PAINT;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; reintroduce;
procedure AfterContrusction;
procedure UpdateTheme;
procedure HideScrollBar;
published
property ThemeManager: TUThemeManager read FThemeManager write SetThemeManager;
property IsScrolling: Boolean read FIsScrolling;
property ScrollLength: Integer read FScrollLength write FScrollLength default 320;
property ScrollTime: Integer read FScrollTime write FScrollTime default 300;
property ScrollOrientation: TUOrientation read FScrollOrientation write FScrollOrientation default oVertical;
property ShowScrollBar: Boolean read FShowScrollBar write FShowScrollBar default false;
end;
implementation
{ THEME }
procedure TUScrollBox.SetThemeManager(const Value: TUThemeManager);
begin
if Value <> FThemeManager then
begin
// Disconnect current ThemeManager
if FThemeManager <> nil then
FThemeManager.DisconnectControl(Self);
// Connect to new ThemeManager
if Value <> nil then
Value.ConnectControl(Self);
FThemeManager := Value;
UpdateTheme;
end;
end;
procedure TUScrollBox.UpdateTheme;
begin
if ThemeManager = nil then
Color := $00E6E6E6
else if ThemeManager.Theme = utLight then
Color := $00E6E6E6
else
Color := $001F1F1F;
end;
{ MAIN CLASS }
procedure TUScrollBox.AfterContrusction;
begin
InitializeFlatSB(Handle);
end;
constructor TUScrollBox.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
DoubleBuffered := true;
BorderStyle := bsNone;
FIsScrolling := false;
FScrollLength := 320;
FScrollTime := 300;
FScrollOrientation := oVertical;
UpdateTheme;
end;
destructor TUScrollBox.Destroy;
begin
UninitializeFlatSB(Handle);
inherited Destroy;
end;
{ MESSAGES }
procedure TUScrollBox.WM_MouseWheel(var Msg: TWMMouseWheel);
var
Ani: TIntAni;
Start, Stop: Integer;
aScrollbar: TControlScrollBar;
begin
inherited;
if FIsScrolling = true then
exit
else
FIsScrolling := true;
if ScrollOrientation = oVertical then
aScrollbar := VertScrollBar
else
aScrollbar := HorzScrollBar;
Start := aScrollbar.Position;
Stop := aScrollbar.Position - ScrollLength * Msg.WheelDelta div Abs(Msg.WheelDelta);
// If ScrollLength > Out of range, reduce it to fit
if Stop < 0 then
Stop := 0
else if Stop > aScrollbar.Range then
Stop := aScrollbar.Range;
Ani := TIntAni.Create(akOut, afkQuartic, Start, Stop,
procedure (Value: Integer)
begin
aScrollbar.Position := Value;
end, true);
// On scroll done
Ani.OnDone :=
procedure
begin
FIsScrolling := false;
if ShowScrollBar = false then
HideScrollBar;
end;
Ani.Step := 20;
Ani.Duration := ScrollTime;
if csDesigning in ComponentState = false then
EnableAlign; // Neccesary
Ani.Start;
end;
procedure TUScrollBox.WM_Paint(var Msg: TWMPaint);
begin
// Hide scrollbar after construction
inherited;
if ShowScrollBar = false then
HideScrollBar;
end;
procedure TUScrollBox.HideScrollBar;
begin
if csDesigning in ComponentState = false then
FlatSB_ShowScrollBar(Handle, SB_BOTH, false);
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 2010-2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Androidapi.IOUtils;
interface
// File Locations in Internal memory. (Accessible only to the program.
// Not accessible to anyone without rooting the Android system.)
// Files written here are deleted when uninstalling the application.)
function GetFilesDir: string;
function GetCacheDir: string;
function GetLibraryPath: string;
// File Locations in External memory. (Accessible only to the program, but easily
// readable mounting the external storage as a drive in a computer.
// Files written here are deleted when uninstalling the application.)
function GetExternalFilesDir: string;
function GetExternalCacheDir: string;
function GetExternalPicturesDir: string;
function GetExternalCameraDir: string;
function GetExternalDownloadsDir: string;
function GetExternalMoviesDir: string;
function GetExternalMusicDir: string;
function GetExternalAlarmsDir: string;
function GetExternalRingtonesDir: string;
// File Locations in External memory. (Accessible to all programs, easily
// readable mounting the external storage as a drive in a computer.
// Files written here are preserved when uninstalling the application.)
function GetSharedFilesDir: string;
function GetSharedPicturesDir: string;
function GetSharedCameraDir: string;
function GetSharedDownloadsDir: string;
function GetSharedMoviesDir: string;
function GetSharedMusicDir: string;
function GetSharedAlarmsDir: string;
function GetSharedRingtonesDir: string;
implementation
uses
Androidapi.Jni,
Androidapi.NativeActivity;
function GetJniPath(MethodName, Signature: MarshaledAString): string;
var
PEnv: PJniEnv;
ActivityClass: JNIClass;
FileClass: JNIClass;
GetMethod: JNIMethodID;
GetPathMethod: JNIMethodID;
PActivity: PANativeActivity;
StrPathObject: JNIObject;
FileObject: JNIObject;
begin
PActivity := PANativeActivity(System.DelphiActivity);
PActivity^.vm^.AttachCurrentThread(PActivity^.vm, @PEnv, nil);
ActivityClass := PEnv^.GetObjectClass(PEnv, PActivity^.clazz);
GetMethod := PEnv^.GetMethodID(PEnv, ActivityClass, MethodName, Signature);
FileObject := PEnv^.CallObjectMethodA(PEnv, PActivity^.clazz, GetMethod, PJNIValue(ArgsToJNIValues([nil])));
if FileObject = nil then
Exit('');
FileClass := PEnv^.GetObjectClass(PEnv, FileObject);
GetPathMethod := PEnv^.GetMethodID(PEnv, FileClass, 'getPath', '()Ljava/lang/String;');
StrPathObject := PEnv^.CallObjectMethodA(PEnv, FileObject, GetPathMethod, PJNIValue(ArgsToJNIValues([])));
Result := JNIStringToString(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, FileClass);
PEnv^.DeleteLocalRef(PEnv, FileObject);
PEnv^.DeleteLocalRef(PEnv, ActivityClass);
end;
{
public static String DIRECTORY_ALARMS Standard directory in which to place any audio files that should be in the list of alarms that the user can select (not as regular music).
public static String DIRECTORY_DCIM The traditional location for pictures and videos when mounting the device as a camera.
public static String DIRECTORY_DOWNLOADS Standard directory in which to place files that have been downloaded by the user.
public static String DIRECTORY_MOVIES Standard directory in which to place movies that are available to the user.
public static String DIRECTORY_MUSIC Standard directory in which to place any audio files that should be in the regular list of music for the user.
public static String DIRECTORY_NOTIFICATIONS Standard directory in which to place any audio files that should be in the list of notifications that the user can select (not as regular music).
public static String DIRECTORY_PICTURES Standard directory in which to place pictures that are available to the user.
public static String DIRECTORY_PODCASTS Standard directory in which to place any audio files that should be in the list of podcasts that the user can select (not as regular music).
public static String DIRECTORY_RINGTONES Standard directory in which to place any audio files that should be in the list of ringtones that the user can select (not as regular music).}
type
TCustomPathType = (cpNONE, cpALARMS, cpDCIM, cpDOWNLOADS, cpMOVIES,
cpMUSIC, cpNOTIFICATIONS, cpPICTURES, cpPODCASTS, cpRINGTONES);
function GetJniCustomPath(MethodName, Signature: MarshaledAString; PathType:TCustomPathType): string;
var
PEnv: PJniEnv;
ActivityClass, EnvironmentClass: JNIClass;
FileClass: JNIClass;
GetMethod: JNIMethodID;
GetPathMethod: JNIMethodID;
PActivity: PANativeActivity;
StrPathObject: JNIObject;
CustomPathObject: JNIObject;
FileObject: JNIObject;
PathFieldID: JNIFieldID;
begin
PActivity := PANativeActivity(System.DelphiActivity);
PActivity^.vm^.AttachCurrentThread(PActivity^.vm, @PEnv, nil);
ActivityClass := PEnv^.GetObjectClass(PEnv, PActivity^.clazz);
EnvironmentClass := PEnv^.FindClass(PEnv, 'android/os/Environment');
case PathType of
cpPICTURES: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_PICTURES', 'Ljava/lang/String;');
cpDOWNLOADS: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_DOWNLOADS', 'Ljava/lang/String;');
cpDCIM: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_DCIM', 'Ljava/lang/String;');
cpMOVIES: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_MOVIES', 'Ljava/lang/String;');
cpALARMS: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_ALARMS', 'Ljava/lang/String;');
cpMUSIC: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_MUSIC', 'Ljava/lang/String;');
cpNOTIFICATIONS: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_NOTIFICATIONS', 'Ljava/lang/String;');
cpPODCASTS: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_PODCASTS', 'Ljava/lang/String;');
cpRINGTONES: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_RINGTONES', 'Ljava/lang/String;');
else
PathFieldID := nil;
end;
if PathFieldID = nil then
CustomPathObject := nil
else
CustomPathObject := PEnv^.GetStaticObjectField(PEnv, EnvironmentClass, PathFieldID);
GetMethod := PEnv^.GetMethodID(PEnv, ActivityClass, MethodName, Signature);
FileObject := PEnv^.CallObjectMethodA(PEnv, PActivity^.clazz, GetMethod, PJNIValue(ArgsToJNIValues([CustomPathObject])));
if FileObject = nil then
Exit('');
FileClass := PEnv^.GetObjectClass(PEnv, FileObject);
GetPathMethod := PEnv^.GetMethodID(PEnv, FileClass, 'getPath', '()Ljava/lang/String;');
StrPathObject := PEnv^.CallObjectMethodA(PEnv, FileObject, GetPathMethod, PJNIValue(ArgsToJNIValues([])));
Result := JNIStringToString(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, StrPathObject);
if CustomPathObject <> nil then PEnv^.DeleteLocalRef(PEnv, CustomPathObject);
PEnv^.DeleteLocalRef(PEnv, FileClass);
PEnv^.DeleteLocalRef(PEnv, FileObject);
PEnv^.DeleteLocalRef(PEnv, EnvironmentClass);
PEnv^.DeleteLocalRef(PEnv, ActivityClass);
end;
function GetJniCustomPath2(MethodName, Signature: MarshaledAString; PathType:TCustomPathType): string;
var
PEnv: PJniEnv;
ActivityClass, EnvironmentClass: JNIClass;
FileClass: JNIClass;
GetMethod: JNIMethodID;
GetPathMethod: JNIMethodID;
PActivity: PANativeActivity;
StrPathObject: JNIObject;
CustomPathObject: JNIObject;
FileObject: JNIObject;
PathFieldID: JNIFieldID;
begin
PActivity := PANativeActivity(System.DelphiActivity);
PActivity^.vm^.AttachCurrentThread(PActivity^.vm, @PEnv, nil);
ActivityClass := PEnv^.GetObjectClass(PEnv, PActivity^.clazz);
EnvironmentClass := PEnv^.FindClass(PEnv, 'android/os/Environment');
case PathType of
cpPICTURES: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_PICTURES', 'Ljava/lang/String;');
cpDOWNLOADS: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_DOWNLOADS', 'Ljava/lang/String;');
cpDCIM: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_DCIM', 'Ljava/lang/String;');
cpMOVIES: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_MOVIES', 'Ljava/lang/String;');
cpALARMS: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_ALARMS', 'Ljava/lang/String;');
cpMUSIC: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_MUSIC', 'Ljava/lang/String;');
cpNOTIFICATIONS: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_NOTIFICATIONS', 'Ljava/lang/String;');
cpPODCASTS: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_PODCASTS', 'Ljava/lang/String;');
cpRINGTONES: PathFieldID := PEnv^.GetStaticFieldID(PEnv, EnvironmentClass, 'DIRECTORY_RINGTONES', 'Ljava/lang/String;');
else
PathFieldID := nil;
end;
if PathFieldID = nil then
CustomPathObject := nil
else
CustomPathObject := PEnv^.GetStaticObjectField(PEnv, EnvironmentClass, PathFieldID);
GetMethod := PEnv^.GetStaticMethodID(PEnv, EnvironmentClass, MethodName, Signature);
FileObject := PEnv^.CallStaticObjectMethodA(PEnv, EnvironmentClass, GetMethod, PJNIValue(ArgsToJNIValues([CustomPathObject])));
if FileObject = nil then
Exit('');
FileClass := PEnv^.GetObjectClass(PEnv, FileObject);
GetPathMethod := PEnv^.GetMethodID(PEnv, FileClass, 'getPath', '()Ljava/lang/String;');
StrPathObject := PEnv^.CallObjectMethodA(PEnv, FileObject, GetPathMethod, PJNIValue(ArgsToJNIValues([])));
Result := JNIStringToString(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, StrPathObject);
if CustomPathObject <> nil then PEnv^.DeleteLocalRef(PEnv, CustomPathObject);
PEnv^.DeleteLocalRef(PEnv, FileClass);
PEnv^.DeleteLocalRef(PEnv, FileObject);
PEnv^.DeleteLocalRef(PEnv, EnvironmentClass);
PEnv^.DeleteLocalRef(PEnv, ActivityClass);
end;
function GetLibraryPath: string;
var
PEnv: PJniEnv;
ActivityClass: JNIClass;
FileClass: JNIClass;
GetMethod: JNIMethodID;
PropertyID: JNIFieldID;
PActivity: PANativeActivity;
StrPathObject: JNIObject;
FileObject: JNIObject;
begin
PActivity := PANativeActivity(System.DelphiActivity);
PActivity^.vm^.AttachCurrentThread(PActivity^.vm, @PEnv, nil);
ActivityClass := PEnv^.GetObjectClass(PEnv, PActivity^.clazz);
GetMethod := PEnv^.GetMethodID(PEnv, ActivityClass, 'getApplicationInfo', '()Landroid/content/pm/ApplicationInfo;');
FileObject := PEnv^.CallObjectMethodA(PEnv, PActivity^.clazz, GetMethod, PJNIValue(ArgsToJNIValues([nil])));
if FileObject = nil then
Exit('');
FileClass := PEnv^.GetObjectClass(PEnv, FileObject);
PropertyID := PEnv^.GetFieldID(PEnv, FileClass, 'nativeLibraryDir', 'Ljava/lang/String;');
StrPathObject := PEnv^.GetObjectField(PEnv, FileObject, PropertyID);
Result := JNIStringToString(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, StrPathObject);
PEnv^.DeleteLocalRef(PEnv, FileClass);
PEnv^.DeleteLocalRef(PEnv, FileObject);
PEnv^.DeleteLocalRef(PEnv, ActivityClass);
end;
function GetFilesDir: string;
begin
{ There is a bug inside ndk on versions previous to version 10 that makes
internal and external paths are wrong in the Native Activity variable
so we need to retrieve them via jni }
// if ANativeActivity(system.DelphiActivity^).sdkVersion > 10 then
// Result := UTF8Tostring(ANativeActivity(system.DelphiActivity^).internalDataPath)
// else
{ Also retrieving it via JNI, ensures that the retrieved path exists.
The folder is created if it does not exist. This way we can avoid the problem
that if we do it via NativeActivity we can have problems trying to write to
the folder if we do not do a previous ForceDirectories.
}
Result := GetJniPath('getFilesDir', '()Ljava/io/File;');
end;
function GetExternalFilesDir: string;
begin
{ There is a bug inside ndk on versions previous to version 10(included)(2.3.3) that makes
internal and external paths are wrong in the Native Activity variable
so we need to retrieve them via jni }
// if ANativeActivity(system.DelphiActivity^).sdkVersion > 10 then
// Result := UTF8Tostring(ANativeActivity(system.DelphiActivity^).externalDataPath);
// else
{ Also retrieving it via JNI, ensures that the retrieved path exists.
The folder is created if it does not exist. This way we can avoid the problem
that if we do it via NativeActivity we can have problems trying to write to
the folder if we do not do a previous ForceDirectories.
}
// Result := GetJniPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;');
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpNONE);
end;
function GetCacheDir: string;
begin
Result := GetJniPath('getCacheDir', '()Ljava/io/File;');
end;
function GetExternalCacheDir: string;
begin
Result := GetJniPath('getExternalCacheDir', '()Ljava/io/File;');
end;
function GetExternalPicturesDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpPICTURES);
end;
function GetExternalCameraDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpDCIM);
end;
function GetExternalDownloadsDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpDOWNLOADS);
end;
function GetExternalMoviesDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpMOVIES);
end;
function GetExternalMusicDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpMUSIC);
end;
function GetExternalAlarmsDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpALARMS);
end;
function GetExternalRingtonesDir: string;
begin
Result := GetJniCustomPath('getExternalFilesDir', '(Ljava/lang/String;)Ljava/io/File;', cpRINGTONES);
end;
// Shared Folders functions.
function GetSharedFilesDir: string;
begin
Result := GetJniCustomPath2('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpDOWNLOADS);
end;
function GetSharedPicturesDir: string;
begin
Result := GetJniCustomPath2('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpPICTURES);
end;
function GetSharedCameraDir: string;
begin
Result := GetJniCustomPath2('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpDCIM);
end;
function GetSharedDownloadsDir: string;
begin
Result := GetJniCustomPath2('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpDOWNLOADS);
end;
function GetSharedMoviesDir: string;
begin
Result := GetJniCustomPath2('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpMOVIES);
end;
function GetSharedMusicDir: string;
begin
Result := GetJniCustomPath2('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpMUSIC);
end;
function GetSharedAlarmsDir: string;
begin
Result := GetJniCustomPath2('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpALARMS);
end;
function GetSharedRingtonesDir: string;
begin
Result := GetJniCustomPath2('getExternalStoragePublicDirectory', '(Ljava/lang/String;)Ljava/io/File;', cpRINGTONES);
end;
end.
|
unit uscanthread;
interface
uses
ucommon, utim, uscanresult, classes, fgl;
type
TScanThread = class(TThread)
private
{ Private declarations }
pScanResult: TScanResult;
pResults: PScanResultList;
pFileSize: Integer;
pFilePos: Integer;
pStatusText: string;
pClearBufferPosition: Integer;
pClearBufferSize: Integer;
pSectorBufferSize: Integer;
pSrcFileStream: TFileStream;
pStopScan: boolean;
procedure SetStatusText;
procedure FinishScan;
procedure UpdateProgressBar;
procedure AddResult(TIM: PTIM);
procedure ClearSectorBuffer(SectorBuffer, ClearBuffer: PBytesArray);
protected
procedure Execute; override;
public
constructor Create(const FileToScan: string; ImageScan: boolean; Results: PScanResultList);
//property Started: boolean read pStarted write pStarted;
property StopScan: boolean read pStopScan write pStopScan;
property FileLength: Integer read pFileSize;
end;
TScanThreadList = specialize TFPGObjectList<TScanThread>;
implementation
uses
umain, ucdimage, sysutils, FileUtil;
const
cClearBufferSize = ((cTIMMaxSize div cSectorDataSize) + 1) * cSectorDataSize * 2;
cSectorBufferSize = (cClearBufferSize div cSectorDataSize) * cSectorSize;
{ TScanThread }
constructor TScanThread.Create(const FileToScan: string; ImageScan: boolean; Results: PScanResultList);
begin
inherited Create(True);
FreeOnTerminate := True;
pClearBufferPosition := 0;
pFilePos := 0;
pFileSize := FileSize(FileToScan);
pStatusText := '';
pStopScan := False;
pScanResult := TScanResult.Create;
pScanResult.ScanFile := FileToScan;
pScanResult.IsImage := ImageScan;
pResults := Results;
end;
procedure TScanThread.AddResult(TIM: PTIM);
var
ScanTim: TTimInfo;
begin
ScanTim.Magic := TIM^.HEAD^.bMagic;
ScanTim.Position := TIM^.dwTimPosition;
ScanTim.Size := TIM^.dwSIZE;
ScanTim.Width := GetTimRealWidth(TIM);
ScanTim.Height := GetTimHeight(TIM);
ScanTim.Bitmode := BppToBitMode(TIM);
if TIMHasCLUT(TIM) then
ScanTim.Cluts := GetTimClutsCount(TIM)
else
ScanTim.Cluts := 0;
ScanTim.Good := TIMIsGood(TIM);
pScanResult.Count := TIM^.dwTimNumber;
pScanResult.ScanTim[pScanResult.Count - 1] := ScanTim;
end;
procedure TScanThread.Execute;
var
SectorBuffer, ClearBuffer: PBytesArray;
TIM: PTIM;
pScanFinished: boolean;
pRealBufSize, pTimPosition, pTIMNumber: Integer;
begin
if pScanResult.IsImage then
pSectorBufferSize := cSectorBufferSize
else
pSectorBufferSize := cClearBufferSize;
pClearBufferSize := cClearBufferSize;
SectorBuffer := GetMemory(pSectorBufferSize);
ClearBuffer := GetMemory(pClearBufferSize);
pSrcFileStream := TFileStream.Create(UTF8ToSys(pScanResult.ScanFile), fmOpenRead or fmShareDenyWrite);
pSrcFileStream.Position := 0;
TIM := CreateTIM;
pStatusText := sStatusBarScanningFile;
Synchronize(@SetStatusText);
pRealBufSize := pSrcFileStream.Read(SectorBuffer^[0], pSectorBufferSize);
Inc(pFilePos, pRealBufSize);
ClearSectorBuffer(SectorBuffer, ClearBuffer);
pScanFinished := False;
pTIMNumber := 0;
while (not pStopScan) and (not Terminated) do
begin
if LoadTimFromBuf(ClearBuffer, TIM, pClearBufferPosition) then
begin
if pScanResult.IsImage then
pTimPosition := pFilePos - pRealBufSize +
((pClearBufferPosition - 1) div cSectorDataSize) * cSectorSize +
((pClearBufferPosition - 1) mod cSectorDataSize) + cSectorInfoSize
else
pTimPosition := pFilePos - pRealBufSize + (pClearBufferPosition - 1);
if pTimPosition >= pFileSize then Break;
TIM^.dwTimPosition := pTimPosition;
Inc(pTIMNumber);
TIM^.dwTimNumber := pTIMNumber;
AddResult(TIM);
end;
if pClearBufferPosition = (pClearBufferSize div 2) then
begin
if pScanFinished then Break;
pScanFinished := (pFilePos = pFileSize);
pClearBufferPosition := 0;
Move(SectorBuffer^[pSectorBufferSize div 2], SectorBuffer^[0], pSectorBufferSize div 2);
if pScanFinished then
begin
if pRealBufSize >= (pSectorBufferSize div 2) then
// Need to check file size
pRealBufSize := pRealBufSize - (pSectorBufferSize div 2);
end
else
begin
pRealBufSize := pSrcFileStream.Read(SectorBuffer^[pSectorBufferSize div 2], pSectorBufferSize div 2);
Inc(pFilePos, pRealBufSize);
pRealBufSize := pRealBufSize + (pSectorBufferSize div 2);
end;
Synchronize(@UpdateProgressBar);
ClearSectorBuffer(SectorBuffer, ClearBuffer);
end;
end;
FreeTIM(TIM);
FreeMemory(SectorBuffer);
FreeMemory(ClearBuffer);
pSrcFileStream.Free;
pStopScan := True;
pFilePos := 0;
pStatusText := '';
FinishScan;
end;
procedure TScanThread.FinishScan;
begin
UpdateProgressBar;
SetStatusText;
if pScanResult.Count = 0 then
begin
pScanResult.Free;
Exit;
end;
if not CheckForFileOpened(pResults, pScanResult.ScanFile) then
begin
pResults^.Add(pScanResult);
frmMain.cbbFiles.Items.Add(pScanResult.ScanFile);
end
else
pScanResult.Free;
end;
procedure TScanThread.SetStatusText;
begin
frmMain.lblStatus.Caption := pStatusText;
end;
procedure TScanThread.UpdateProgressBar;
begin
frmMain.pbProgress.Position := pFilePos;
frmMain.lvList.Column[0].Caption := Format('# / %d', [pScanResult.Count]);
end;
procedure TScanThread.ClearSectorBuffer(SectorBuffer, ClearBuffer: PBytesArray);
var
i: Integer;
begin
FillChar(ClearBuffer^[0], pClearBufferSize, 0);
if not pScanResult.IsImage then
begin
Move(SectorBuffer^[0], ClearBuffer^[0], pClearBufferSize);
Exit;
end;
for i := 1 to (pSectorBufferSize div cSectorSize) do
begin
Move(SectorBuffer^[(i - 1) * cSectorSize + cSectorInfoSize],
ClearBuffer^[(i - 1) * cSectorDataSize], cSectorDataSize);
end;
end;
end.
|
unit JSON.VendorList;
// *************************************************
// Generated By: JsonToDelphiClass - 0.65
// Project link: https://github.com/PKGeorgiev/Delphi-JsonToDelphiClass
// Generated On: 2019-05-22 19:53:00
// *************************************************
// Created By : Petar Georgiev - 2014
// WebSite : http://pgeorgiev.com
// *************************************************
interface
uses
Generics.Collections
, Rest.Json
, REST.JSON.Types
;
type
TMetaDataClass = class
private
FCreateTime: String;
FLastUpdatedTime: String;
public
property CreateTime: String read FCreateTime write FCreateTime;
property LastUpdatedTime: String read FLastUpdatedTime write FLastUpdatedTime;
function ToJsonString: string;
class function FromJsonString(AJsonString: string): TMetaDataClass;
end;
TVendorClass = class
private
FActive: Boolean;
FBalance: Extended;
FDisplayName: String;
FId: String;
FMetaData: TMetaDataClass;
FPrintOnCheckName: String;
FSyncToken: String;
FVendor1099: Boolean;
FDomain: String;
FSparse: Boolean;
public
property Active: Boolean read FActive write FActive;
property Balance: Extended read FBalance write FBalance;
property DisplayName: String read FDisplayName write FDisplayName;
property Id: String read FId write FId;
property MetaData: TMetaDataClass read FMetaData write FMetaData;
property PrintOnCheckName: String read FPrintOnCheckName write FPrintOnCheckName;
property SyncToken: String read FSyncToken write FSyncToken;
property Vendor1099: Boolean read FVendor1099 write FVendor1099;
property domain: String read FDomain write FDomain;
property sparse: Boolean read FSparse write FSparse;
constructor Create;
destructor Destroy; override;
function ToJsonString: string;
class function FromJsonString(AJsonString: string): TVendorClass;
end;
TQueryResponseClass = class
private
FVendor: TArray<TVendorClass>;
FMaxResults: Extended;
FStartPosition: Extended;
public
property Vendor: TArray<TVendorClass> read FVendor write FVendor;
property maxResults: Extended read FMaxResults write FMaxResults;
property startPosition: Extended read FStartPosition write FStartPosition;
destructor Destroy; override;
function ToJsonString: string;
class function FromJsonString(AJsonString: string): TQueryResponseClass;
end;
TJSONVendorListClass = class
private
FQueryResponse: TQueryResponseClass;
FTime: String;
public
property QueryResponse: TQueryResponseClass read FQueryResponse write FQueryResponse;
property time: String read FTime write FTime;
constructor Create;
destructor Destroy; override;
function ToJsonString: string;
class function FromJsonString(AJsonString: string): TJSONVendorListClass;
end;
implementation
{TMetaDataClass}
function TMetaDataClass.ToJsonString: string;
begin
result := TJson.ObjectToJsonString(self);
end;
class function TMetaDataClass.FromJsonString(AJsonString: string): TMetaDataClass;
begin
result := TJson.JsonToObject<TMetaDataClass>(AJsonString)
end;
{TVendorClass}
constructor TVendorClass.Create;
begin
inherited;
FMetaData := TMetaDataClass.Create;
end;
destructor TVendorClass.Destroy;
begin
FMetaData.free;
inherited;
end;
function TVendorClass.ToJsonString: string;
begin
result := TJson.ObjectToJsonString(self);
end;
class function TVendorClass.FromJsonString(AJsonString: string): TVendorClass;
begin
result := TJson.JsonToObject<TVendorClass>(AJsonString)
end;
{TQueryResponseClass}
destructor TQueryResponseClass.Destroy;
var
LVendorItem: TVendorClass;
begin
for LVendorItem in FVendor do
LVendorItem.free;
inherited;
end;
function TQueryResponseClass.ToJsonString: string;
begin
result := TJson.ObjectToJsonString(self);
end;
class function TQueryResponseClass.FromJsonString(AJsonString: string): TQueryResponseClass;
begin
result := TJson.JsonToObject<TQueryResponseClass>(AJsonString)
end;
{TRootClass}
constructor TJSONVendorListClass.Create;
begin
inherited;
FQueryResponse := TQueryResponseClass.Create;
end;
destructor TJSONVendorListClass.Destroy;
begin
FQueryResponse.free;
inherited;
end;
function TJSONVendorListClass.ToJsonString: string;
begin
result := TJson.ObjectToJsonString(self);
end;
class function TJSONVendorListClass.FromJsonString(AJsonString: string): TJSONVendorListClass;
begin
result := TJson.JsonToObject<TJSONVendorListClass>(AJsonString)
end;
end.
|
unit HdExcpEx;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,DB, BDE;
type
TErrorMsgDialog = class(TForm)
btnOK: TButton;
btnDetail: TButton;
mmMsgs: TMemo;
mmInfo: TMemo;
procedure btnDetailClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FisShowDetails: boolean;
procedure SetisShowDetails(const Value: boolean);
class procedure HandleAppError(Sender: TObject; E: Exception);
{ Private declarations }
public
{ Public declarations }
property isShowDetails : boolean read FisShowDetails write SetisShowDetails;
procedure Execute(E : Exception);
end;
var
ErrorMsgDialog: TErrorMsgDialog;
threadvar
CurProgressMsg : string;
procedure SetProgressMsg(const Msg:string);
procedure ClearProgressMsg;
procedure HandleProgressException;
procedure HandleThisException(E : Exception);
procedure InstallExceptHanlder;
const
KnownExceptCount = 12;
KnownExceptions : array[1..KnownExceptCount] of ExceptClass
= ( EOutOfMemory,
EInvalidPointer,
EHeapException,
EInOutError,
EIntError,
EMathError,
EAccessViolation,
EStackOverflow,
EExternal,
EWin32Error,
EDatabaseError,
Exception
);
KnownExceptionInfos : array[1..KnownExceptCount] of string[20]
= ( '内存溢出',
'无效指针',
'堆',
'输入输出',
'整数运算',
'数学运算',
'访问地址',
'堆栈溢出',
'外部',
'Win32操作系统',
'数据库操作',
''
);
implementation
{$R *.DFM}
procedure SetProgressMsg(const Msg:string);
begin
CurProgressMsg := Msg;
end;
procedure ClearProgressMsg;
begin
CurProgressMsg := '';
end;
procedure HandleProgressException;
var
E : Exception;
begin
E := Exception(ExceptObject);
HandleThisException(E);
end;
procedure HandleThisException(E : Exception);
var
Dialog : TErrorMsgDialog;
begin
if (E<>nil) and not (E is EAbort) then
begin
Dialog := TErrorMsgDialog.Create(nil);
try
Dialog.Execute(E);
finally
Dialog.free;
end;
end;
end;
procedure InstallExceptHanlder;
begin
if Application<>nil then
Application.OnException := TErrorMsgDialog.HandleAppError;
end;
procedure TErrorMsgDialog.btnDetailClick(Sender: TObject);
begin
isShowDetails := not isShowDetails;
end;
procedure TErrorMsgDialog.Execute(E: Exception);
var
Info,Msg,ExtraInfo : string;
i : integer;
begin
assert(E<>nil);
ExtraInfo := '';
mmInfo.lines.clear;
mmMsgs.lines.clear;
// Set Info
if CurProgressMsg<>'' then Info := ' 在进行'+CurProgressMsg+'操作时发生'
else Info := ' 发生';
CurProgressMsg:='';
for i:=1 to KnownExceptCount do
if E is KnownExceptions[i] then
begin
Info := Info + KnownExceptionInfos[i];
break;
end;
Info := Info+'错误';
// set Msg
Msg := E.ClassName+#13#10;
// set Database Error Msg
if E is EDBEngineError then
with EDBEngineError(E) do
begin
for i:=0 to ErrorCount-1 do
with Errors[i] do
begin
Msg := format('%s[%d] (Catalog: %d,SubCode: %d,Server Code: %d)'#13#10' %s'#13#10,
[Msg,I+1,Category,SubCode,NativeError,Message]);
case Category of
ERRCAT_SYSTEM : ExtraInfo := ExtraInfo + ' (数据库引擎错误) ';
ERRCAT_NOTFOUND : ExtraInfo := ExtraInfo + ' (找不到记录) ';
ERRCAT_DATACORRUPT : ExtraInfo := ExtraInfo + ' (数据被破坏) ';
ERRCAT_IO : ExtraInfo := ExtraInfo + ' (I/O错误) ';
ERRCAT_LIMIT : ExtraInfo := ExtraInfo + ' (系统资源溢出) ';
ERRCAT_INTEGRITY : ExtraInfo := ExtraInfo + ' (数据一致性错误) ';
ERRCAT_INVALIDREQ: ExtraInfo := ExtraInfo + ' (无效的参数) ';
ERRCAT_LOCKCONFLICT : ExtraInfo := ExtraInfo + ' (数据库锁定冲突) ';
ERRCAT_SECURITY : ExtraInfo := ExtraInfo + ' (没有访问权限) ';
end;
end;
if ExtraInfo<>'' then Info := Info+#13#10+ExtraInfo;
end;
mmInfo.lines.Add(Info);
mmMsgs.lines.Add(msg);
ShowModal;
end;
procedure TErrorMsgDialog.FormCreate(Sender: TObject);
begin
FIsShowDetails := false;
ClientHeight := mmMsgs.Top - 2;
btnDetail.caption := '显示详细信息';
end;
class procedure TErrorMsgDialog.HandleAppError(Sender: TObject;
E: Exception);
begin
HandleThisException(e);
end;
procedure TErrorMsgDialog.SetisShowDetails(const Value: boolean);
begin
if FisShowDetails <> Value then
begin
FisShowDetails := Value;
if FisShowDetails then
begin
ClientHeight := mmMsgs.Top + mmMsgs.Height+2;
btnDetail.caption := '隐藏详细信息';
end
else
begin
ClientHeight := mmMsgs.Top - 2;
btnDetail.caption := '显示详细信息';
end;
end;
end;
end.
|
unit uExceptionHandle;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Dialogs;
procedure CallException(E: Exception);
implementation
// 显示异常
procedure CallException(E: Exception);
begin
if Assigned(Application) then
begin
if Assigned(Application.OnException) then
Application.OnException(Application, E)
else
MessageDlg(E.Message, mtError, [mbOK], 0);
end;
end;
end.
|
program OddEven(Input, Output);
uses wincrt;
type IntArray = array[1..25] of integer;
var I, OddInts, EvenInts : integer;
RandomInts, OddArray, EvenArray : IntArray;
{Gets random number between Min & Max}
procedure RandomNum(Min, Max : integer;
var RandomNumber : integer);
begin
RandomNumber := Random(Max - Min + 1) + Min;
end;
begin {main}
Randomize;
{Keeps track of how much odds or evens the array has}
OddInts := 0;
EvenInts := 0;
{Get 25 random numbers}
for I := 1 to 25 do
RandomNum(0, 99, RandomInts[I]);
{Find out if its even or odd, then puts it in the right array}
for I := 1 to 25 do
begin
if (RandomInts[I] mod 2 = 0) then
begin
{Even}
EvenInts := EvenInts + 1;
EvenArray[EvenInts] := RandomInts[I];
end
else
begin
{Odd}
OddInts := OddInts + 1;
OddArray[OddInts] := RandomInts[I];
end;
end;
{Display numbers in Odd Array}
write('Odd: ');
for I := 1 to OddInts do
begin
write(OddArray[I], ' ');
end;
{Display numbers in Even Array}
writeln;
write('Even: ');
for I := 1 to EvenInts do
begin
write(EvenArray[I], ' ');
end;
{End Program}
readln;
donewincrt;
end.
{Odd or Even}
{Kaleb Haslam} |
unit uPanelNotificaciones;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uPanel, BusCommunication, UtilDock, JvComponentBase, JvFormPlacement;
type
TPanelNotificacion = (pnValorCambiado, pnCotizacionCambiada, pnTipoCotizacionCambiada);
TPanelNotificaciones = set of TPanelNotificacion;
TfrPanelNotificaciones = class(TfrPanel)
private
notificaciones: TPanelNotificaciones;
protected
procedure OnCotizacionCambiada; virtual;
procedure OnValorCambiado; virtual;
procedure OnTipoCotizacionCambiada; virtual;
public
constructor CreatePanelNotificaciones(AOwner: TComponent;
const DefaultDock: TDefaultDock; const notificaciones: TPanelNotificaciones);
destructor Destroy; override;
end;
implementation
{$R *.dfm}
uses dmData;
{ TfrCotizacionCambiada }
constructor TfrPanelNotificaciones.CreatePanelNotificaciones(AOwner: TComponent;
const DefaultDock: TDefaultDock; const notificaciones: TPanelNotificaciones);
begin
inherited CreatePanel(AOwner, DefaultDock);
Self.notificaciones := notificaciones;
if pnValorCambiado in notificaciones then
Bus.RegisterEvent(MessageValorCambiado, OnValorCambiado);
if pnCotizacionCambiada in notificaciones then
Bus.RegisterEvent(MessageCotizacionCambiada, OnCotizacionCambiada);
if pnTipoCotizacionCambiada in notificaciones then
Bus.RegisterEvent(MessageTipoCotizacionCambiada, OnTipoCotizacionCambiada);
end;
destructor TfrPanelNotificaciones.Destroy;
begin
if pnValorCambiado in notificaciones then
Bus.UnregisterEvent(MessageValorCambiado, OnValorCambiado);
if pnCotizacionCambiada in notificaciones then
Bus.UnregisterEvent(MessageCotizacionCambiada, OnCotizacionCambiada);
if pnTipoCotizacionCambiada in notificaciones then
Bus.UnregisterEvent(MessageTipoCotizacionCambiada, OnTipoCotizacionCambiada);
inherited Destroy;
end;
procedure TfrPanelNotificaciones.OnCotizacionCambiada;
begin
end;
procedure TfrPanelNotificaciones.OnTipoCotizacionCambiada;
begin
end;
procedure TfrPanelNotificaciones.OnValorCambiado;
begin
end;
end.
|
//RP que ingrese 10 notas aprobadas y que muestre
//cual fue la nota mayor
//cual fue la menor
//y el promedio de todas las notas
program arreglo;
uses crt;
type
calificacion = array[0..9] of Real;
const
prom = 10;
var
cal: calificacion;
i:Integer=0;
promedio:real=0;
mayor:Real=0;
menor:Real=99999999999;
begin
clrscr;
writeln('ingrese 10 caificaciones');
while i < 10 do
begin
writeln('ingrse calificacion - ',i);
readln(cal[i]);
if (cal[i]>=70) and (cal[i]<=100) then
begin
promedio:= promedio + cal[i];
if cal[i]>mayor then
begin
mayor:= cal[i];
end;
if cal[i]<menor then
begin
menor:=cal[i];
end;
end
else
begin
writeln('Debe ingrsar una nota aprobada >=70 y <=100');
i:=i-1;
end;
i:=i+1;
end;
promedio:= promedio/prom;
writeln('EL promedio es - ', promedio:2:2);
writeln('La nota mayor es - ', mayor:2:2);
writeln('La nota menor es - ', menor:2:2);
end. |
{Hint: save all files to location: C:\android-neon\eclipse\workspace\AppBroadcastReceiverDemo2\jni }
unit unit1;
{$mode delphi}
interface
uses
Classes, SysUtils, AndroidWidget, Laz_And_Controls, broadcastreceiver,
And_jni, intentmanager;
type
{ TAndroidModule1 }
TAndroidModule1 = class(jForm)
jBroadcastReceiver1: jBroadcastReceiver;
jButton1: jButton;
jButton2: jButton;
jIntentManager1: jIntentManager;
jTextView1: jTextView;
procedure AndroidModule1JNIPrompt(Sender: TObject);
procedure AndroidModule1RequestPermissionResult(Sender: TObject;
requestCode: integer; manifestPermission: string;
grantResult: TManifestPermissionResult);
procedure jBroadcastReceiver1Receiver(Sender: TObject; intent: jObject);
procedure jButton1Click(Sender: TObject);
procedure jButton2Click(Sender: TObject);
private
{private declarations}
public
{public declarations}
end;
var
AndroidModule1: TAndroidModule1;
implementation
{$R *.lfm}
{ TAndroidModule1 }
//http://www.feelzdroid.com/2015/04/detect-incoming-call-android-programmatically.html
//http://www.theappguruz.com/blog/detecting-incoming-phone-calls-in-android
procedure TAndroidModule1.jButton1Click(Sender: TObject);
begin
if IsRuntimePermissionGranted('android.permission.READ_PHONE_STATE') then //from AndroodManifest.xml
begin
jBroadcastReceiver1.RegisterIntentActionFilter('android.intent.action.PHONE_STATE');
//or jBroadcastReceiver1.IntentActionFilter:= afPhoneState;
ShowMessage('Registering action PHONE_STATE ... Please, wait for a incomming call ... ');
end;
end;
procedure TAndroidModule1.jBroadcastReceiver1Receiver(Sender: TObject; intent: jObject);
var
action, phoneState, phoneNumber: string;
begin
action:= jIntentManager1.GetAction(intent);
ShowMessage(action);
if action = 'android.intent.action.PHONE_STATE' then
begin
//reference: https://developer.android.com/reference/android/telephony/TelephonyManager.html
phoneState:= jIntentManager1.GetExtraString(intent, 'state');
ShowMessage(phoneState);
if phoneState = 'IDLE' then
begin
ShowMessage('Waiting ...[IDLE]');
end;
if phoneState = 'RINGING' then
begin
phoneNumber:= jIntentManager1.GetExtraString(intent, 'incoming_number');
ShowMessage('"Incomming call from [RINGING]: '+phoneNumber);
end;
if phoneState = 'OFFHOOK' then
begin
ShowMessage('Call end/received... [OFFHOOK]');
end;
end;
end;
procedure TAndroidModule1.AndroidModule1JNIPrompt(Sender: TObject);
begin
if IsRuntimePermissionNeed() then // that is, if target API >= 23
begin
ShowMessage('RequestRuntimePermission....');
////https://developer.android.com/guide/topics/security/permissions#normal-dangerous
//from AndroodManifest.xml
Self.RequestRuntimePermission('android.permission.READ_PHONE_STATE', 1213); //handled by OnRequestPermissionResult
end
end;
procedure TAndroidModule1.AndroidModule1RequestPermissionResult(
Sender: TObject; requestCode: integer; manifestPermission: string;
grantResult: TManifestPermissionResult);
begin
case requestCode of
1213:begin
if grantResult = PERMISSION_GRANTED then
begin
//ShowMessage('Success! ['+manifestPermission+'] Permission granted!!! ' );
if manifestPermission = 'android.permission.READ_PHONE_STATE' then
begin
jButton1.Enabled:= True;
jButton2.Enabled:= True;
end;
end
else//PERMISSION_DENIED
begin
jButton1.Enabled:= False;
jButton2.Enabled:= False;
ShowMessage('Sorry... ['+manifestPermission+'] permission not granted... ' );
end;
end;
end;
end;
procedure TAndroidModule1.jButton2Click(Sender: TObject);
begin
if jBroadcastReceiver1.Registered then
begin
jBroadcastReceiver1.Unregister();
ShowMessage('BroadcastReceiver UnRegistering ... [PHONE_STATE]');
end
else
begin
ShowMessage('Nothing Registered yet ... ');
end;
end;
end.
|
unit CurrencyListMovement;
interface
uses
AncestorEditDialog, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters,
Vcl.Menus, cxControls, cxContainer, cxEdit, Vcl.ComCtrls, dxCore, cxDateUtils,
dsdGuides, cxDropDownEdit, cxCalendar, cxMaskEdit, cxButtonEdit, cxTextEdit,
cxCurrencyEdit, Vcl.Controls, cxLabel, dsdDB, dsdAction, System.Classes,
Vcl.ActnList, cxPropertiesStore, dsdAddOn, Vcl.StdCtrls, cxButtons,
dxSkinsCore, dxSkinsDefaultPainters, dxSkinBlack, dxSkinBlue, dxSkinBlueprint,
dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinPumpkin, dxSkinSeven,
dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver,
dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld,
dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue;
type
TCurrencyListMovementForm = class(TAncestorEditDialogForm)
cxLabel1: TcxLabel;
Код: TcxLabel;
ceOperDate: TcxDateEdit;
ceAmount: TcxCurrencyEdit;
cxLabel7: TcxLabel;
ceCurrencyTo: TcxButtonEdit;
CurrencyToGuides: TdsdGuides;
cxLabel6: TcxLabel;
GuidesFiller: TGuidesFiller;
ceCurrencyFrom: TcxButtonEdit;
cxLabel8: TcxLabel;
cxLabel10: TcxLabel;
ceComment: TcxTextEdit;
CurrencyFromGuides: TdsdGuides;
edInvNumber: TcxTextEdit;
ceParValue: TcxCurrencyEdit;
cxLabel2: TcxLabel;
edPaidKind: TcxButtonEdit;
cxLabel3: TcxLabel;
PaidKindGuides: TdsdGuides;
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TCurrencyListMovementForm);
end.
|
unit TestCopperTrace;
interface
procedure TestLinesIntersect;
procedure TestSegmentToRect;
implementation
uses Types, SysUtils, CopperTrace, Board;
procedure Error( comment : string );
begin
raise Exception.Create( 'Error ' + comment );
end;
procedure TestLinesIntersect;
begin
// Vertical and Horizontal lines
if not LinesCross( Point(5, 5), Point(10,5), Point(7,0), Point(7,15) ) then begin
Error( 'LinesIntersect: Lines cross not detected' );
end;
if LinesCross( Point(5, 5), Point(10,5), Point(7,0), Point(7,4) ) then begin
Error( 'LinesIntersect: Wrongly detected lines cross' );
end;
// Criss-cross lines
if not LinesCross( Point(5, 5), Point(10,15), Point(5,15), Point(15,4) ) then begin
Error( 'LinesIntersect: Lines cross not detected' );
end;
if LinesCross( Point(5, 50), Point(10,15), Point(5,15), Point(15,4) ) then begin
Error( 'LinesIntersect: Wrongly detected lines cross' );
end;
end;
procedure TestSegmentToRect;
var
Segment : TbrSegment;
Rect : TRect;
begin
Segment := TbrSegment.Create;
try
// rect intersects with segment, but not at segment end point
// segment horizontal
Segment.X1_1000 := 1000;
Segment.Y1_1000 := 1000;
Segment.X2_1000 := 2000;
Segment.Y2_1000 := 1000;
Segment.Width_1000 := 100;
Rect.Left := 1500;
Rect.Top := 990;
Rect.Right := 1510;
Rect.Bottom := 1100;
{
if not SegmentToRect( Segment, Rect ) then begin
Error( 'SegmentToRect: Intersect not detected' );
end;
}
// rect intersects with segment, but not at segment end point
// segment vertical, no intersection
Segment.X1_1000 := 1000;
Segment.Y1_1000 := 1000;
Segment.X2_1000 := 1000;
Segment.Y2_1000 := 2000;
Segment.Width_1000 := 100;
Rect.Left := 1500;
Rect.Top := 990;
Rect.Right := 1510;
Rect.Bottom := 1100;
{
if SegmentToRect( Segment, Rect ) then begin
Error( 'SegmentToRect: Intersect wrongly detected' );
end;
}
// rect intersects with segment, with segment at 45 degrees angle
// and rectangle near center.
Segment.X1_1000 := 1000;
Segment.Y1_1000 := 1000;
Segment.X2_1000 := 10000;
Segment.Y2_1000 := 10000;
Segment.Width_1000 := 1000;
Rect.Left := 5500;
Rect.Top := 5500;
Rect.Right := 5800;
Rect.Bottom := 5800;
if not SegmentToRect( Segment, Rect ) then begin
Error( 'SegmentToRect: Intersect not detected' );
end;
// segment end just touches top of rectangle - tests end circle intersect
Segment.X1_1000 := 7000;
Segment.Y1_1000 := 1000;
Segment.X2_1000 := 7000;
Segment.Y2_1000 := 6000;
Segment.Width_1000 := 100;
Rect.Left := 6800;
Rect.Top := 6049;
Rect.Right := 7200;
Rect.Bottom := 7300;
if not SegmentToRect( Segment, Rect ) then begin
Error( 'SegmentToRect: Intersect not detected' );
end;
// same as previous, but Segment Ends swapped
Segment.X1_1000 := 7000;
Segment.Y1_1000 := 6000;
Segment.X2_1000 := 7000;
Segment.Y2_1000 := 1000;
Segment.Width_1000 := 100;
if not SegmentToRect( Segment, Rect ) then begin
Error( 'SegmentToRect: Intersect not detected' );
end;
finally
Segment.Free;
end;
end;
end.
|
unit Menus.Controller.ListaBox.Itens.Default;
interface
uses Menus.Controller.ListBox.Interfaces, FMX.ListBox, System.Classes, FMX.Types;
type
TControllerListaBoxItensDefault = class(TInterfacedObject, iControllerListBoxItensDefault)
private
FListBoxItem : TListBoxItem;
public
constructor Create;
destructor Destroy; override;
class Function New : iControllerListBoxItensDefault;
function Name(Value : String): iControllerListBoxItensDefault;
function Text(Value : String): iControllerListBoxItensDefault;
function StyleLookup(Value : String): iControllerListBoxItensDefault;
function onClick(Value : TNotifyEvent) : iControllerListBoxItensDefault;
Function Item : TFMXObject;
end;
implementation
{ TControllerListaBoxItensDefault }
constructor TControllerListaBoxItensDefault.Create;
begin
FListBoxItem := TListBoxItem.Create(nil);
FListBoxItem.Name := 'btnDefault';
FListBoxItem.Text := 'Default';
FListBoxItem.StyleLookup := 'listboxitemdetaillabel';
end;
destructor TControllerListaBoxItensDefault.Destroy;
begin
inherited;
end;
function TControllerListaBoxItensDefault.Item: TFMXObject;
begin
Result := FListBoxItem;
end;
function TControllerListaBoxItensDefault.Name(
Value: String): iControllerListBoxItensDefault;
begin
Result := Self;
FListBoxItem.Name := Value;
end;
class function TControllerListaBoxItensDefault.New: iControllerListBoxItensDefault;
begin
Result := Self.Create;
end;
function TControllerListaBoxItensDefault.onClick(
Value: TNotifyEvent): iControllerListBoxItensDefault;
begin
Result := Self;
FListBoxItem.OnClick := Value;
end;
function TControllerListaBoxItensDefault.StyleLookup(
Value: String): iControllerListBoxItensDefault;
begin
Result := Self;
FListBoxItem.StyleLookup := Value;
end;
function TControllerListaBoxItensDefault.Text(
Value: String): iControllerListBoxItensDefault;
begin
Result := Self;
FListBoxItem.Text := Value;
end;
end.
|
(******************************************************************************)
(** Suite : AtWS **)
(** Object : TAtXMLDocument **)
(** Framework : **)
(** Developed by : Nuno Picado **)
(******************************************************************************)
(** Interfaces : **)
(******************************************************************************)
(** Dependencies : **)
(******************************************************************************)
(** Description : Customized version of TXMLDocument, capable of setting **)
(** up by itself the fields Nonce, Password and Created **)
(******************************************************************************)
(** Licence : MIT (https://opensource.org/licenses/MIT) **)
(** Contributions : You can create pull request for all your desired **)
(** contributions as long as they comply with the guidelines **)
(** you can find in the readme.md file in the main directory **)
(** of the Reusable Objects repository **)
(** Disclaimer : The licence agreement applies to the code in this unit **)
(** and not to any of its dependencies, which have their own **)
(** licence agreement and to which you must comply in their **)
(** terms **)
(******************************************************************************)
unit AtXMLDocument;
interface
uses
XMLDoc
, xmlintf
;
type
TAtXMLDocument = class(TXMLDocument)
public
class function New(const XMLData, PubKey: string): IXMLDocument;
end;
implementation
uses
RO.TAES128
, RO.TZDate
, RO.ISNTPTime
, RO.TSNTPTime
, RO.TIf
, RO.TValue
, RO.TRSASignature
, RO.TRandomKey
, SysUtils
;
{ TAtXMLDocument }
class function TAtXMLDocument.New(const XMLData, PubKey: string): IXMLDocument;
const
RandomKeyBitNumber = 16;
var
CurNode : IXMLNode;
SecretKey : string;
begin
Result := NewXMLDocument;
Result.Encoding := 'utf-8';
Result.StandAlone := 'no';
Result.Options := [doNodeAutoIndent];
Result.LoadFromXML(XMLData);
SecretKey := TRandomKey.New(RandomKeyBitNumber).AsString;
with Result.DocumentElement.ChildNodes[0].ChildNodes[0].ChildNodes[0].ChildNodes do
begin
// Nonce
CurNode := FindNode('Nonce');
if Assigned(CurNode) then
CurNode.Text := TRSASignature.New(
SecretKey,
PubKey
).AsString;
// Password
CurNode := FindNode('Password');
if Assigned(CurNode) then
CurNode.Text := TAES128.New(
TString.New(
CurNode.Text
),
SecretKey
).Value;
// Created
CurNode := FindNode('Created');
if Assigned(CurNode) then
CurNode.Text := TAES128.New(
TString.New(
TZDate.New(
'Portugal',
TSNTPTimePool.New(
[
'ntp04.oal.ul.pt',
'ntp02.oal.ul.pt'
],
TSPBehavior.spReturnCurrentDate
)
).AsString
),
SecretKey
).Value
end;
end;
end.
|
{
Purpose:
Run an adhoc query as a script - good for multiple queries, separated by ;s
Bit of a hack though to get multiple queries running.
Classes:
TFormRunAsScript - The form
ToDo:
Remove the need to shell out to a script engine. Better to run the quesies
from within the SQLManager process.
}
unit FRunAsScript;
{$I tiDefines.inc}
interface
uses
Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, tiButtons, tiPerAwareCtrls, tiFocusPanel,
tiMemoReadOnly, tiPerAwareCombosAbs, tiPerAwareFileCombos
{$IFDEF FPC}
,LResources
{$ENDIF}
;
type
TFormRunAsScript = class(TForm)
tiButtonPanel1: TtiButtonPanel;
hcParams: TtiPerAwareComboBoxHistory;
memoMacros: TtiMemoReadOnly;
paeApplicationToRun: TtiPerAwarePickFile;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure tiButtonPanel1Btn1Click(Sender: TObject);
procedure tiButtonPanel1Btn2Click(Sender: TObject);
private
function GetAppToRun: string;
function GetParams: string;
{ Private declarations }
public
property AppToRun : string read GetAppToRun ;
property Params : string read GetParams ;
end;
implementation
uses
tiUtils
,tiINI
,tiGUIINI
;
//{$IFDEF FPC}
{$R *.dfm}
//{$ENDIF}
procedure TFormRunAsScript.FormCreate(Sender: TObject);
begin
gGUIINI.ReadFormState( self ) ;
paeApplicationToRun.Value := gINI.ReadString( name, 'AppToRun', '' ) ;
hcParams.Value := gINI.ReadString( name, 'Params', '' ) ;
end;
procedure TFormRunAsScript.FormDestroy(Sender: TObject);
begin
gGUIINI.WriteFormState( self ) ;
gINI.WriteString( name, 'AppToRun', paeApplicationToRun.Value ) ;
gINI.WriteString( name, 'Params', hcParams.Value ) ;
end;
function TFormRunAsScript.GetAppToRun: string;
begin
result := paeApplicationToRun.Value ;
end;
function TFormRunAsScript.GetParams: string;
begin
result := hcParams.Value ;
end;
procedure TFormRunAsScript.tiButtonPanel1Btn1Click(Sender: TObject);
begin
ModalResult := mrOK ;
end;
procedure TFormRunAsScript.tiButtonPanel1Btn2Click(Sender: TObject);
begin
ModalResult := mrCancel ;
end;
initialization
{$i FRunAsScript.lrs}
end.
|
unit View.TitleEdit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, View.TemplateEdit, Data.DB,
JvComponentBase, JvFormPlacement, Vcl.StdCtrls, Vcl.ExtCtrls,
Model.LanguageDictionary,
Model.ProSu.Interfaces,
Model.ProSu.Provider,
Model.Declarations,
Spring.Data.ObjectDataset,
Model.FormDeclarations, Vcl.DBCtrls, JvExControls, JvDBLookupTreeView,
Vcl.Mask;
type
TTitleEditForm = class(TTemplateEdit)
dsCompany: TDataSource;
labelTitleName: TLabel;
labelTitleNameEng: TLabel;
labelParentTitleId: TLabel;
labelCompanyId: TLabel;
edTitleName: TDBEdit;
edTitleNameEng: TDBEdit;
edParentTitleId: TJvDBLookupTreeViewCombo;
edCompanyId: TDBLookupComboBox;
dsTitleTree: TDataSource;
edIsHeadShip: TDBCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
fCompanyDataset : TObjectDataset;
fTitleTreeDataset : TObjectDataset;
procedure RefreshTitleDataset;
procedure FormLoaded; override;
class function RequiredPermission(cmd: TBrowseFormCommand) : string; override;
public
{ Public declarations }
end;
var
TitleEditForm: TTitleEditForm;
implementation
uses
Spring.Collections,
MainDM;
{$R *.dfm}
procedure TTitleEditForm.FormDestroy(Sender: TObject);
begin
inherited;
fCompanyDataset.Free;
fTitleTreeDataset.Free;
end;
procedure TTitleEditForm.FormLoaded;
begin
fCompanyDataset := TObjectDataset.Create(self);
fCompanyDataset.DataList := DMMain.Session.FindAll<TCompany> as IObjectList;
fCompanyDataset.Open;
dsCompany.DataSet := fCompanyDataset;
fTitleTreeDataset := TObjectDataset.Create(self);
dsTitleTree.DataSet := fTitleTreeDataset;
RefreshTitleDataset;
if fTitleTreeDataset.RecordCount>0 then
edParentTitleId.FullExpand := True;
end;
procedure TTitleEditForm.RefreshTitleDataset;
begin
//if DataSource1.DataSet.FieldByName('CompanyId').IsNull then
// Exit;
fTitleTreeDataset.Close;
fTitleTreeDataset.DataList := dmmain.Session.GetList<TTitle>('select * from Title where CompanyId=:0;',
[DataSource1.DataSet.FieldByName('CompanyId').AsInteger]) as IObjectList;
fTitleTreeDataset.Open;
end;
class function TTitleEditForm.RequiredPermission(cmd: TBrowseFormCommand): string;
begin
Result := '>????<';
case cmd of
efcmdAdd: Result := '3522';
efcmdEdit: Result := '3523';
efcmdDelete: Result := '3524';
efcmdViewDetail: Result := '3525';
end;
end;
procedure TTitleEditForm.FormCreate(Sender: TObject);
begin
inherited;
Caption := ComponentDictionary.GetText(Self.ClassName, 'Caption');
labelTitleName.Caption := ComponentDictionary.GetText(ClassName, 'labelTitleName.Caption');
labelTitleNameEng.Caption := ComponentDictionary.GetText(ClassName, 'labelTitleNameEng.Caption');
labelParentTitleId.Caption := ComponentDictionary.GetText(ClassName, 'labelParentTitleId.Caption');
labelCompanyId.Caption := ComponentDictionary.GetText(ClassName, 'labelCompanyId.Caption');
edIsHeadShip.Caption := ComponentDictionary.GetText(ClassName, 'edIsHeadShip.Caption');
end;
end.
|
unit udmFinanc;
interface
uses
SysUtils, Classes, DB, IBX.IBDatabase, uLib, IBX.IBCustomDataSet,
IBX.IBUpdateSQL, IBX.IBQuery, DBClient, uConst, DateUTils, Datasnap.Provider;
type
TdmFinanc = class(TDataModule)
tdb: TIBTransaction;
db: TIBDatabase;
Conta: TIBQuery;
uConta: TIBUpdateSQL;
dConta: TDataSource;
ContaID_CONTA: TIntegerField;
ContaCD_USUARIO: TIBStringField;
ContaNR_CONTA: TIntegerField;
ContaDS_CONTA: TIBStringField;
Movimento: TIBQuery;
uMovimento: TIBUpdateSQL;
dMovimento: TDataSource;
MovimentoID_MOVIM: TIntegerField;
MovimentoID_CONTA: TIntegerField;
MovimentoVL_MOVIM: TIBBCDField;
MovimentoDS_MOVIM: TIBStringField;
MovimentoNR_CONTA: TIntegerField;
MovimentoDS_CONTA: TIBStringField;
MovimentoFL_TIPO: TIBStringField;
Categoria: TIBQuery;
UCategoria: TIBUpdateSQL;
DCategoria: TDataSource;
CategoriaID_CATEG: TIntegerField;
CategoriaCD_USUARIO: TIBStringField;
CategoriaID_CATPAI: TIntegerField;
CategoriaDS_CATEG: TIBStringField;
CategoriaFL_TIPO: TIBStringField;
PesCategoria: TIBQuery;
dPesCategoria: TDataSource;
PesCategoriaID_CATEG: TIntegerField;
PesCategoriaCD_USUARIO: TIBStringField;
PesCategoriaID_CATPAI: TIntegerField;
PesCategoriaDS_CATEG: TIBStringField;
PesCategoriaFL_TIPO: TIBStringField;
MovimentoID_CATEG: TIntegerField;
MovimentoDS_CATEG: TIBStringField;
ContaVL_SALDO: TIBBCDField;
MovimentoDT_MOVIM: TDateField;
MovimentoCD_USUARIO: TIBStringField;
Transferencia: TIBQuery;
uTransferencia: TIBUpdateSQL;
dTransferencia: TDataSource;
TransferenciaID_TRANSFER: TIntegerField;
TransferenciaID_MOVDEB: TIntegerField;
TransferenciaID_MOVCRE: TIntegerField;
TransferenciaDS_TRANSF: TIBStringField;
TransferenciaDT_TRANSF: TDateField;
TransferenciaVL_TRANSF: TIBBCDField;
TransferenciaDS_CDEB: TIBStringField;
TransferenciaNR_CDEB: TIntegerField;
TransferenciaDS_CCRED: TIBStringField;
TransferenciaNR_CCRED: TIntegerField;
TransferenciaID_CDEB: TIntegerField;
TransferenciaID_CCRED: TIntegerField;
TransferenciaCD_USUARIO: TIBStringField;
cdsAnalise: TClientDataSet;
cdsAnaliseID_CATEG: TIntegerField;
cdsAnaliseCATEG: TStringField;
cdsAnaliseVALOR: TFloatField;
cdsAnaliseNIVEL: TIntegerField;
cdsAnaliseFL_TIPO: TStringField;
cdsAnaliseB_PAI: TBooleanField;
PagarReceber: TIBQuery;
uPagarReceber: TIBUpdateSQL;
dPagarReceber: TDataSource;
PagarReceberID_PAGRECEB: TIntegerField;
PagarReceberCD_USUARIO: TIBStringField;
PagarReceberID_CATEG: TIntegerField;
PagarReceberVL_VALOR: TIBBCDField;
PagarReceberDT_VENCTO: TDateField;
PagarReceberFL_TIPO: TIBStringField;
PagarReceberDS_CATEG: TIBStringField;
PagarReceberDS_DESCRI: TIBStringField;
PagarReceberVL_PAGO: TIBBCDField;
MovimentoID_PAGRECEB: TIntegerField;
PagarReceberNR_DOCTO: TIBStringField;
cdsAnual: TClientDataSet;
cdsAnualID_CATEG: TIntegerField;
cdsAnualCATEG: TStringField;
cdsAnualNIVEL: TIntegerField;
cdsAnualFL_TIPO: TStringField;
cdsAnualB_PAI: TBooleanField;
cdsAnualVL_M1: TFloatField;
cdsAnualVL_M2: TFloatField;
cdsAnualVL_M3: TFloatField;
cdsAnualVL_M4: TFloatField;
cdsAnualVL_M5: TFloatField;
cdsAnualVL_M6: TFloatField;
cdsAnualVL_M7: TFloatField;
cdsAnualVL_M8: TFloatField;
cdsAnualVL_M9: TFloatField;
cdsAnualVL_M10: TFloatField;
cdsAnualVL_M11: TFloatField;
cdsAnualVL_M12: TFloatField;
CCusto: TIBQuery;
uCCusto: TIBUpdateSQL;
dCCusto: TDataSource;
PesCCusto: TIBQuery;
dPesCCusto: TDataSource;
CCustoID_CCUSTO: TIntegerField;
CCustoCD_USUARIO: TIBStringField;
CCustoID_CCPAI: TIntegerField;
CCustoDS_CCUSTO: TIBStringField;
PesCCustoID_CCUSTO: TIntegerField;
PesCCustoCD_USUARIO: TIBStringField;
PesCCustoID_CCPAI: TIntegerField;
PesCCustoDS_CCUSTO: TIBStringField;
MovimentoID_CCUSTO: TIntegerField;
MovimentoDS_CCUSTO: TIBStringField;
Plano: TIBQuery;
uPlano: TIBUpdateSQL;
dPlano: TDataSource;
PlanoID_PLANO: TIntegerField;
PlanoCD_USUARIO: TIBStringField;
PlanoID_CATEG: TIntegerField;
PlanoID_CCUSTO: TIntegerField;
PlanoVL_VALOR: TIBBCDField;
PlanoFL_ALERTA: TIBStringField;
PlanoDS_PLANO: TIBStringField;
PlanoDS_CATEG: TIBStringField;
PlanoDS_CCUSTO: TIBStringField;
PlanoDS_ACAO: TIBStringField;
MovimentoVL_JUROS: TIBBCDField;
MovimentoVL_DESCON: TIBBCDField;
MovimentoVL_BRUTO: TIBBCDField;
ContaFL_ATIVO: TIBStringField;
CategoriaFL_ATIVO: TIBStringField;
PesCategoriaFL_ATIVO: TIBStringField;
CCustoFL_ATIVO: TIBStringField;
PesCCustoFL_ATIVO: TIBStringField;
Bens: TIBQuery;
uBens: TIBUpdateSQL;
dBens: TDataSource;
BensID_BEM: TIntegerField;
BensCD_USUARIO: TIBStringField;
BensDS_BEM: TIBStringField;
BensVL_AQUISICAO: TIBBCDField;
BensDT_AQUISICAO: TDateField;
BensVL_ATUAL: TIBBCDField;
BensDT_VENDA: TDateField;
procedure DataModuleCreate(Sender: TObject);
procedure ContaAfterInsert(DataSet: TDataSet);
procedure MovimentoAfterInsert(DataSet: TDataSet);
procedure CategoriaAfterInsert(DataSet: TDataSet);
function i_funcNextSequence(s_seq : string) : integer;
procedure TransferenciaAfterInsert(DataSet: TDataSet);
procedure TransferenciaVL_TRANSFValidate(Sender: TField);
procedure MovimentoBeforePost(DataSet: TDataSet);
procedure PagarReceberAfterInsert(DataSet: TDataSet);
procedure PagarReceberVL_VALORValidate(Sender: TField);
procedure PagarReceberVL_BRUTOValidate(Sender: TField);
procedure CCustoAfterInsert(DataSet: TDataSet);
procedure PlanoAfterInsert(DataSet: TDataSet);
procedure MovimentoAfterEdit(DataSet: TDataSet);
procedure MovimentoVL_JUROSValidate(Sender: TField);
procedure MovimentoVL_DESCONValidate(Sender: TField);
procedure MovimentoVL_BRUTOValidate(Sender: TField);
procedure ContaFL_ATIVOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure CategoriaFL_ATIVOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure PesCategoriaFL_ATIVOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure CCustoFL_ATIVOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure PesCCustoFL_ATIVOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure MovimentoFL_TIPOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure CategoriaFL_TIPOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure PagarReceberFL_TIPOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
procedure BensAfterInsert(DataSet: TDataSet);
procedure BensVL_ATUALValidate(Sender: TField);
procedure BensVL_AQUISICAOValidate(Sender: TField);
procedure BensDT_VENDAValidate(Sender: TField);
procedure BensDT_AQUISICAOValidate(Sender: TField);
private
{ Private declarations }
procedure procInsereMascara;
procedure procCalculaMovimentoVL_MOVIM;
public
{ Public declarations }
function funcListaCategoria(i_categ : integer = 0) : string;
function funcListaCCusto(i_ccusto : integer = 0) : string;
function b_funcTemCCustoHierarquia(i_ccusto, i_ccpai : integer) : boolean;
function b_funcTemCategHierarquia(i_categ, i_catpai : integer) : boolean;
procedure procCriaAtualizaMovimento(i_movto,i_conta : integer; f_valor : double; s_descri, s_tipo : string; i_categ : integer; d_data : TDate; i_ccusto : integer);
function i_funcCategPadrao(s_tipo : string) : integer;
procedure procValidaFieldNumericoPositivo(campo : TField);
procedure procValidaFieldNumericoMaiorQueZero(campo: TField);
procedure procValidaFieldNumericoPercentual(campo: TField);
function funcValidaMovimentoDentroDoPlano(i_mov, i_ccusto, i_categ : integer; f_valor : double; d_data : TDateTime):boolean;
procedure procGetTextAtivoInativo(Sender: TField; var Text: string; DisplayText: Boolean);
procedure procGetText(Sender: TField; var Text: string; DisplayText: Boolean; c_argumentos : string);
end;
var
dmFinanc: TdmFinanc;
id_CCPad : integer;
id_ConPad : integer;
implementation
{$R *.dfm}
procedure TdmFinanc.CategoriaAfterInsert(DataSet: TDataSet);
begin
CategoriaID_CATEG.AsInteger := i_funcNextSequence('GEN_CATEGORIA');
CategoriaCD_USUARIO.AsString := CD_USUARIO_LOGADO;
CategoriaFL_ATIVO.AsString := 'A';
end;
procedure TdmFinanc.CategoriaFL_ATIVOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
procGetTextAtivoInativo(Sender, Text, DisplayText);
end;
procedure TdmFinanc.CategoriaFL_TIPOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
procGetText(Sender, Text, DisplayText,
'R=Receita'+sLineBreak+
'D=Despesa'
);
end;
procedure TdmFinanc.CCustoAfterInsert(DataSet: TDataSet);
begin
CCustoID_CCUSTO.AsInteger := i_funcNextSequence('GEN_CCUSTO');
CCustoCD_USUARIO.AsString := CD_USUARIO_LOGADO;
CCustoFL_ATIVO.AsString := 'A';
end;
procedure TdmFinanc.CCustoFL_ATIVOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
procGetTextAtivoInativo(Sender, Text, DisplayText);
end;
procedure TdmFinanc.ContaAfterInsert(DataSet: TDataSet);
begin
ContaID_CONTA.AsInteger := i_funcNextSequence('GEN_CONTA');
ContaCD_USUARIO.AsString := CD_USUARIO_LOGADO;
ContaFL_ATIVO.AsString := 'A';
end;
procedure TdmFinanc.ContaFL_ATIVOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
procGetTextAtivoInativo(Sender, Text, DisplayText);
end;
procedure TdmFinanc.DataModuleCreate(Sender: TObject);
begin
Ulib.transacao := tdb;
Ulib.s_projeto := 'Financ';
DB.Connected := false;
try
DB.DatabaseName := caminhoBancoDados;
DB.Connected := true;
except
procMsgErro('Erro ao conectar ao banco de dados. Verifique a conexão pelo arquivo ''financ.inf''.',True);
end;
try
procInsereMascara;
except
on e : Exception do
procMsgErro('Erro ao inicializar o sistema.'+sLineBreak+'Descrição do erro:'+sLineBreak+e.Message,True);
end;
end;
function TdmFinanc.funcListaCategoria(i_categ: integer): string;
begin
Result := funcSelect(Format(
'WITH RECURSIVE CAT_TREE AS( '+
' SELECT A.ID_CATEG '+
' FROM CATEGORIA A '+
' WHERE A.ID_CATEG = %d '+
' UNION ALL '+
' '+
' SELECT A.ID_CATEG '+
' FROM CATEGORIA A '+
' INNER JOIN CAT_TREE B ON '+
' B.ID_CATEG = A.ID_CATPAI)'+
' '+
' SELECT LIST(A.ID_CATEG) LISTA '+
' FROM CAT_TREE A ',
[i_categ]));
end;
function TdmFinanc.i_funcCategPadrao(s_tipo: string): integer;
begin
Result := strToIntDef(
funcSelect(Format(
'SELECT A.ID_CATEG '+
' FROM CATEGORIA A '+
' WHERE A.CD_USUARIO = ''%s'''+
' AND A.FL_TIPO = ''%s'''+
' AND A.ID_CATPAI IS NULL ',
[CD_USUARIO_LOGADO,s_tipo])),0
);
end;
function TdmFinanc.funcListaCCusto(i_ccusto: integer): string;
begin
Result := funcSelect(Format(
'WITH RECURSIVE CC_TREE AS( '+
' SELECT A.ID_CCUSTO '+
' FROM CCUSTO A '+
' WHERE A.ID_CCUSTO = %d '+
' UNION ALL '+
' '+
' SELECT A.ID_CCUSTO '+
' FROM CCUSTO A '+
' INNER JOIN CC_TREE B ON '+
' B.ID_CCUSTO = A.ID_CCPAI)'+
' '+
' SELECT LIST(A.ID_CCUSTO) LISTA '+
' FROM CC_TREE A ',
[i_ccusto]));
end;
function TdmFinanc.funcValidaMovimentoDentroDoPlano(i_mov,i_ccusto,i_categ: integer; f_valor : double; d_data : TDateTime): boolean;
function funcValidaCCusto : boolean;
var q1,q2,q3 : TIBQuery;
begin
Result := False;
procCriarQuery(q1);
procCriarQuery(q2);
procCriarQuery(q3);
try
q1.SQL.Text :=
'WITH RECURSIVE CC_TREE AS( '+
' SELECT A.ID_CCPAI, '+
' A.ID_CCUSTO '+
' FROM CCUSTO A '+
' WHERE A.ID_CCUSTO = '+IntToStr(i_ccusto)+
' UNION ALL '+
' '+
' SELECT A.ID_CCPAI, '+
' A.ID_CCUSTO '+
' FROM CCUSTO A '+
' INNER JOIN CC_TREE B ON '+
' B.ID_CCPAI = A.ID_CCUSTO)'+
' '+
' SELECT A.ID_CCUSTO '+
' FROM CC_TREE A ';
q1.Open;
while not q1.Eof do
begin
q2.sql.Text :=
'SELECT A.VL_VALOR, '+
' A.FL_ALERTA, '+
' A.DS_PLANO, '+
' B.DS_CCUSTO '+
' FROM PLANO A '+
' INNER JOIN CCUSTO B ON B.ID_CCUSTO = A.ID_CCUSTO'+
' WHERE A.ID_CCUSTO = :CCUSTO ';
q2.ParamByName('CCUSTO').AsInteger := q1.FieldByName('ID_CCUSTO').AsInteger;
q2.Open;
if not q2.IsEmpty then
begin
q3.sql.Text :=
'SELECT COALESCE(SUM(A.VL_MOVIM),0) * -1 VL_VALOR '+
' FROM MOVIMENTO A '+
' WHERE A.ID_CCUSTO IN ('+
funcListaCCusto(q1.FieldByName('ID_CCUSTO').AsInteger)+')'+
' AND A.DT_MOVIM BETWEEN :DATAINI AND :DATAFIN '+
' AND A.FL_TIPO = ''R'' '+
' AND A.ID_MOVIM <> :ESTEMOV '+
' AND NOT EXISTS(SELECT 1 FROM TRANSFERENCIA C '+
' WHERE (C.ID_MOVDEB = A.ID_MOVIM '+
' OR C.ID_MOVCRE = A.ID_MOVIM))';
q3.ParamByName('DATAINI').AsDateTime := DateUtils.StartOfTheMonth(d_data);
q3.ParamByName('DATAFIN').AsDateTime := DateUtils.EndOfTheMonth(d_data);
q3.ParamByName('ESTEMOV').AsInteger := i_mov;
q3.Open;
if (q3.FieldByName('VL_VALOR').AsFloat + f_valor) > q2.FieldByName('VL_VALOR').AsFloat then
begin
if q2.FieldByName('FL_ALERTA').AsString = 'B' then
raise Exception.Create(Format(
'Não será possivel continuar pois o Centro de Custos %s está configurado no '+
'Plano %s para movimentar apenas R$ %s mensalmente, e com esta movimentação ficaria com o valor de R$ %s.',
[q2.FieldByName('DS_CCUSTO').AsString,
q2.FieldByName('DS_PLANO').AsString,
FormatFloat('###,###,##0.00',q2.FieldByName('VL_VALOR').AsFloat),
FormatFloat('###,###,##0.00',q3.FieldByName('VL_VALOR').AsFloat + f_valor)
]))
else
if not funcMsgConfirma(Format(
'O Centro de Custos %s está configurado no Plano %s para movimentar apenas R$ %s mensalmente, '+
'e com esta movimentação ficará com o valor de R$ %s. Deseja continuar?',
[q2.FieldByName('DS_CCUSTO').AsString,
q2.FieldByName('DS_PLANO').AsString,
FormatFloat('###,###,##0.00',q2.FieldByName('VL_VALOR').AsFloat),
FormatFloat('###,###,##0.00',q3.FieldByName('VL_VALOR').AsFloat + f_valor)
])) then
raise Exception.Create(Format(
'Não foi possivel continuar pois o Centro de Custos %s está configurado no '+
'Plano %s para movimentar apenas R$ %s mensalmente, e com esta movimentação ficaria com o valor de R$ %s, '+
'e o usuário optou por cancelar.',
[q2.FieldByName('DS_CCUSTO').AsString,
q2.FieldByName('DS_PLANO').AsString,
FormatFloat('###,###,##0.00',q2.FieldByName('VL_VALOR').AsFloat),
FormatFloat('###,###,##0.00',q3.FieldByName('VL_VALOR').AsFloat + f_valor)
]));
end;
end;
q1.Next;
end;
Result := True;
finally
FreeAndNil(q1);
FreeAndNil(q2);
FreeAndNil(q3);
end;
end;
function funcValidaCategoria : boolean;
var q1,q2,q3 : TIBQuery;
begin
Result := False;
procCriarQuery(q1);
procCriarQuery(q2);
procCriarQuery(q3);
try
q1.SQL.Text :=
'WITH RECURSIVE CAT_TREE AS( '+
' SELECT A.ID_CATPAI, '+
' A.ID_CATEG '+
' FROM CATEGORIA A '+
' WHERE A.ID_CATEG = '+IntToStr(i_categ)+
' UNION ALL '+
' '+
' SELECT A.ID_CATPAI, '+
' A.ID_CATEG '+
' FROM CATEGORIA A '+
' INNER JOIN CAT_TREE B ON '+
' B.ID_CATPAI = A.ID_CATEG)'+
' '+
' SELECT A.ID_CATEG '+
' FROM CAT_TREE A ';
q1.Open;
while not q1.Eof do
begin
q2.sql.Text :=
'SELECT A.VL_VALOR, '+
' A.FL_ALERTA, '+
' A.DS_PLANO, '+
' B.DS_CATEG '+
' FROM PLANO A '+
' INNER JOIN CATEGORIA B ON B.ID_CATEG = A.ID_CATEG'+
' WHERE A.ID_CATEG = :CATEG ';
q2.ParamByName('CATEG').AsInteger := q1.FieldByName('ID_CATEG').AsInteger;
q2.Open;
if not q2.IsEmpty then
begin
q3.sql.Text :=
'SELECT COALESCE(SUM(A.VL_MOVIM),0) * -1 VL_VALOR '+
' FROM MOVIMENTO A '+
' WHERE A.ID_CATEG IN ('+
funcListaCategoria(q1.FieldByName('ID_CATEG').AsInteger)+')'+
' AND A.DT_MOVIM BETWEEN :DATAINI AND :DATAFIN '+
' AND A.FL_TIPO = ''R'' '+
' AND A.ID_MOVIM <> :ESTEMOV '+
' AND NOT EXISTS(SELECT 1 FROM TRANSFERENCIA C '+
' WHERE (C.ID_MOVDEB = A.ID_MOVIM '+
' OR C.ID_MOVCRE = A.ID_MOVIM))';
q3.ParamByName('DATAINI').AsDateTime := DateUtils.StartOfTheMonth(d_data);
q3.ParamByName('DATAFIN').AsDateTime := DateUtils.EndOfTheMonth(d_data);
q3.ParamByName('ESTEMOV').AsInteger := i_mov;
q3.Open;
if (q3.FieldByName('VL_VALOR').AsFloat + f_valor) > q2.FieldByName('VL_VALOR').AsFloat then
begin
if q2.FieldByName('FL_ALERTA').AsString = 'B' then
raise Exception.Create(Format(
'Não será possivel continuar pois a Categoria %s está configurada no '+
'Plano %s para movimentar apenas R$ %s mensalmente, e com esta movimentação ficaria com o valor de R$ %s.',
[q2.FieldByName('DS_CATEG').AsString,
q2.FieldByName('DS_PLANO').AsString,
FormatFloat('###,###,##0.00',q2.FieldByName('VL_VALOR').AsFloat),
FormatFloat('###,###,##0.00',q3.FieldByName('VL_VALOR').AsFloat + f_valor)
]))
else
if not funcMsgConfirma(Format(
'A Categoria %s está configurada no Plano %s para movimentar apenas R$ %s mensalmente, '+
'e com esta movimentação ficará com o valor de R$ %s. Deseja continuar?',
[q2.FieldByName('DS_CATEG').AsString,
q2.FieldByName('DS_PLANO').AsString,
FormatFloat('###,###,##0.00',q2.FieldByName('VL_VALOR').AsFloat),
FormatFloat('###,###,##0.00',q3.FieldByName('VL_VALOR').AsFloat + f_valor)
])) then
raise Exception.Create(Format(
'Não foi possivel continuar pois a Categoria %s está configurada no '+
'Plano %s para movimentar apenas R$ %s mensalmente, e com esta movimentação ficaria com o valor de R$ %s, '+
'e o usuário optou por cancelar.',
[q2.FieldByName('DS_CATEG').AsString,
q2.FieldByName('DS_PLANO').AsString,
FormatFloat('###,###,##0.00',q2.FieldByName('VL_VALOR').AsFloat),
FormatFloat('###,###,##0.00',q3.FieldByName('VL_VALOR').AsFloat + f_valor)
]));
end;
end;
q1.Next;
end;
Result := True;
finally
FreeAndNil(q1);
FreeAndNil(q2);
FreeAndNil(q3);
end;
end;
begin
Result := funcValidaCCusto;
if result then
Result := funcValidaCategoria;
end;
function TdmFinanc.b_funcTemCCustoHierarquia(i_ccusto, i_ccpai : integer) : boolean;
begin
Result := (Trim(funcSelect(Format(
'WITH RECURSIVE CC_TREE AS( '+
' SELECT A.ID_CCUSTO '+
' FROM CCUSTO A '+
' WHERE A.ID_CCUSTO = %d '+
' UNION ALL '+
' '+
' SELECT A.ID_CCUSTO '+
' FROM CCUSTO A '+
' INNER JOIN CC_TREE B ON '+
' B.ID_CCUSTO = A.ID_CCPAI)'+
' '+
' SELECT A.ID_CCUSTO '+
' FROM CC_TREE A '+
' WHERE A.ID_CCUSTO = %d ',
[i_ccusto, i_ccpai]))) <> EmptyStr);
end;
procedure TdmFinanc.BensAfterInsert(DataSet: TDataSet);
begin
BensID_BEM.AsInteger := i_funcNextSequence('GEN_BENS');
BensDT_AQUISICAO.AsDateTime := funcHoje;
BensCD_USUARIO.AsString := CD_USUARIO_LOGADO;
end;
procedure TdmFinanc.BensDT_AQUISICAOValidate(Sender: TField);
begin
BensDT_VENDAValidate(Sender);
end;
procedure TdmFinanc.BensDT_VENDAValidate(Sender: TField);
begin
if (not BensDT_VENDA.IsNull) and (BensDT_VENDA.AsDateTime < BensDT_AQUISICAO.AsDateTime) then
raise Exception.Create('Data de Venda não pode ser menor que a data de aquisição');
end;
procedure TdmFinanc.BensVL_AQUISICAOValidate(Sender: TField);
begin
procValidaFieldNumericoPositivo(Sender);
end;
procedure TdmFinanc.BensVL_ATUALValidate(Sender: TField);
begin
procValidaFieldNumericoPositivo(Sender);
end;
function TdmFinanc.b_funcTemCategHierarquia(i_categ, i_catpai : integer) : boolean;
begin
Result := (Trim(funcSelect(Format(
'WITH RECURSIVE CAT_TREE AS( '+
' SELECT A.ID_CATEG '+
' FROM CATEGORIA A '+
' WHERE A.ID_CATEG = %d '+
' UNION ALL '+
' '+
' SELECT A.ID_CATEG '+
' FROM CATEGORIA A '+
' INNER JOIN CAT_TREE B ON '+
' B.ID_CATEG = A.ID_CATPAI)'+
' '+
' SELECT LIST(A.ID_CATEG) LISTA '+
' FROM CAT_TREE A '+
' WHERE A.ID_CATEG = %d ',
[i_categ, i_catpai]))) <> EmptyStr);
end;
function TdmFinanc.i_funcNextSequence(s_seq: string): integer;
begin
Result := strToInt(funcSelect('SELECT GEN_ID('+s_seq+',1) FROM RDB$DATABASE'));
end;
procedure TdmFinanc.MovimentoAfterEdit(DataSet: TDataSet);
begin
if MovimentoVL_MOVIM.AsFloat < 0 then
begin
MovimentoVL_BRUTO.AsFloat := MovimentoVL_BRUTO.AsFloat * -1;
end;
end;
procedure TdmFinanc.MovimentoAfterInsert(DataSet: TDataSet);
begin
MovimentoID_MOVIM.AsInteger := i_funcNextSequence('GEN_MOVIMENTO'); //i_funcProxInt('MOVIMENTO','ID_MOVIM');
MovimentoDT_MOVIM.AsDateTime := funcHoje;
MovimentoCD_USUARIO.AsString := CD_USUARIO_LOGADO;
MovimentoVL_MOVIM.AsFloat := 0;
MovimentoVL_JUROS.AsFloat := 0;
MovimentoVL_DESCON.AsFloat := 0;
MovimentoVL_BRUTO.AsFloat := 0;
if id_ConPad > 0 then
MovimentoID_CONTA.AsInteger := id_ConPad;
if id_CCPad > 0 then
MovimentoID_CCUSTO.AsInteger := id_CCPad;
end;
procedure TdmFinanc.MovimentoBeforePost(DataSet: TDataSet);
begin
if MovimentoVL_MOVIM.AsFloat = 0 then
procMsgErro('Valor não pode ser zero!',True);
if ((MovimentoFL_TIPO.AsString = 'R') and (MovimentoVL_MOVIM.AsFloat > 0)) or
((MovimentoFL_TIPO.AsString = 'D') and (MovimentoVL_MOVIM.AsFloat < 0)) then
MovimentoVL_MOVIM.AsFloat := MovimentoVL_MOVIM.AsFloat * -1;
end;
procedure TdmFinanc.MovimentoFL_TIPOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
procGetText(Sender, Text, DisplayText,
'R=Retirada'+sLineBreak+
'D=Depósito'
);
end;
procedure TdmFinanc.MovimentoVL_BRUTOValidate(Sender: TField);
begin
procValidaFieldNumericoPositivo(Sender);
procCalculaMovimentoVL_MOVIM;
end;
procedure TdmFinanc.MovimentoVL_DESCONValidate(Sender: TField);
begin
procValidaFieldNumericoPositivo(Sender);
procCalculaMovimentoVL_MOVIM;
end;
procedure TdmFinanc.MovimentoVL_JUROSValidate(Sender: TField);
begin
procValidaFieldNumericoPositivo(Sender);
procCalculaMovimentoVL_MOVIM;
end;
procedure TdmFinanc.PagarReceberAfterInsert(DataSet: TDataSet);
begin
PagarReceberID_PAGRECEB.AsInteger := i_funcNextSequence('GEN_PAGRECEB');
PagarReceberDT_VENCTO.AsDateTime := funcHoje;
PagarReceberCD_USUARIO.AsString := CD_USUARIO_LOGADO;
PagarReceberVL_VALOR.AsFloat := 0;
PagarReceberVL_PAGO.AsFloat := 0;
end;
procedure TdmFinanc.PagarReceberFL_TIPOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
procGetText(Sender, Text, DisplayText,
'P=Pagar'+sLineBreak+
'R=Receber'
);
end;
procedure TdmFinanc.PagarReceberVL_BRUTOValidate(Sender: TField);
begin
procValidaFieldNumericoPositivo(Sender);
end;
procedure TdmFinanc.PagarReceberVL_VALORValidate(Sender: TField);
begin
procValidaFieldNumericoPositivo(Sender);
end;
procedure TdmFinanc.PesCategoriaFL_ATIVOGetText(Sender: TField;
var Text: string; DisplayText: Boolean);
begin
procGetTextAtivoInativo(Sender, Text, DisplayText);
end;
procedure TdmFinanc.PesCCustoFL_ATIVOGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
procGetTextAtivoInativo(Sender, Text, DisplayText);
end;
procedure TdmFinanc.PlanoAfterInsert(DataSet: TDataSet);
begin
PlanoID_PLANO.AsInteger := i_funcNextSequence('GEN_PLANO');
PlanoCD_USUARIO.AsString := CD_USUARIO_LOGADO;
PlanoVL_VALOR.AsFloat := 0;
PlanoFL_ALERTA.AsString := 'A';
end;
procedure TdmFinanc.procCalculaMovimentoVL_MOVIM;
begin
MovimentoVL_MOVIM.AsFloat :=
MovimentoVL_BRUTO.AsFloat -
MovimentoVL_DESCON.AsFloat +
MovimentoVL_JUROS.AsFloat;
end;
procedure TdmFinanc.procCriaAtualizaMovimento(i_movto,i_conta : integer; f_valor : double; s_descri, s_tipo : string; i_categ : integer; d_data : TDate; i_ccusto : integer);
begin
dmFinanc.Movimento.Close;
dmFinanc.Movimento.sql.Text := SQL_MOVIMENTO +
' WHERE A.CD_USUARIO = :USUARIO'+
' AND A.ID_MOVIM = :MOVIM ';
dmFinanc.Movimento.ParamByName('USUARIO').AsString := CD_USUARIO_LOGADO;
dmFinanc.Movimento.ParamByName('MOVIM').AsInteger := i_movto;
dmFinanc.Movimento.Open;
if dmFinanc.Movimento.IsEmpty then
dmFinanc.Movimento.Append
else
dmFinanc.Movimento.Edit;
dmFinanc.MovimentoID_CONTA.AsInteger := i_conta;
dmFinanc.MovimentoVL_MOVIM.AsFloat := f_valor;
dmFinanc.MovimentoDS_MOVIM.AsString := s_descri;
dmFinanc.MovimentoFL_TIPO.AsString := s_tipo;
dmFinanc.MovimentoID_CATEG.AsInteger := i_categ;
dmFinanc.MovimentoDT_MOVIM.AsDateTime := d_data;
dmFinanc.MovimentoID_CCUSTO.AsInteger := i_ccusto;
dmFinanc.MovimentoCD_USUARIO.AsString := CD_USUARIO_LOGADO;
dmFinanc.Movimento.Post;
end;
procedure TdmFinanc.procGetText(Sender: TField; var Text: string;
DisplayText: Boolean; c_argumentos: string);
var slArgumentos : TStrings;
i : integer;
begin
Text := Sender.AsString;
if DisplayText then
begin
slArgumentos := TStringList.Create;
try
slArgumentos.Text := c_argumentos;
for i := 0 to slArgumentos.Count -1 do
begin
if Text = slArgumentos.Names[i] then
begin
Text := slArgumentos.ValueFromIndex[i];
Break;
end;
end;
finally
FreeAndNil(slArgumentos);
end;
end;
end;
procedure TdmFinanc.procGetTextAtivoInativo(Sender: TField; var Text: string;
DisplayText: Boolean);
begin
procGetText(Sender, Text, DisplayText,
'A=Ativo'+sLineBreak+
'I=Inativo'
);
end;
procedure TdmFinanc.procInsereMascara;
var iDm, iQry : integer;
function getFrac(iTam : integer) : string;
var i : integer;
begin
result := '';
for i := 0 to iTam - 1 do
begin
result := result + '0';
end;
end;
begin
for iDm := 0 to self.ComponentCount - 1 do
begin
if self.Components[iDm].ClassType = TIBQuery then
begin
for iQry := 0 to TIBQuery(self.Components[iDm]).FieldCount - 1 do
begin
//id e inteiros
if TIBQuery(self.Components[iDm]).Fields[iQry].ClassType = TIntegerField then
TIntegerField(TIBQuery(self.Components[iDm]).Fields[iQry]).DisplayFormat := '###,###,###'
//datas
else if TIBQuery(self.Components[iDm]).Fields[iQry].ClassType = TDateField then
TDateField(TIBQuery(self.Components[iDm]).Fields[iQry]).EditMask := '!99/99/9999;1;_'//'!99/99/9999;_'
//Datas e horas
else if TIBQuery(self.Components[iDm]).Fields[iQry].ClassType = TDateTimeField then
TDateTimeField(TIBQuery(self.Components[iDm]).Fields[iQry]).EditMask := '!99/99/9999 99:99:99;1;_' // '!99/99/9999 99:99;1;_'}
//quantidade e valores
else if TIBQuery(self.Components[iDm]).Fields[iQry].ClassType = TIBBCDField then
TIBBCDField(TIBQuery(self.Components[iDm]).Fields[iQry]).DisplayFormat := '###,###,##0.'+
getFrac(TIBBCDField(TIBQuery(self.Components[iDm]).Fields[iQry]).Size);
end;
end;
end;
end;
procedure TdmFinanc.procValidaFieldNumericoMaiorQueZero(campo: TField);
begin
if campo.IsNull then
Exit;
if campo.Value <= 0 then
procMsgErro('Campo '''+campo.DisplayLabel+''' deve ser maior que zero.',True);
end;
procedure TdmFinanc.procValidaFieldNumericoPercentual(campo: TField);
begin
if (campo.Value < 0) or (campo.Value > 100) then
procMsgErro('Campo '''+campo.DisplayLabel+''' deve ser entre 0 e 100.',True);
end;
procedure TdmFinanc.procValidaFieldNumericoPositivo(campo: TField);
begin
if campo.IsNull then
exit;
if campo.Value < 0 then
procMsgErro('Campo '''+campo.DisplayLabel+''' deve ser maior ou igual a zero.',True);
end;
procedure TdmFinanc.TransferenciaAfterInsert(DataSet: TDataSet);
begin
TransferenciaID_TRANSFER.AsInteger := i_funcNextSequence('GEN_TRANSF');
TransferenciaDT_TRANSF.AsDateTime := funcHoje;
TransferenciaCD_USUARIO.AsString := CD_USUARIO_LOGADO;
TransferenciaVL_TRANSF.AsFloat := 0;
end;
procedure TdmFinanc.TransferenciaVL_TRANSFValidate(Sender: TField);
begin
procValidaFieldNumericoPositivo(Sender);
end;
end.
|
unit XFaceHelper;
(*
* Compface - 48x48x1 image compression and decompression
*
* Copyright (c) James Ashton - Sydney University - June 1990.
*
* Written 11th November 1989.
*
* Delphi conversion Copyright (c) Nicholas Ring February 2012
*
* Permission is given to distribute these sources, as long as the
* copyright messages are not removed, and no monies are exchanged.
*
* No responsibility is taken for any errors on inaccuracies inherent
* either to the comments or the code of this program, but if reported
* to me, then an attempt will be made to fix them.
*)
{$IFDEF FPC}{$mode delphi}{$ENDIF}
interface
uses
Graphics;
type
TXFaceHelper = class
public
class function CreateXFaceBitmap(const AFirstColour : TColor;
const ASecondColour : TColor) : Graphics.TBitmap;
end;
implementation
uses
XFaceConstants,
Windows;
{ TXFaceHelper }
class function TXFaceHelper.CreateXFaceBitmap(const AFirstColour : TColor;
const ASecondColour : TColor) : Graphics.TBitmap;
var
LMaxLogPalette : Windows.TMaxLogPalette;
LRGBColour : Longint;
begin
Result := Graphics.TBitmap.Create;
Result.Monochrome := True;
Result.Width := XFaceConstants.cWIDTH;
Result.Height := XFaceConstants.cHEIGHT;
Result.PixelFormat := pf1bit;
LMaxLogPalette.palVersion := $0300; // "Magic Number" for Windows LogPalette
LMaxLogPalette.palNumEntries := 2;
LRGBColour := Graphics.ColorToRGB(AFirstColour);
LMaxLogPalette.palPalEntry[0].peRed := Windows.GetRValue(LRGBColour);
LMaxLogPalette.palPalEntry[0].peGreen := Windows.GetGValue(LRGBColour);
LMaxLogPalette.palPalEntry[0].peBlue := Windows.GetBValue(LRGBColour);
LMaxLogPalette.palPalEntry[0].peFlags := 0;
LRGBColour := Graphics.ColorToRGB(ASecondColour);
LMaxLogPalette.palPalEntry[1].peRed := Windows.GetRValue(LRGBColour);
LMaxLogPalette.palPalEntry[1].peGreen := Windows.GetGValue(LRGBColour);
LMaxLogPalette.palPalEntry[1].peBlue := Windows.GetBValue(LRGBColour);
LMaxLogPalette.palPalEntry[1].peFlags := 0;
Result.Palette := Windows.CreatePalette(PLogPalette(@LMaxLogPalette)^);
end;
end.
|
Unit TSTOStoreMenuMaster;
Interface
Uses XMLDoc, XMLIntf;
Type
ITSTOXmlStoreObject = Interface(IXmlNode)
['{323CE256-39FA-4CD0-BC10-D469F87D108F}']
Function GetType_: Widestring;
Function GetId: Integer;
Function GetName: Widestring;
Function GetShowDuringTutorial: Widestring;
Function GetAllowRandomRecommendation: Widestring;
Procedure SetType_(Value: Widestring);
Procedure SetId(Value: Integer);
Procedure SetName(Value: Widestring);
Procedure SetShowDuringTutorial(Value: Widestring);
Procedure SetAllowRandomRecommendation(Value: Widestring);
Property StoreObjectType : Widestring Read GetType_ Write SetType_;
Property Id : Integer Read GetId Write SetId;
Property Name : Widestring Read GetName Write SetName;
Property ShowDuringTutorial : Widestring Read GetShowDuringTutorial Write SetShowDuringTutorial;
Property AllowRandomRecommendation : Widestring Read GetAllowRandomRecommendation Write SetAllowRandomRecommendation;
End;
ITSTOXmlStoreObjectList = Interface(IXmlNodeCollection)
['{E910BBDA-1117-4B31-9341-503FEA896D53}']
Function Add: ITSTOXmlStoreObject;
Function Insert(Const Index: Integer): ITSTOXmlStoreObject;
Function GetItem(Index: Integer): ITSTOXmlStoreObject;
Property Items[Index: Integer]: ITSTOXmlStoreObject Read GetItem; Default;
End;
ITSTOXmlStoreRequirement = Interface(IXmlNode)
['{112587AE-9AA7-4748-8E58-55A53B49676E}']
Function GetType_: Widestring;
Function GetQuest: Widestring;
Procedure SetType_(Value: Widestring);
Procedure SetQuest(Value: Widestring);
Property StoreReqType : Widestring Read GetType_ Write SetType_;
Property Quest : Widestring Read GetQuest Write SetQuest;
End;
ITSTOXmlStoreRequirements = Interface(IXmlNodeCollection)
['{85817538-5B24-4053-A608-79D5D7A6DC61}']
Function GetRequirement(Index: Integer): ITSTOXmlStoreRequirement;
Function Add: ITSTOXmlStoreRequirement;
Function Insert(Const Index: Integer): ITSTOXmlStoreRequirement;
Property Requirement[Index: Integer]: ITSTOXmlStoreRequirement Read GetRequirement; Default;
End;
ITSTOXmlStoreCategory = Interface(IXmlNode)
['{8DB9BC2E-DE9A-4EE2-9976-0317657B7BEF}']
Function GetName: Widestring;
Function GetTitle: Widestring;
Function GetBaseCategory: Widestring;
Function GetIcon: Widestring;
Function GetDisabledIcon: Widestring;
Function GetEmptyText: Widestring;
Function GetFile_: Widestring;
Function GetObject_: ITSTOXmlStoreObjectList;
Function GetRequirements: ITSTOXmlStoreRequirements;
Procedure SetName(Value: Widestring);
Procedure SetTitle(Value: Widestring);
Procedure SetBaseCategory(Value: Widestring);
Procedure SetIcon(Value: Widestring);
Procedure SetDisabledIcon(Value: Widestring);
Procedure SetEmptyText(Value: Widestring);
Procedure SetFile_(Value: Widestring);
Property Name : Widestring Read GetName Write SetName;
Property Title : Widestring Read GetTitle Write SetTitle;
Property BaseCategory : Widestring Read GetBaseCategory Write SetBaseCategory;
Property Icon : Widestring Read GetIcon Write SetIcon;
Property DisabledIcon : Widestring Read GetDisabledIcon Write SetDisabledIcon;
Property EmptyText : Widestring Read GetEmptyText Write SetEmptyText;
Property FileName : Widestring Read GetFile_ Write SetFile_;
Property StoreObject : ITSTOXmlStoreObjectList Read GetObject_;
Property Requirements : ITSTOXmlStoreRequirements Read GetRequirements;
End;
ITSTOXmlStoreCategoryList = Interface(IXmlNodeCollection)
['{2F47CB96-F8BF-4B75-A59E-A52D7DDEFB12}']
Function Add: ITSTOXmlStoreCategory;
Function Insert(Const Index: Integer): ITSTOXmlStoreCategory;
Function GetItem(Index: Integer): ITSTOXmlStoreCategory;
Property Items[Index: Integer]: ITSTOXmlStoreCategory Read GetItem; Default;
End;
ITSTOXmlStoreMenus = Interface(IXmlNodeCollection)
['{7FB363C6-0643-4A56-ABAB-CAE50BAD11A9}']
Function GetCategory(Index: Integer): ITSTOXmlStoreCategory;
Function Add: ITSTOXmlStoreCategory;
Function Insert(Const Index: Integer): ITSTOXmlStoreCategory;
Property Category[Index: Integer]: ITSTOXmlStoreCategory Read GetCategory; Default;
End;
{ Global Functions }
Function GetStoreMenus(Doc: IXmlDocument): ITSTOXmlStoreMenus;
Function LoadStoreMenus(Const FileName: Widestring): ITSTOXmlStoreMenus;
Function NewStoreMenus: ITSTOXmlStoreMenus;
Const
TargetNamespace = '';
Implementation
Type
TXMLStoreMenusType = Class(TXMLNodeCollection, ITSTOXmlStoreMenus)
Protected
Function GetCategory(Index: Integer): ITSTOXmlStoreCategory;
Function Add: ITSTOXmlStoreCategory;
Function Insert(Const Index: Integer): ITSTOXmlStoreCategory;
Public
Procedure AfterConstruction; Override;
End;
TXMLCategoryType = Class(TXMLNode, ITSTOXmlStoreCategory)
Private
FObject_: ITSTOXmlStoreObjectList;
Protected
Function GetName: Widestring;
Function GetTitle: Widestring;
Function GetBaseCategory: Widestring;
Function GetIcon: Widestring;
Function GetDisabledIcon: Widestring;
Function GetEmptyText: Widestring;
Function GetFile_: Widestring;
Function GetObject_: ITSTOXmlStoreObjectList;
Function GetRequirements: ITSTOXmlStoreRequirements;
Procedure SetName(Value: Widestring);
Procedure SetTitle(Value: Widestring);
Procedure SetBaseCategory(Value: Widestring);
Procedure SetIcon(Value: Widestring);
Procedure SetDisabledIcon(Value: Widestring);
Procedure SetEmptyText(Value: Widestring);
Procedure SetFile_(Value: Widestring);
Public
Procedure AfterConstruction; Override;
End;
TXMLCategoryTypeList = Class(TXMLNodeCollection, ITSTOXmlStoreCategoryList)
Protected
Function Add: ITSTOXmlStoreCategory;
Function Insert(Const Index: Integer): ITSTOXmlStoreCategory;
Function GetItem(Index: Integer): ITSTOXmlStoreCategory;
End;
TXMLObjectType = Class(TXMLNode, ITSTOXmlStoreObject)
Protected
Function GetType_: Widestring;
Function GetId: Integer;
Function GetName: Widestring;
Function GetShowDuringTutorial: Widestring;
Function GetAllowRandomRecommendation: Widestring;
Procedure SetType_(Value: Widestring);
Procedure SetId(Value: Integer);
Procedure SetName(Value: Widestring);
Procedure SetShowDuringTutorial(Value: Widestring);
Procedure SetAllowRandomRecommendation(Value: Widestring);
End;
TXMLObjectTypeList = Class(TXMLNodeCollection, ITSTOXmlStoreObjectList)
Protected
Function Add: ITSTOXmlStoreObject;
Function Insert(Const Index: Integer): ITSTOXmlStoreObject;
Function GetItem(Index: Integer): ITSTOXmlStoreObject;
End;
TXMLRequirementsType = Class(TXMLNodeCollection, ITSTOXmlStoreRequirements)
Protected
Function GetRequirement(Index: Integer): ITSTOXmlStoreRequirement;
Function Add: ITSTOXmlStoreRequirement;
Function Insert(Const Index: Integer): ITSTOXmlStoreRequirement;
Public
Procedure AfterConstruction; Override;
End;
TXMLRequirementType = Class(TXMLNode, ITSTOXmlStoreRequirement)
Protected
Function GetType_: Widestring;
Function GetQuest: Widestring;
Procedure SetType_(Value: Widestring);
Procedure SetQuest(Value: Widestring);
End;
// TXMLRequirementTypeList = Class(TXMLNodeCollection, ITSTOXmlStoreRequirementList)
// Protected
// Function Add: ITSTOXmlStoreRequirement;
// Function Insert(Const Index: Integer): ITSTOXmlStoreRequirement;
// Function GetItem(Index: Integer): ITSTOXmlStoreRequirement;
//
// End;
(******************************************************************************)
{ Global Functions }
Function GetStoreMenus(Doc: IXmlDocument): ITSTOXmlStoreMenus;
Begin
Result := Doc.GetDocBinding('StoreMenus', TXMLStoreMenusType, TargetNamespace) As ITSTOXmlStoreMenus;
End;
Function LoadStoreMenus(Const FileName: Widestring): ITSTOXmlStoreMenus;
Begin
Result := LoadXMLDocument(FileName).GetDocBinding('StoreMenus', TXMLStoreMenusType, TargetNamespace) As ITSTOXmlStoreMenus;
End;
Function NewStoreMenus: ITSTOXmlStoreMenus;
Begin
Result := NewXMLDocument.GetDocBinding('StoreMenus', TXMLStoreMenusType, TargetNamespace) As ITSTOXmlStoreMenus;
End;
{ TXMLStoreMenusType }
Procedure TXMLStoreMenusType.AfterConstruction;
Begin
RegisterChildNode('Category', TXMLCategoryType);
ItemTag := 'Category';
ItemInterface := ITSTOXmlStoreCategory;
Inherited;
End;
Function TXMLStoreMenusType.GetCategory(Index: Integer): ITSTOXmlStoreCategory;
Begin
Result := List[Index] As ITSTOXmlStoreCategory;
End;
Function TXMLStoreMenusType.Add: ITSTOXmlStoreCategory;
Begin
Result := AddItem(-1) As ITSTOXmlStoreCategory;
End;
Function TXMLStoreMenusType.Insert(Const Index: Integer): ITSTOXmlStoreCategory;
Begin
Result := AddItem(Index) As ITSTOXmlStoreCategory;
End;
{ TXMLCategoryType }
Procedure TXMLCategoryType.AfterConstruction;
Begin
RegisterChildNode('Object', TXMLObjectType);
RegisterChildNode('Requirements', TXMLRequirementsType);
FObject_ := CreateCollection(TXMLObjectTypeList, ITSTOXmlStoreObject, 'Object') As ITSTOXmlStoreObjectList;
Inherited;
End;
Function TXMLCategoryType.GetName: Widestring;
Begin
Result := AttributeNodes['name'].Text;
End;
Procedure TXMLCategoryType.SetName(Value: Widestring);
Begin
SetAttribute('name', Value);
End;
Function TXMLCategoryType.GetTitle: Widestring;
Begin
Result := AttributeNodes['title'].Text;
End;
Procedure TXMLCategoryType.SetTitle(Value: Widestring);
Begin
SetAttribute('title', Value);
End;
Function TXMLCategoryType.GetBaseCategory: Widestring;
Begin
Result := AttributeNodes['baseCategory'].Text;
End;
Procedure TXMLCategoryType.SetBaseCategory(Value: Widestring);
Begin
SetAttribute('baseCategory', Value);
End;
Function TXMLCategoryType.GetIcon: Widestring;
Begin
Result := AttributeNodes['icon'].Text;
End;
Procedure TXMLCategoryType.SetIcon(Value: Widestring);
Begin
SetAttribute('icon', Value);
End;
Function TXMLCategoryType.GetDisabledIcon: Widestring;
Begin
Result := AttributeNodes['disabledIcon'].Text;
End;
Procedure TXMLCategoryType.SetDisabledIcon(Value: Widestring);
Begin
SetAttribute('disabledIcon', Value);
End;
Function TXMLCategoryType.GetEmptyText: Widestring;
Begin
Result := AttributeNodes['emptyText'].Text;
End;
Procedure TXMLCategoryType.SetEmptyText(Value: Widestring);
Begin
SetAttribute('emptyText', Value);
End;
Function TXMLCategoryType.GetFile_: Widestring;
Begin
Result := AttributeNodes['file'].Text;
End;
Procedure TXMLCategoryType.SetFile_(Value: Widestring);
Begin
SetAttribute('file', Value);
End;
Function TXMLCategoryType.GetObject_: ITSTOXmlStoreObjectList;
Begin
Result := FObject_;
End;
Function TXMLCategoryType.GetRequirements: ITSTOXmlStoreRequirements;
Begin
Result := ChildNodes['Requirements'] As ITSTOXmlStoreRequirements;
End;
{ TXMLCategoryTypeList }
Function TXMLCategoryTypeList.Add: ITSTOXmlStoreCategory;
Begin
Result := AddItem(-1) As ITSTOXmlStoreCategory;
End;
Function TXMLCategoryTypeList.Insert(Const Index: Integer): ITSTOXmlStoreCategory;
Begin
Result := AddItem(Index) As ITSTOXmlStoreCategory;
End;
Function TXMLCategoryTypeList.GetItem(Index: Integer): ITSTOXmlStoreCategory;
Begin
Result := List[Index] As ITSTOXmlStoreCategory;
End;
{ TXMLObjectType }
Function TXMLObjectType.GetType_: Widestring;
Begin
Result := AttributeNodes['type'].Text;
End;
Procedure TXMLObjectType.SetType_(Value: Widestring);
Begin
SetAttribute('type', Value);
End;
Function TXMLObjectType.GetId: Integer;
Begin
Result := AttributeNodes['id'].NodeValue;
End;
Procedure TXMLObjectType.SetId(Value: Integer);
Begin
SetAttribute('id', Value);
End;
Function TXMLObjectType.GetName: Widestring;
Begin
Result := AttributeNodes['name'].Text;
End;
Procedure TXMLObjectType.SetName(Value: Widestring);
Begin
SetAttribute('name', Value);
End;
Function TXMLObjectType.GetShowDuringTutorial: Widestring;
Begin
Result := AttributeNodes['showDuringTutorial'].Text;
End;
Procedure TXMLObjectType.SetShowDuringTutorial(Value: Widestring);
Begin
SetAttribute('showDuringTutorial', Value);
End;
Function TXMLObjectType.GetAllowRandomRecommendation: Widestring;
Begin
Result := AttributeNodes['allowRandomRecommendation'].Text;
End;
Procedure TXMLObjectType.SetAllowRandomRecommendation(Value: Widestring);
Begin
SetAttribute('allowRandomRecommendation', Value);
End;
{ TXMLObjectTypeList }
Function TXMLObjectTypeList.Add: ITSTOXmlStoreObject;
Begin
Result := AddItem(-1) As ITSTOXmlStoreObject;
End;
Function TXMLObjectTypeList.Insert(Const Index: Integer): ITSTOXmlStoreObject;
Begin
Result := AddItem(Index) As ITSTOXmlStoreObject;
End;
Function TXMLObjectTypeList.GetItem(Index: Integer): ITSTOXmlStoreObject;
Begin
Result := List[Index] As ITSTOXmlStoreObject;
End;
{ TXMLRequirementsType }
Procedure TXMLRequirementsType.AfterConstruction;
Begin
RegisterChildNode('Requirement', TXMLRequirementType);
ItemTag := 'Requirement';
ItemInterface := ITSTOXmlStoreRequirement;
Inherited;
End;
Function TXMLRequirementsType.GetRequirement(Index: Integer): ITSTOXmlStoreRequirement;
Begin
Result := List[Index] As ITSTOXmlStoreRequirement;
End;
Function TXMLRequirementsType.Add: ITSTOXmlStoreRequirement;
Begin
Result := AddItem(-1) As ITSTOXmlStoreRequirement;
End;
Function TXMLRequirementsType.Insert(Const Index: Integer): ITSTOXmlStoreRequirement;
Begin
Result := AddItem(Index) As ITSTOXmlStoreRequirement;
End;
{ TXMLRequirementType }
Function TXMLRequirementType.GetType_: Widestring;
Begin
Result := AttributeNodes['type'].Text;
End;
Procedure TXMLRequirementType.SetType_(Value: Widestring);
Begin
SetAttribute('type', Value);
End;
Function TXMLRequirementType.GetQuest: Widestring;
Begin
Result := AttributeNodes['quest'].Text;
End;
Procedure TXMLRequirementType.SetQuest(Value: Widestring);
Begin
SetAttribute('quest', Value);
End;
End. |
unit Project87.Types.SimpleGUI;
interface
uses
QCore.Types,
QCore.Input,
Strope.Math,
QEngine.Font;
type
TEventAction = procedure of object;
TWidget = class abstract (TComponent)
strict protected
FPosition: TVectorF;
FSize: TVectorF;
FCaption: string;
FColor: Cardinal;
FFont: TQuadFont;
FIsFocused: Boolean;
FIsEnabled: Boolean;
FOnMouseMove: TEventAction;
FOnClick: TEventAction;
procedure SetSize(const ASize: TVectorF); virtual;
procedure SetCaption(const ACaption: string); virtual;
public
constructor Create;
function OnMouseMove(const AMousePosition: TVectorF): Boolean; override;
function OnMouseButtonUp(AButton: TMouseButton;
const AMousePosition: TVectorF): Boolean; override;
property Position: TVectorF read FPosition write FPosition;
property Size: TVectorF read FSize write SetSize;
property Caption: string read FCaption write SetCaption;
property Color: Cardinal read FColor write FColor;
property Font: TQuadFont read FFont write FFont;
property IsEnabled: Boolean read FIsEnabled write FIsEnabled;
property OnMouseMoveEvent: TEventAction read FOnMouseMove write FOnMouseMove;
property OnClickEvent: TEventAction read FOnClick write FOnClick;
end;
TSimpleButton = class (TWidget)
strict protected
public
end;
TGUIManager = class sealed (TComponent)
public
constructor Create;
destructor Destroy; override;
end;
implementation
{$REGION ' TWidget '}
constructor TWidget.Create;
begin
end;
procedure TWidget.SetSize(const ASize: TVector2F);
begin
end;
procedure TWidget.SetCaption(const ACaption: string);
begin
end;
function TWidget.OnMouseMove(const AMousePosition: TVector2F): Boolean;
begin
Result := False;
end;
function TWidget.OnMouseButtonUp(AButton: TMouseButton;
const AMousePosition: TVectorF): Boolean;
begin
Result := False;
end;
{$ENDREGION}
{$REGION ' TGUIManager '}
constructor TGUIManager.Create;
begin
end;
destructor TGUIManager.Destroy;
begin
inherited;
end;
{$ENDREGION}
end.
|
//***************************************************************************
//
// 名称:RTX.Common.pas
// 工具:RAD Studio XE6
// 日期:2014/11/8 15:12:01
// 作者:ying32
// QQ :396506155
// MSN :ying_32@live.cn
// E-mail:yuanfen3287@vip.qq.com
// Website:http://www.ying32.com
//
//---------------------------------------------------------------------------
//
// 备注:
//
//
//***************************************************************************
unit RTX.Common;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
ActiveX, ComObj;
const
VARIANT_FALSE = WordBool(0);
VARIANT_TRUE = WordBool(-1);
type
TEventSink = class(TInterfacedObject, IUnknown, IDispatch)
private
[weak]FController: IUnknown;
FIId: TIID;
FConnectionToken: Integer;
protected
function QueryInterface(const IID: TGUID; out Obj):HResult;stdcall;
function GetTypeInfoCount(out Count: Integer): HResult; stdcall;
function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall;
function GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall;
function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall;
protected
procedure InvokeEvent(DispID: TDispID; var Params: TOleVariantArray); virtual;
public
constructor Create(AController: IUnknown; AIId: TIID);
destructor Destroy; override;
end;
function TypeLibOfUUID(UUID: TGUID; LibMajor: Word = 1; LibMinor: Word = 0; LocalLang: Cardinal = 0): ITypeLib; inline;
implementation
function TypeLibOfUUID(UUID: TGUID; LibMajor: Word = 1; LibMinor: Word = 0; LocalLang: Cardinal = 0): ITypeLib;
begin
OleCheck(LoadRegTypeLib(UUID, LibMajor, LibMinor, LocalLang, Result));
end;
{ TEventSink }
constructor TEventSink.Create(AController: IUnknown; AIId: TIID);
begin
inherited Create;
FController := AController;
FIId := AIId;
InterfaceConnect(FController, FIId, Self, FConnectionToken);
end;
destructor TEventSink.Destroy;
begin
InterfaceDisconnect(FController, FIId, FConnectionToken);
inherited;
end;
function TEventSink.GetIDsOfNames(const IID: TGUID;
Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult;
begin
Result := S_OK;
end;
function TEventSink.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult;
begin
Result := S_OK;
end;
function TEventSink.GetTypeInfoCount(out Count: Integer): HResult;
begin
Result := S_OK;
end;
function TEventSink.Invoke(DispID: Integer;
const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult,
ExcepInfo, ArgErr: Pointer): HResult;
var
vPDispParams: PDispParams;
begin
vPDispParams := PDispParams(@Params);
Result := EventDispatchInvoke(DispID, vPDispParams^,
procedure(DispId: Integer; var Params: TOleVariantArray)
begin
Self.InvokeEvent(DispID, Params);
end);
end;
procedure TEventSink.InvokeEvent(DispID: TDispID;
var Params: TOleVariantArray);
begin
// no code
end;
function TEventSink.QueryInterface(const IID: TGUID;
out Obj): HResult;
begin
if GetInterFace(IID,Obj) then
Result := S_OK
else if IsEqualIID(IID, FIId) then
Result := QueryInterface(IDispatch,Obj)
else
Result := E_NOINTERFACE;
end;
end.
|
unit uCartasCadastro;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, JvExControls, JvXPCore, JvXPButtons, DB, ComCtrls, DBCtrls, StdCtrls, Mask, Buttons;
type
TfrmCartasCadastro = class(TForm)
Label1: TLabel;
Label2: TLabel;
lbCampos: TLabel;
Label3: TLabel;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
btOK: TJvXPButton;
btCancelar: TJvXPButton;
edDescricao: TDBEdit;
cbCampos: TComboBox;
btIncluir: TJvXPButton;
memo: TMemo;
dbeCodigo: TDBEdit;
ckFormatoRTF: TDBCheckBox;
btnFontes: TJvXPButton;
memoRTF: TDBRichEdit;
mmRTFAux: TRichEdit;
DBEdit1: TDBEdit;
DBEdit2: TDBEdit;
DBEdit3: TDBEdit;
DBEdit4: TDBEdit;
DBCheckBox1: TDBCheckBox;
dsCartas: TDataSource;
fdlg: TFontDialog;
procedure SpeedButton3Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure DBCheckBox1Click(Sender: TObject);
procedure ckFormatoRTFClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btOKClick(Sender: TObject);
procedure btnFontesClick(Sender: TObject);
procedure btIncluirClick(Sender: TObject);
private
{ Private declarations }
public
procedure SomenteLeitura;
procedure FormatoDoTexto;
{ Public declarations }
end;
var
frmCartasCadastro: TfrmCartasCadastro;
implementation
uses uCartas, Consttipos;
{$R *.dfm}
{ TfrmCartasCadastro }
procedure TfrmCartasCadastro.btIncluirClick(Sender: TObject);
begin
if cbCampos.ItemIndex >- 1 then
begin
if ckFormatoRTF.Checked then
begin
memoRTF.SelText := '['+Trim(cbCampos.Text)+']';
memoRTF.SetFocus;
end else
begin
memo.SelText := '['+Trim(cbCampos.Text)+']';
memo.SetFocus;
end;
end;
end;
procedure TfrmCartasCadastro.btnFontesClick(Sender: TObject);
begin
fdlg.Font.Color := memoRTF.SelAttributes.Color;
fdlg.Font.Name := memoRTF.SelAttributes.Name;
fdlg.Font.Pitch := memoRTF.SelAttributes.Pitch;
fdlg.font.Size := memoRTF.SelAttributes.Size;
fdlg.Font.Style := memoRTF.SelAttributes.Style;
if fdlg.Execute then
begin
memoRTF.SelAttributes.Color := fdlg.Font.Color;
memoRTF.SelAttributes.Name := fdlg.Font.Name;
memoRTF.SelAttributes.Pitch := fdlg.Font.Pitch;
memoRTF.SelAttributes.Size := fdlg.font.Size;
memoRTF.SelAttributes.Style := fdlg.Font.Style;
end;
end;
procedure TfrmCartasCadastro.btOKClick(Sender: TObject);
begin
btOK.SetFocus;
if frmCartas.sqlCartasDescricao.Value = '' then
begin
MessageBox(Handle, 'Informe a descrição da carta.', 'Atenção!', MB_ICONERROR);
edDescricao.SetFocus;
end else
if (Trim(memo.Lines.Text) = '') and (not ckFormatoRTF.Checked) then
begin
MessageBox(Handle, 'Informe um texto para a carta.', 'Atenção!', MB_ICONERROR);
memo.SetFocus;
end else
ModalResult := mrOk;
end;
procedure TfrmCartasCadastro.ckFormatoRTFClick(Sender: TObject);
begin
FormatoDoTexto;
end;
procedure TfrmCartasCadastro.DBCheckBox1Click(Sender: TObject);
begin
FormatoDoTexto;
end;
procedure TfrmCartasCadastro.FormActivate(Sender: TObject);
begin
FormatoDoTexto;
end;
procedure TfrmCartasCadastro.FormatoDoTexto;
begin
memoRTF.Visible := ckFormatoRTF.Checked;
btnFontes.Visible := ckFormatoRTF.Checked;
memo.Visible := not ckFormatoRTF.Checked;
end;
procedure TfrmCartasCadastro.FormCreate(Sender: TObject);
var
i : Integer;
begin
cbCampos.Items.Clear;
for i := 1 to MAX_CAMPOS_COBRANCA do
cbCampos.Items.Add(CamposCobranca[i]);
end;
procedure TfrmCartasCadastro.SomenteLeitura;
begin
dbeCodigo.ReadOnly := True;
edDescricao.ReadOnly := True;
memo.ReadOnly := True;
dbeCodigo.Color := clBtnFace;
edDescricao.Color := clBtnFace;
memo.Color := clBtnFace;
cbCampos.Visible := False;
lbCampos.Visible := False;
btIncluir.Visible := False;
DBEdit1.Color := clBtnFace;
DBEdit2.Color := clBtnFace;
DBEdit3.Color := clBtnFace;
DBEdit4.Color := clBtnFace;
end;
procedure TfrmCartasCadastro.SpeedButton1Click(Sender: TObject);
begin
memoRTF.Paragraph.Alignment := taLeftJustify;
end;
procedure TfrmCartasCadastro.SpeedButton2Click(Sender: TObject);
begin
memoRTF.Paragraph.Alignment := taCenter;
end;
procedure TfrmCartasCadastro.SpeedButton3Click(Sender: TObject);
begin
memoRTF.Paragraph.Alignment := taRightJustify;
end;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://localhost:8888/wsdl/IObservationsWS
// Encoding : utf-8
// Version : 1.0
// (3/30/2012 11:45:11 AM - 1.33.2.5)
// ************************************************************************ //
unit IObservationsProxy;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Borland types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:string - "http://www.w3.org/2001/XMLSchema"
// !:int - "http://www.w3.org/2001/XMLSchema"
// !:dateTime - "http://www.w3.org/2001/XMLSchema"
// !:boolean - "http://www.w3.org/2001/XMLSchema"
// !:double - "http://www.w3.org/2001/XMLSchema"
// !:TIntegerDynArray - "http://www.borland.com/namespaces/Types"
// !:float - "http://www.w3.org/2001/XMLSchema"
FormatData = class; { "urn:CommunicationObj" }
TTemplateInfo = class; { "urn:CommunicationObj" }
{ "urn:CommunicationObj" }
DesignKindEnum = (dk_PPI, dk_RHI);
{ "urn:CommunicationObj" }
TxPulseEnum = (tx_Pulse_Long, tx_Pulse_Short, tx_Pulse_None, tx_Pulse_Dual);
{ "urn:CommunicationObj" }
TWaveLengthEnum = (wl_3cm, wl_10cm);
// ************************************************************************ //
// Namespace : urn:CommunicationObj
// ************************************************************************ //
FormatData = class(TRemotable)
private
FOnda: TWaveLengthEnum;
FCeldas: Integer;
FLong: Integer;
FPotMet: Single;
published
property Onda: TWaveLengthEnum read FOnda write FOnda;
property Celdas: Integer read FCeldas write FCeldas;
property Long: Integer read FLong write FLong;
property PotMet: Single read FPotMet write FPotMet;
end;
TFormatArray = array of FormatData; { "urn:CommunicationObj" }
// ************************************************************************ //
// Namespace : urn:CommunicationObj
// ************************************************************************ //
TTemplateInfo = class(TRemotable)
private
FName: WideString;
FFlags: Integer;
FAddress: WideString;
FFTPSettings: WideString;
FPeriod: TXSDateTime;
FDelay: TXSDateTime;
FKind: DesignKindEnum;
FStart: Integer;
FFinish: Integer;
FSpeed: Integer;
FAngles: Integer;
FFormats: Integer;
FAutomatic: Boolean;
FSentFTP: Boolean;
FLastTime: TXSDateTime;
FNextTime: TXSDateTime;
FPulse: TxPulseEnum;
FCH3cm_ManualAFC: Boolean;
FCH3cm_StaloPower: Double;
FCH3cm_StaloFreq: Integer;
FCH3cm_NCO: Integer;
FCH10cm_ManualAFC: Boolean;
FCH10cm_StaloPower: Double;
FCH10cm_StaloFreq: Integer;
FCH10cm_NCO: Integer;
FAngleList: TIntegerDynArray;
FFormatList: TFormatArray;
public
destructor Destroy; override;
published
property Name: WideString read FName write FName;
property Flags: Integer read FFlags write FFlags;
property Address: WideString read FAddress write FAddress;
property FTPSettings: WideString read FFTPSettings write FFTPSettings;
property Period: TXSDateTime read FPeriod write FPeriod;
property Delay: TXSDateTime read FDelay write FDelay;
property Kind: DesignKindEnum read FKind write FKind;
property Start: Integer read FStart write FStart;
property Finish: Integer read FFinish write FFinish;
property Speed: Integer read FSpeed write FSpeed;
property Angles: Integer read FAngles write FAngles;
property Formats: Integer read FFormats write FFormats;
property Automatic: Boolean read FAutomatic write FAutomatic;
property SentFTP: Boolean read FSentFTP write FSentFTP;
property LastTime: TXSDateTime read FLastTime write FLastTime;
property NextTime: TXSDateTime read FNextTime write FNextTime;
property Pulse: TxPulseEnum read FPulse write FPulse;
property CH3cm_ManualAFC: Boolean read FCH3cm_ManualAFC write FCH3cm_ManualAFC;
property CH3cm_StaloPower: Double read FCH3cm_StaloPower write FCH3cm_StaloPower;
property CH3cm_StaloFreq: Integer read FCH3cm_StaloFreq write FCH3cm_StaloFreq;
property CH3cm_NCO: Integer read FCH3cm_NCO write FCH3cm_NCO;
property CH10cm_ManualAFC: Boolean read FCH10cm_ManualAFC write FCH10cm_ManualAFC;
property CH10cm_StaloPower: Double read FCH10cm_StaloPower write FCH10cm_StaloPower;
property CH10cm_StaloFreq: Integer read FCH10cm_StaloFreq write FCH10cm_StaloFreq;
property CH10cm_NCO: Integer read FCH10cm_NCO write FCH10cm_NCO;
property AngleList: TIntegerDynArray read FAngleList write FAngleList;
property FormatList: TFormatArray read FFormatList write FFormatList;
end;
// ************************************************************************ //
// Namespace : urn:ObservationsWSIntf-IObservationsWS
// soapAction: urn:ObservationsWSIntf-IObservationsWS#%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// style : rpc
// binding : IObservationsWSbinding
// service : IObservationsWSservice
// port : IObservationsWSPort
// URL : http://localhost:8888/soap/IObservationsWS
// ************************************************************************ //
IObservationsWS = interface(IInvokable)
['{7EC4E564-CBC3-DE95-D4A1-01395292B708}']
function Get_Plantillas: Integer; stdcall;
procedure Ejecutar(const Name: WideString); stdcall;
function Plantilla(const Index: Integer): TTemplateInfo; stdcall;
function Buscar(const Name: WideString): TTemplateInfo; stdcall;
procedure ChequearRadar; stdcall;
procedure Borrar(const Name: WideString); stdcall;
function Nueva: TTemplateInfo; stdcall;
function Control(const Name: WideString): TTemplateInfo; stdcall;
function Clonar(const TemplateName: WideString): TTemplateInfo; stdcall;
procedure Save(const Template: TTemplateInfo); stdcall;
procedure Automatica(const TemplateName: WideString; const Value: Boolean); stdcall;
function Get_InProgress: Boolean; stdcall;
function Get_Name: WideString; stdcall;
function Get_Client: WideString; stdcall;
function Get_StartTime: TXSDateTime; stdcall;
function Get_LastTime: TXSDateTime; stdcall;
function Get_Progress: Integer; stdcall;
function Get_Message: WideString; stdcall;
function Get_SubMsg: WideString; stdcall;
function Get_Result: Integer; stdcall;
procedure Cancel; stdcall;
end;
function GetIObservationsWS(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): IObservationsWS;
implementation
function GetIObservationsWS(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): IObservationsWS;
const
defWSDL = 'http://localhost:8888/wsdl/IObservationsWS';
defURL = 'http://localhost:8888/soap/IObservationsWS';
defSvc = 'IObservationsWSservice';
defPrt = 'IObservationsWSPort';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as IObservationsWS);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
destructor TTemplateInfo.Destroy;
var
I: Integer;
begin
for I := 0 to Length(FFormatList)-1 do
if Assigned(FFormatList[I]) then
FFormatList[I].Free;
SetLength(FFormatList, 0);
if Assigned(FPeriod) then
FPeriod.Free;
if Assigned(FDelay) then
FDelay.Free;
if Assigned(FLastTime) then
FLastTime.Free;
if Assigned(FNextTime) then
FNextTime.Free;
inherited Destroy;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(IObservationsWS), 'urn:ObservationsWSIntf-IObservationsWS', 'utf-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(IObservationsWS), 'urn:ObservationsWSIntf-IObservationsWS#%operationName%');
RemClassRegistry.RegisterXSInfo(TypeInfo(DesignKindEnum), 'urn:CommunicationObj', 'DesignKindEnum');
RemClassRegistry.RegisterXSInfo(TypeInfo(TxPulseEnum), 'urn:CommunicationObj', 'TxPulseEnum');
RemClassRegistry.RegisterXSInfo(TypeInfo(TWaveLengthEnum), 'urn:CommunicationObj', 'TWaveLengthEnum');
RemClassRegistry.RegisterXSClass(FormatData, 'urn:CommunicationObj', 'FormatData');
RemClassRegistry.RegisterXSInfo(TypeInfo(TFormatArray), 'urn:CommunicationObj', 'TFormatArray');
RemClassRegistry.RegisterXSClass(TTemplateInfo, 'urn:CommunicationObj', 'TTemplateInfo');
end. |
unit SystemAuthentificationFormControllerEvents;
interface
uses
ServiceInfo,
ClientAccount,
AuthentificationData,
Event;
type
TLogOnRequestedEvent = class (TEvent)
end;
TClientAuthentificatedEvent = class (TEvent)
private
FClientAccount: TClientAccount;
FClientServiceAuthentificationData: TClientServiceAuthentificationData;
public
constructor Create(
ClientAccount: TClientAccount;
ClientServiceAuthentificationData: TClientServiceAuthentificationData
);
property ClientAccount: TClientAccount read FClientAccount;
property ClientServiceAuthentificationData:
TClientServiceAuthentificationData
read FClientServiceAuthentificationData
write FClientServiceAuthentificationData;
end;
implementation
{ TClientAuthentificatedEvent }
constructor TClientAuthentificatedEvent.Create(
ClientAccount: TClientAccount;
ClientServiceAuthentificationData: TClientServiceAuthentificationData
);
begin
inherited Create;
FClientAccount := ClientAccount;
FClientServiceAuthentificationData := ClientServiceAuthentificationData;
end;
end.
|
unit MtxTypes;
// =============================================================================
// =============================================================================
//
// Module name : $RCSfile: MtxTypes.pas,v $
// Short description : Contains global data types, which are used
// by the library components and/or MSC.
// Project : MSC 2.8
// Compiler : Delphi 2007
// First author : 2007-03-22 /gsv/
// Author : $Author: gsv $
// Version : $Revision: 1.55 $
// Copyright : (c) Metronix GmbH 2007
// -----------------------------------------------------------------------------
// History : --
// -----------------------------------------------------------------------------
// Descriptions
// =============================================================================
{$INCLUDE MtxCompilers.inc}
interface
{$IFDEF USE_STD_LIB_INSTEAD_OF_TNT_LIB}
uses SysUtils, Classes, Contnrs, SyncObjs, Windows, System.Generics.Collections,
System.Generics.Defaults, Types, StrUtils, Controls;
{$ELSE}
uses SysUtils, Classes, TntSysUtils, TntDialogs, Contnrs, SyncObjs, Windows,
System.Generics.Collections, System.Generics.Defaults, Types, StrUtils,
Controls;
{$ENDIF}
// 2008-10-22 /gsv/: Bei Delphi 2007 muss dieser Compiler-Schalter gesetzt werden,
// damit es keine Warnung beim Compilieren gibt (Konflikt mit dem published-Abschnitt).
// Den Schalter gibt es auch schon unter Delphi 7, also keine Sonderbehandlung für Delphi 2007.
// Scope of $TYPEINFO = local
{$TYPEINFO ON}
const
C_DEF_BIT_INV_LOGIC = false; // Defaultwert für die Eigenschaft InvLogic von TBitListentry
// Konstanten für die Länge des Datentyps TDataType in Bits
C_BITS_PER_BYTE = 8; // Ein Byte hat 8 Bits!
C_BIT_SIZE_INT8 = C_BITS_PER_BYTE*1;
C_BIT_SIZE_INT16 = C_BITS_PER_BYTE*2;
C_BIT_SIZE_INT32 = C_BITS_PER_BYTE*4;
C_CHAR_COMMENT_LINE = ';';
// Konstanten für Key-Codes, die in Windows.pas nicht definiert sind.
VK_0 = $30; // Taste 0 (Nicht Numpad0!)
VK_1 = $31; // Taste 1 (Nicht Numpad1!)
VK_2 = $32; // Taste 2 (Nicht Numpad2!)
VK_3 = $33; // Taste 3 (Nicht Numpad3!)
VK_4 = $34; // Taste 4 (Nicht Numpad4!)
VK_5 = $35; // Taste 5 (Nicht Numpad5!)
VK_6 = $36; // Taste 6 (Nicht Numpad6!)
VK_7 = $37; // Taste 7 (Nicht Numpad7!)
VK_8 = $38; // Taste 8 (Nicht Numpad8!)
VK_9 = $39; // Taste 9 (Nicht Numpad9!)
VK_PERIOD = $BE; // Punkt
C_TEXT_ID_DEFAULT_VALUE = -1; // Default-Wert der TextID-Property
C_TEXT_ID_FORMAT_TEXT_CUSTOMER_SPECIFIC = 3236; // Default-Wert der FormatTextID-Property für die ComboBox
// TEXT_3236 = kundenspezifisch 0x%.08X
// 2016-09-14 /gsv/: Konstanten für die Default-Position der MSC-Fenster
C_MTX_DEF_WIN_POS_LEFT = 4;
C_MTX_DEF_WIN_POS_TOP = 4;
type // Because of the forward declarations do not use other "type" keywords
// until the end of all type declarations!
// ===========================================================================
// F O R W A R D D E C L A R A T I O N S
// ===========================================================================
TMaskedTableEntry = class;
// ===========================================================================
// T Y P E D E C L A R A T I O N S
// ===========================================================================
{$IFDEF USE_STD_LIB_INSTEAD_OF_TNT_LIB}
TWideCaption = type string;
{$ENDIF}
// ===========================================================================
// E X C E P T I O N D E C L A R A T I O N S
// ===========================================================================
// ===========================================================================
// Class MtxException
// Oberklasse für alle MTX spezifischen Exceptions.
// ===========================================================================
MtxException = class ( Exception )
end; // MtxException = class ( Exception )
// ===========================================================================
// Class EFileError
// A MTX defined exception. This exception is thrown,
// when an error occurs during a file operation required.
// ===========================================================================
EFileError = class ( MtxException )
end; // type EFileError = class ( MtxException )
// ===========================================================================
// Class EFileNotFound
// Diese Exception wird beim lesenden Zugriff auf eine nicht existierende
// Datei ausgelöst.
// ===========================================================================
EFileNotFound = class ( MtxException )
end; // type EFileNotFound = class ( MtxException )
// ===========================================================================
// Class EObjectNotExist
// A MTX defined exception. This exception is thrown,
// when a required object cannot be found, e.g. searching for an object in
// an array, which doesn't contain the desired object.
// ===========================================================================
EObjectNotExist = class ( MtxException )
end; // type EObjectNotExist = class ( MtxException )
// ===========================================================================
// Class EObjectAlreadyExist
// Diese Exception wird ausgelöst, wenn ein Objekt bereits existiert,
// z.B. wenn in eine Liste ein Objekt eingefügt werden soll, welches in der
// Liste bereits enthalten ist (Duplikate ausschließen).
// ===========================================================================
EObjectAlreadyExist = class ( MtxException )
end; // type EObjectAlreadyExist = class ( MtxException )
// ===========================================================================
// Class ETooManyObjects
// Diese Exception wird beim Einfügen eines Objektes in eine Liste,
// die bereits voll ist und keine weiteren Objekte aufnehmen kann.
// z.B. Hinzufügen eines CAN-Objektes in ein PDO, welches bereits die maximale
// Anzahl von CAN-Objekten enthält.
// ===========================================================================
ETooManyObjects = class ( MtxException )
end; // type ETooManyObjects = class ( MtxException )
// ===========================================================================
// Class ETooMuchData
// Diese Exception wird bei zu vielen Daten ausgelöst.
// z.B. Hinzufügen eines CAN-Objektes in ein PDO,
// bei dem die 64-Bits bereits belegt sind bzw. durch das Einfügen des Objektes
// diese Datenlänge von 64-Bits überschritten wird.
// ===========================================================================
ETooMuchData = class ( MtxException )
end; // type ETooMuchData = class ( MtxException )
// ===========================================================================
// Class EIndexOutOfBounds
// A MTX defined exception. This exception is thrown,
// when an array/list element is indexed with an invalid index,
// e.g. index < 0 OR index >= number of elements
// ===========================================================================
EIndexOutOfBounds = class ( MtxException )
end; // EIndexOutOfBounds = class ( MtxException )
// ===========================================================================
// Class EInvalidState
// This exception is thrown, when an invalid state is reached,
// e.g. the default state in a switch-statement.
// ===========================================================================
EInvalidState = class ( MtxException )
end; // EInvalidState = class ( MtxException )
// ===========================================================================
// Class EInvalidArgument
// This exception is thrown, when function/method is called with an invalid
// argument(s).
// ===========================================================================
EInvalidArgument = class ( MtxException )
end; // EInvalidArgument = class ( MtxException )
// ===========================================================================
// 2010-07-07 /gsv/: SWAE 2010-169
// Class MtxDCOException
// Exception für Fehler in der DCO-Datei
// ===========================================================================
EDCOException = class ( MtxException )
end; // MtxDCOException = class ( MtxException )
// ===========================================================================
// 2010-07-07 /gsv/: SWAE 2010-169
// Class EDCOInvalidCompNr
// Exception für eine ungültige Komponentennummer eines KOs in der DCO-Datei
// z.B. nicht unterstützte Komp-Nr / Textdarstellung der Komp-Nr unbekannt
// ===========================================================================
EDCOInvalidCompNr = class ( EDCOException )
end; // type EDCOInvalidCompNr = class ( EDCOException )
// ===========================================================================
// 2010-07-07 /gsv/: SWAE 2010-169
// Class EDCOInvalidCONr
// Exception für eine ungültige KO-Nummer in der DCO-Datei
// z.B. Fehler bei der Konvertierung der KO-Nummer String --> Zahl
// ===========================================================================
EDCOInvalidCONr = class ( EDCOException )
end; // type EDCOInvalidCONr = class ( EDCOException )
// ===========================================================================
// 2010-07-07 /gsv/: SWAE 2010-169
// Class EDCOAbortUser
// Diese Exception wird ausgelöst, fall der DCO-Download durch den
// Benutzer abgebrochen wird.
// ===========================================================================
EDCOAbortUser = class ( EDCOException )
end; // type EDCOAbortUser = class ( EDCOException )
// ===========================================================================
// E V E N T D E C L A R A T I O N S
// ===========================================================================
// ===========================================================================
// Data type TMaskedTableEvent
// This is the data type used by the class TMaskedTable for some of the events,
// the class generates.
// Parameters: sender - the table object, generated the event
// entry - the table entry, currently participated
// in the corresponding operation, as the event was fired.
// ===========================================================================
TMaskedTableEvent = procedure ( Sender : TObject; entry : TMaskedTableEntry ) of object;
// ===========================================================================
// Data type TItemChangedEvent
// Used for OnItemChanged events generated by RadioGroups and ComboBoxes
// (in the following called just "GUI component").
// The OnItemChanged event is generated, whenever the item index of the
// GUI component is changed by the user or in the source code.
// When using a GUI component with an initialized TMaskedTable object,
// the GUI component automatically sets the corresponding item index.
// With this event the software developer has still the possibility to do any
// further actions, whenever the item index of the GUI component changes.
// For example further GUI components may be enabled/disabled or shown/hidden.
// The information about the last and new selections is passed as arguments,
// when the event is generated, so that the SW developer has just to evaluate the
// passed arguments, in order to determine any further actions.
//
// Parameters: sender - The GUI component (RadioGroup, Combobox), generated the event
// oldItemIndex - The index of the last selected item in the GUI component
// newItemIndex - The index of the new/currently selected item in the GUI component
// oldEntry - The table entry of the last selection. This parameter may be nil,
// if the last selection was invalid!
// newEntry - The table entry of the new/current selection.
// This parameter may be nil, if the new/current selection is invalid!
// ===========================================================================
TItemChangedEvent = procedure ( Sender : TObject; oldItemIndex, newItemIndex : integer;
oldEntry, newEntry : TMaskedTableEntry ) of object;
// ===========================================================================
// E N U M D E C L A R A T I O N S
// ===========================================================================
// ===========================================================================
// Aufzählungstyp: TDataType
// Definition für Datentypen eines Objektes (KO, CAN-Objekt, etc.),
// die z.B. in externen Dateien hinterlegt sind.
// Dieser Datentyp wird benutzt, um den in der Datei hinterlegten Datentyp
// intern darzustellen. (s. z.B. Einlesen der EDS-Datei im PDO-Editor)
// ===========================================================================
TDataType = (
dtINT8, // signed 8-Bit
dtUINT8, // unsigned 8-Bit
dtINT16, // signed 16-Bit
dtUINT16, // unsigned 32-Bit
dtINT32, // signed 32-Bit
dtUINT32 // unsigned 32-Bit
); // TDataType
// ===========================================================================
// Aufzählungstyp: TAccessType
// Definiert die Zugriffsart auf ein KO, CAN-Objekt, etc.
// Dieser Datentyp wird benutzt, um z.B. die in der Datei hinterlegten Zugriffsart
// intern darzustellen. (s. z.B. Einlesen der EDS-Datei im PDO-Editor)
// ===========================================================================
TAccessType = (
atNoReadWrite, // kein Zugriff
atReadOnly, // nur Lesezugriff
atWriteOnly, // nur Schreibzugriff
atReadWrite // Lese- und Schreibzugriff
); // TAccessType
// ===========================================================================
// R E C O R D D E C L A R A T I O N S
// ===========================================================================
// ===========================================================================
// Record TMaskedTableMask
// A record describing the mask for the class TMaskedTable.
// ===========================================================================
TMaskedTableMask = record
s_alias : string; // symbolic identifier (alias) of the mask
lw_mask : longword; // the value of the mask
end; // type TMaskedTableMask = record
// ===========================================================================
// Record: TLimitInfo
// Dieser Rekord bildet die Grenzen eines Parameters ab.
// ===========================================================================
TIntLimitInfo = record
i64_min : Int64; // untere Grenze des Parameters
i64_max : Int64; // obere Grenze des Parameters
end; // TIntLimitInfo = record
// ===========================================================================
// I N T E R F A C E D E C L A R A T I O N S
// ===========================================================================
// ===========================================================================
// Klasse: TMtxCloneableObject
// Von allen Klassen zu implementieren, die zentral geklont werden können sollen,
// z.B. als UserData in TMaskedTableObject, d.h. wenn der eigentliche Datentyp
// nicht wirklich bekannt ist, sondern die Instanz als TObject da ist.
// ===========================================================================
TMtxCloneableObject = class ( TObject )
function Clone() : TMtxCloneableObject; virtual; abstract;
end;
// ===========================================================================
// C L A S S D E C L A R A T I O N S
// ===========================================================================
// Forward declarations
TMtxCOComponentControlCOReadWrite = class;
TMtxCOComponentSingleCOReadOnly = class;
TMtxExtCOAssociatedComponentList = class;
TMtxCOComponentSingleCOReadWrite = class;
// ===========================================================================
// Class TBoolean
// A class representating the simple data type "boolean".
// This class is used to store boolean user data in classes such as
// TMaskedTableEntry.
// ===========================================================================
TBoolean = class ( TMtxCloneableObject )
protected
b_value : boolean;
public
property Value : boolean read b_value write b_value;
constructor create(); overload; virtual;
constructor create ( b_val : boolean ); overload; virtual;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // TBoolean = class
// ===========================================================================
// Class TDouble
// A class representating the simple data type "double".
// This class is used to store double user data in classes such as
// TMaskedTableEntry.
// ===========================================================================
TDouble = class ( TMtxCloneableObject )
protected
d_value : double;
public
property Value : double read d_value write d_value;
constructor create(); overload; virtual;
constructor create ( d_val : double ); overload; virtual;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // TDouble = class
// ===========================================================================
// Class TAcknowledgedDouble
// A data container consisting of a double and a boolean value.
// The boolean value defines, whether the double value is valid or not.
// ===========================================================================
TAcknowledgedDouble = class ( TDouble )
private
b_value_valid : boolean;
public
property isValid : boolean read b_value_valid write b_value_valid;
constructor create(); override;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // TAcknowledgedDouble = class
PAcknowledgedDouble = ^TAcknowledgedDouble;
// ===========================================================================
// Class TInteger
// A class representating the simple data type "Int64".
// This class is used to store integer user data in classes such as
// TMaskedTableEntry.
// ===========================================================================
TInteger = class ( TMtxCloneableObject )
protected
li_value : longint;
public
property Value : longint read li_value write li_value;
constructor Create (); overload; virtual;
constructor Create ( i : longint ); overload; virtual;
procedure copyFrom ( src : TInteger );
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // TInteger = class
// ===========================================================================
// Class TInt64
// A class representating the simple data type "Int64".
// This class is used to store integer user data in classes such as
// TMaskedTableEntry.
// ===========================================================================
TInt64 = class ( TMtxCloneableObject )
protected
i64_value : Int64;
public
property Value : int64 read i64_value write i64_value;
constructor create(); overload; virtual;
constructor create ( i64 : int64 ); overload; virtual;
procedure copyFrom ( src : TInt64 );
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // TInt64 = class
// ===========================================================================
// Class TAcknowledgedInt64
// A data container consisting of an int64 and a boolean value.
// The boolean value defines, whether the int64 value is valid or not.
// ===========================================================================
TAcknowledgedInt64 = class ( TInt64 )
private
b_value_valid : boolean;
public
property isValid : boolean read b_value_valid write b_value_valid;
constructor create(); override;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // TAcknowledgedInt64 = class
// ===========================================================================
// Class: TBitListEntry
// This class represents an entry of a TBitList.
// ===========================================================================
TBitListEntry = class ( TMtxCloneableObject )
private
lw_bit : longword; // Bit value, e.g. 0x80000000 = Bit 31, 0x00000001 = Bit 0
str_alias : string; // An unique alias for the list, containing this bit entry.
// Alias = abstraction of the underlying bit number.
str_text : string; // Description: Meaning of the bit
b_inv_logic : boolean; // Flag: The bit has inverted logic?
i64_user_data : int64; // Platzhalter für benutzerdefinierte Daten
public
property Alias : string read str_alias write str_alias;
property Bit : longword read lw_bit write lw_bit;
property Text : string read str_text write str_text;
property InvLogic : boolean read b_inv_logic write b_inv_logic;
property UserData : int64 read i64_user_data write i64_user_data;
constructor create(); overload;
constructor create ( s_alias : string; bit : longword; s_text : string;
inv_logic : boolean = C_DEF_BIT_INV_LOGIC ); overload;
destructor Destroy(); override;
function equals ( e : TBitListEntry ) : boolean; {$IFDEF DELPHI_XE_UP} reintroduce; {$ENDIF}
procedure copyFrom ( entry : TBitListEntry );
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // TBitListEntry = class
// ===========================================================================
// Class: TBitList
// Implementation of a list, containing bit information.
// This list can be used for storing the bit meaning of a statusword or
// controlword.
// ===========================================================================
TBitList = class ( TMtxCloneableObject )
private
entries : TList;
function indexOf ( entry : TBitListEntry ) : integer;
function getCount() : integer;
public
property Count : integer read getCount;
constructor create();
destructor Destroy(); override;
procedure clear();
procedure add ( entry : TBitListEntry ); overload;
procedure add ( alias : string; bit : longword; text : string;
inv_logic : boolean = C_DEF_BIT_INV_LOGIC ); overload;
procedure delete ( entry : TBitListEntry );
function getEntry ( inx : integer ) : TBitListEntry;
function getByAlias ( alias : string ) : TBitListEntry;
function getByBit ( bit : longword ) : TBitListEntry;
function getByText ( text : string ) : TBitListEntry;
function isEmpty() : boolean;
function contains ( entry : TBitListEntry ) : boolean;
procedure copyFrom ( list : TBitList );
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // TBitList = class
// ===========================================================================
// Class: TDoubleList
// Implementation of a list, which contains only double values.
// ===========================================================================
TDoubleList = class ( TMtxCloneableObject )
private
list_values : TList; // the internal list containing the values
protected
// Number of elements in the list
function getCount() : integer;
public
// Number of elements in the list
property Count : integer read getCount;
constructor create();
destructor Destroy(); override;
// Copies the elements of list to the calling object.
procedure copyFrom ( list : TDoubleList );
// Adds a new value to the list
procedure add ( value : double ); overload;
// Adds a new value to the list at the specified index
procedure add ( index : integer; value : double ); overload;
// Raturns the value at the specified index
function get ( index : integer ) : double;
// Updates the entry at the specified index
procedure update ( index : integer; value : double );
// Clears the contents of the list
procedure clear();
// Tests whether the list is empty or not.
function isEmpty() : boolean;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // type TDoubleList = class
// ===========================================================================
// Class: TAcknowledgedDoubleList
// Implementation of a list, which contains only variables of type TAcknowledgedDouble.
// ===========================================================================
TAcknowledgedDoubleList = class ( TMtxCloneableObject )
private
list_values : TList; // the internal list containing the values
protected
// Number of elements in the list
function getCount() : integer;
public
// Number of elements in the list
property Count : integer read getCount;
constructor create();
destructor Destroy(); override;
// Copies the elements of list to the calling object.
procedure copyFrom ( list : TAcknowledgedDoubleList );
// Adds a new value to the list
procedure add ( value : double; b_valid : boolean ); overload;
// Adds a new value to the list
procedure add ( value : TAcknowledgedDouble ); overload;
// Adds a new value to the list at the specified index
procedure add ( index : integer; value : TAcknowledgedDouble ); overload;
// Returns the value at the specified index
function get ( index : integer ) : TAcknowledgedDouble;
// Updates the entry at the specified index
procedure update ( index : integer; entry : TAcknowledgedDouble ); overload;
// Updates the double value of the entry at the specified index
procedure update ( index : integer; d_value : double ); overload;
// Updates the boolean value of the entry at the specified index
procedure update ( index : integer; b_valid : boolean ); overload;
// Clears the contents of the list
procedure clear();
// Tests whether the list is empty or not.
function isEmpty() : boolean;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // type TAcknowledgedDoubleList = class
// ===========================================================================
// Class: TByteList
// Implementation of a list, which contains only byte values.
// ===========================================================================
TByteList = class ( TMtxCloneableObject )
private
list_values : TList; // the internal list containing the values
protected
// Number of elements in the list
function getCount() : integer;
public
// Number of elements in the list
property Count : integer read getCount;
constructor create();
destructor Destroy(); override;
// Copies the elements of list to the calling object.
procedure copyFrom ( list : TByteList );
// Adds a new value to the list
procedure add ( value : byte ); overload;
// Adds a new value to the list at the specified index
procedure add ( index : integer; value : byte ); overload;
// Raturns the value at the specified index
function get ( index : integer ) : byte;
// Updates the entry at the specified index
procedure update ( index : integer; value : byte );
// Clears the contents of the list
procedure clear();
// Tests whether the list is empty or not.
function isEmpty() : boolean;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // type TByteList = class
// ===========================================================================
// Class: TInt64List
// Implementation of a list, which contains only int64 values.
// ===========================================================================
TInt64List = class ( TMtxCloneableObject )
private
list_values : TList; // the internal list containing the values
protected
// Number of elements in the list
function getCount() : integer;
public
// Number of elements in the list
property Count : integer read getCount;
constructor create();
destructor Destroy(); override;
// Copies the elements of list to the calling object.
procedure copyFrom ( list : TInt64List );
// Adds a new value to the list
procedure add ( value : int64 ); overload;
// Adds a new value to the list at the specified index
procedure add ( index : integer; value : int64 ); overload;
// Raturns the value at the specified index
function get ( index : integer ) : int64;
// Updates the entry at the specified index
procedure update ( index : integer; value : int64 );
// Clears the contents of the list
procedure clear();
// Tests whether the list is empty or not.
function isEmpty() : boolean;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // type TInt64List = class
// ===========================================================================
// Class: TLongwordList
// Implementation of a list, which contains only longword values.
// ===========================================================================
TLongwordList = class ( TMtxCloneableObject )
private
list_values : TList; // the internal list containing the values
FAllowDuplicates : boolean; // 2009-10-05 /gsv/: Duplikate zulassen?
protected
// Number of elements in the list
function getCount() : integer;
public
// Number of elements in the list
property Count : integer read getCount;
// 2009-10-05 /gsv/: Duplikate zulassen?
property AllowDuplicates : boolean read FAllowDuplicates write FAllowDuplicates;
constructor create();
destructor Destroy(); override;
// Copies the elements of list to the calling object.
procedure copyFrom ( list : TLongwordList );
// Adds a new value to the list
procedure add ( value : longword ); overload;
// Adds a new value to the list at the specified index
procedure add ( index : integer; value : longword ); overload;
// Raturns the value at the specified index
function get ( index : integer ) : longword;
// Updates the entry at the specified index
procedure update ( index : integer; value : longword );
// Clears the contents of the list
procedure clear();
// 2009-10-05 /gsv/: Prüft, ob ein Longword-Wert in der Liste bereits enthalten ist.
function contains ( lw : longword ) : boolean;
// Tests whether the list is empty or not.
function isEmpty() : boolean;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // type TLongwordList = class
// ===========================================================================
// Class TMaskedTableEntry
// An entry for the class TMaskedTable
// ===========================================================================
TMaskedTableEntry = class ( TMtxCloneableObject )
private
s_alias : string; // symbolic identifier (alias) of the bitfield option
lw_bitfield : longword; // the value of the bitfield option
s_text : string; // the text to be displayed in the RadioGroup/Combobox
i_text_id : integer; // 2015-12-02 /gsv/: TextID als Platzhalter für den sprachabhängigen Text
objUserData : TObject; // "pointer" to an user defined data (optional, nil if not set!)
// 2009-10-05 /gsv/: Manchmal soll bei unterschiedlichen
// KO-Werten der gleiche Text angezeigt / die gleiche
// Option ausgewählt werden. Dabei soll der Eintrag / Text
// in einer RadioGroup/Combobox nur einmal vorhanden sein.
// Deshalb wird eine optionale Liste mit alternativen Bitfeldern
// implementiert, die nur für die Richtung Servo --> Para-SW benutzt wird.
// Beim Setzen des KO-Wertes wird die Property Bitfield verwendet.
list_alt_bitfields : TLongwordList;
public
constructor create();
destructor Destroy(); override;
procedure copyFrom ( entry : TMaskedTableEntry );
function equals ( e : TMaskedTableEntry ) : boolean; {$IFDEF DELPHI_XE_UP} reintroduce; {$ENDIF}
// 2009-10-05 /gsv/: Alternative Bitfeld-Definitionen zurückgeben
// Existieren alternative Bitfeld-Definitionen?
function hasAltBitfields() : boolean;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
published
property Alias : string read s_alias write s_alias;
property Bitfield : longword read lw_bitfield write lw_bitfield;
property Text : string read s_text write s_text;
property UserData : TObject read objUserData write objUserData;
// 2009-10-05 /gsv/: Liste mit den alternativen Bitfeld-Werten
property AltBitfields : TLongwordList read list_alt_bitfields;
// 2015-12-02 /gsv/: TextID als Platzhalter für den sprachabhängigen Text
property TextID : integer read i_text_id write i_text_id default C_TEXT_ID_DEFAULT_VALUE;
end; // type TMaskedTableEntry = record
// ===========================================================================
// Class TMaskedTable
// A class implementing a table with entries of data type TMaskedTableEntry.
// This class is used by radio groups and combo boxes and provides a
// translation table bitfield <-> displayed text (==> ItemIndex).
// Such a table is always associated with one mask!
// ===========================================================================
TMaskedTable = class ( TMtxCloneableObject )
protected
mask : TMaskedTableMask;
entries : TObjectList;
FOnAdd : TMaskedTableEvent;
FOnClear : TNotifyEvent;
FOnDelete : TMaskedTableEvent;
FCapitalizeFirstLetter : boolean; // 2016-09-28 /gsv/: Flag: ersten Buchstaben immer in Großbuchstaben umwandeln?
function indexOf ( entry : TMaskedTableEntry ) : integer;
function getCount() : integer;
public
property Count : integer read getCount;
// 2016-09-28 /gsv/: Flag: ersten Buchstaben immer in Großbuchstaben umwandeln?
// Diese Property hat keine Auswirkung auf bereits vorhandene Einträge!
property CapitalizeFirstLetter : boolean read FCapitalizeFirstLetter write FCapitalizeFirstLetter;
constructor create();
destructor Destroy(); override;
procedure clear();
function add ( entry : TMaskedTableEntry ) : boolean; overload;
function add ( alias : string; bitfield : longword; text : string ) : boolean; overload;
function add ( alias : string; bitfield : longword; text : string; userData : TMtxCloneableObject ) : boolean; overload;
function add ( alias : string; bitfield : longword; text : string; userData : TObject ) : boolean; overload;
// 2015-12-02 /gsv/: Neue add-Funktionen mit TextID (Platzhalter für den sprachabhängigen Text)
function add ( alias : string; bitfield : longword; text : string; text_id : integer ) : boolean; overload;
function add ( alias : string; bitfield : longword; text : string; text_id : integer; userData : TObject ) : boolean; overload;
procedure delete ( entry : TMaskedTableEntry );
function getEntry ( inx : integer ) : TMaskedTableEntry;
function getByAlias ( alias : string ) : TMaskedTableEntry;
function getByBitfield ( bitfield : longword ) : TMaskedTableEntry; overload;
function getIndexByBitfield ( bitfield : longword ) : integer;
function getByBitfield ( bitfield : longword; var index : integer ) : boolean; overload;
function getByBitfield ( bitfield : longword; var index : integer; var entry : TMaskedTableEntry ) : boolean; overload;
function getByText ( text : string ) : TMaskedTableEntry;
function getMask() : TMaskedTableMask;
procedure setMask ( new_mask : TMaskedTableMask ); overload;
procedure setMask ( alias : string; value : longword ); overload;
function isEmpty() : boolean;
function contains ( entry : TMaskedTableEntry ) : boolean;
procedure copyFrom ( table : TMaskedTable );
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
published
property OnAdd : TMaskedTableEvent read FOnAdd write FOnAdd;
property OnClear : TNotifyEvent read FOnClear write FOnClear;
property OnDelete : TMaskedTableEvent read FOnDelete write FOnDelete;
end; // TMaskedTable = class
// ===========================================================================
// Class: TMaskedTableList
// A list containing TMaskedTable-Objects
// ===========================================================================
TMaskedTableList = class ( TMtxCloneableObject )
protected
entries : TObjectList;
function getCount() : integer;
public
property Count : integer read getCount;
constructor create();
destructor Destroy(); override;
procedure clear();
procedure add ( table : TMaskedTable );
function getTable ( inx : integer ) : TMaskedTable;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // TMaskedTableList = class
// ===========================================================================
// class TFraction
// Implementation of a fraction numerator/divisor.
// ===========================================================================
TFraction = class ( TMtxCloneableObject )
private
i64_numerator : int64;
i64_divisor : int64;
d_decimal_fraction : double;
protected
procedure setNumerator ( new_numerator : int64 );
procedure setDivisor ( new_divisor : int64 );
procedure refreshDecimalFraction();
public
property Numerator : int64 read i64_numerator write setNumerator;
property Divisor : int64 read i64_divisor write setDivisor;
property DecimalFraction : double read d_decimal_fraction;
constructor create();
function equals ( fraction : TFraction ) : boolean; {$IFDEF DELPHI_XE_UP} reintroduce; {$ENDIF}
// 2009-11-21 /gsv/: Größten gemeinsamen Teiler ermitteln
function getGCD() : int64;
// 2009-11-21 /gsv/: Bruch kürzen
procedure shorten();
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // TFraction = class
// ===========================================================================
// Klasse: TDataCmdCO / DatenCluster Oszilloskop
// Datencontainer für das Auslesen der Oszi-Daten
// Ein Datencluster nimmt einen ROD-Befehl auf
// ===========================================================================
TOszCluster = class ( TMtxCloneableObject )
protected
iChannel : longword; // Kanal
iCluster : longword; // Cluster / Paketnummer
str_answer : string; // Antwortdaten / Messwerte
public
// Kanal
property Channel : longword read iChannel write iChannel;
// Cluster / Paketnummer
property Cluster : longword read iCluster write iCluster;
// Antwortdaten / Messwerte
property Answer : string read str_answer write str_answer;
constructor create();
// Kopierfunktion: Kopiert osz in self
procedure copyFrom ( const osz : TOszCluster );
// Rückgabe eines Messwertes
function getLong ( i : integer ) : longword;
// 2014-08-21 /gsv/: Kopie des Objektes erstellen
function Clone() : TMtxCloneableObject; override;
end; // TOszCluster = class
TMtxGUICODataBase = class ( TPersistent )
protected
i64Value : int64; // KO-Wert (OR, High- + Low-Anteil)
i64ValueBackup : int64; // Backup-Wert des KOs (1. ausgelesener Wert)
i64ValueOI : int64; // OI-Wert des KOs, falls das KO OI-Wert hat (High- + Low-Anteil)
bHasOIValue : boolean; // Flag: KO hat OI-Wert?
bReadCyclic : boolean; // Flag: KO auch in prog_update zyklisch auslesen?
bReadORValue : boolean; // Flag: OR-Wert auslesen?
bReadOIValue : boolean; // Flag: OI-Wert auslesen? (falls vorhanden)
bRestoreOldValue : boolean; // Flag: ursprünglichen KO-Wert bei Abbruch restaurieren?
public
constructor Create(); virtual;
procedure copyFrom ( obj : TMtxGUICODataBase ); virtual;
published
// KO-Wert (OR, High- + Low-Anteil)
property Value : int64 read i64Value write i64Value default 0;
// Backup-Wert des KOs (1. ausgelesener Wert)
property ValueBackup : int64 read i64ValueBackup write i64ValueBackup default 0;
// OI-Wert des KOs, falls das KO OI-Wert hat (High- + Low-Anteil)
property ValueOI : int64 read i64ValueOI write i64ValueOI default 0;
// Flag: KO hat OI-Wert?
property HasOIValue : boolean read bHasOIValue write bHasOIValue default false;
// Flag: KO auch in prog_update zyklisch auslesen?
property ReadCyclic : boolean read bReadCyclic write bReadCyclic default false;
// Flag: OR-Wert auslesen?
property ReadORValue : boolean read bReadORValue write bReadORValue default true;
// Flag: OI-Wert auslesen? (falls vorhanden)
property ReadOIValue : boolean read bReadOIValue write bReadOIValue default false;
// Flag: ursprünglichen KO-Wert bei Abbruch restaurieren?
property RestoreOldValue : boolean read bRestoreOldValue write bRestoreOldValue default true;
end;
TMtxGUICODataSingleCO = class ( TMtxGUICODataBase )
protected
sName : string; // Name des KOs
public
constructor Create(); override;
procedure copyFrom ( obj : TMtxGUICODataBase ); override;
published
// Name des KOs
property Name : string read sName write sName;
end;
TMtxGUICODataInt64 = class ( TMtxGUICODataBase )
protected
sNameHigh : string; // Name des KOs für den High-Anteil
sNameLow : string; // Name des KOs für den Low-Anteil
public
constructor Create(); override;
procedure copyFrom ( obj : TMtxGUICODataBase ); override;
published
// Name des KOs für den High-Anteil
property NameHigh : string read sNameHigh write sNameHigh;
// Name des KOs für den Low-Anteil
property NameLow : string read sNameLow write sNameLow;
end;
// ===========================================================================
// Klasse: TMtxGUICODataSimpleMultiCO
// Einfaches Multi-KO
// ===========================================================================
TMtxGUICODataSimpleMultiCO = class ( TPersistent )
private
FPointerCOName : string;
FPointerCOMin : int64;
FPointerCOMax : int64;
FPointerCOVal : int64;
FDataCOInfo : TMtxGUICODataSingleCO;
FDataCOValues : TInt64List;
FDataCOValuesBackup : TInt64List;
public
constructor Create(); virtual;
procedure copyFrom ( obj : TMtxGUICODataSimpleMultiCO );
property PointerCOMin : int64 read FPointerCOMin write FPointerCOMin default 0;
property PointerCOMax : int64 read FPointerCOMax write FPointerCOMax default 0;
property PointerCOVal : int64 read FPointerCOVal write FPointerCOVal default 0;
property DataCOValues : TInt64List read FDataCOValues write FDataCOValues;
property DataCOValuesBackup : TInt64List read FDataCOValuesBackup write FDataCOValuesBackup;
published
// Name des Zeiger-KOs
property PointerCOName : string read FPointerCOName write FPointerCOName;
// Info über das Daten-KO (Name, OR-/OI-Wert lesen, etc.)
property DataCOInfo : TMtxGUICODataSingleCO read FDataCOInfo write FDataCOInfo;
end;
// ===========================================================================
// Klasse: TMtxThread
// Basisklasse für die von Thread abgeleiteten Klassen.
// Die Funktionen Suspend() und Resume() sind veraltet. Diese Basisklasse
// bietet alternative Funktionen.
// ===========================================================================
TMtxThread = class ( TThread )
protected
FSuspendEvent : TEvent;
FCreateSuspendedMtx : boolean; // Flag: Thread als Suspended erzeugt?
public
{$IFDEF DELPHI_XE_UP}
constructor Create(); overload;
{$ENDIF}
constructor Create ( CreateSuspended: Boolean ); {$IFDEF DELPHI_XE_UP} overload; {$ENDIF}
destructor Destroy(); override;
{$IFDEF DELPHI_XE_UP}
procedure TerminatedSet(); override;
{$ENDIF}
procedure SuspendWork();
procedure ResumeWork();
procedure CheckHandleSuspended();
function isSuspended() : boolean;
end;
// ===========================================================================
// 2015-11-27 /gsv/:
// Interface: IMtxGUIComponent
// Basis-Interface, über welches eine GUI-Klasse als Metronix GUI-Klasse
// gekennzeichnet werden kann.
// ===========================================================================
IMtxGUIComponent = interface
['{05DB41AF-A94F-4402-8BA1-DB2BB5FB76A2}']
end;
IMtxGUIComponentWithHint = interface (IMtxGUIComponent)
['{FD0D86BB-7D27-43EF-BDE3-4D06911CBD08}']
procedure CancelHint();
end;
IMtxGUIComponentMultiLanguage = interface ( IMtxGUIComponent )
['{F8EE35A8-F075-4A2D-82AB-9DF464C36227}']
// Getter/Setter der Property TextID
procedure setTextID ( id : integer );
function getTextID () : integer;
// Getter/Setter der Property TextRemoveChars
procedure setTextRemoveChars ( s : string );
function getTextRemoveChars() : string;
// Funktion, um den Text/die Caption zu aktualisieren
// ws: sprachabhängiger Text
procedure updateText ( ws : string );
// Text-ID für die Sprachunterstützung. Über die Text-ID wird in der Klasse
// TUpdateFormWithAutomation der Text / die Caption aktualisiert.
property TextID : integer read getTextID write setTextID;
// Zeichen, die aus dem Text (s. TextID) entfernt werden.
// Die Zeichen werden durch die Klasse TUpdateFormWithAutomation entfernt.
property TextRemoveChars : string read getTextRemoveChars write setTextRemoveChars;
end;
// ===========================================================================
// 2015-11-27 /gsv/:
// Interface: IMtxUpdatedGUIComponent
// Dieses Interface definiert die Schnittstelle für eine Metronix GUI-Komponente,
// die mit dem Regler interagiert und minimale Funktionen / Eigenschaften
// für die Darstellung der Werte unterstützt.
// ===========================================================================
IMtxUpdatedGUIComponent = interface ( IMtxGUIComponent )
['{CC2A0A27-69DD-416E-8926-81CA761B6F7E}']
// Getter / Setter für die Enabled-Eigenschaft
function GetEnabled() : boolean;
procedure SetEnabled ( b_on : boolean );
// Komponente zurücksetzen (bei win_reset()).
procedure reset();
// Berechnung Servo --> GUI (==> COValue anzeigen)
procedure calcValueFromServo();
// Komponente aktiv / inaktiv
property Enabled : boolean read GetEnabled write SetEnabled;
end;
// ===========================================================================
// 2015-11-27 /gsv/:
// Interface: IMtxUpdatedGUIComponentReadOnly
// Dieses Interface definiert die Schnittstelle für eine Metronix GUI-Komponente,
// die mit dem Regler interagiert und readonly ist.
// ===========================================================================
IMtxUpdatedGUIComponentReadOnly = interface ( IMtxUpdatedGUIComponent )
['{5A6E2C6E-D2DC-4204-B0A3-6963EF6EC86B}']
end; // IMtxUpdatedGUIComponentReadOnly = interface
// ===========================================================================
// 2015-11-27 /gsv/:
// Interface: IMtxUpdatedGUIComponent
// Dieses Interface definiert die Schnittstelle für eine Metronix GUI-Komponente,
// die mit dem Regler interagiert und die is_changed()-Eigenschaft unterstützt.
// ===========================================================================
IMtxUpdatedGUIComponentReadWrite = interface ( IMtxUpdatedGUIComponent )
['{15CF819A-C817-4D20-B774-B886E66FA4A2}']
// Getter/Setter für die Property is_changed
function getIsChanged() : boolean;
procedure setIsChanged ( b : boolean );
// Berechnung GUI --> Servo (==> COValue berechnen/aktualisieren)
procedure calcValueToServo();
// is_changed-Property: Sollte nur bei Änderung durch den Benutzer gesetzt werden.
property is_changed : boolean read getIsChanged write setIsChanged;
end; // IMtxUpdatedGUIComponentReadWrite = interface
// ===========================================================================
// 2015-11-27 /gsv/:
// Interface: IMtxUpdatedGUIComponentWithLimitsAndPhysUnit
// Metronix GUI-Komponente, die zusätztlich die Eingabegrenzen entsprechend
// den KO-Grenzen setzt und physikalische Einheit unterstützt.
// ===========================================================================
IMtxUpdatedGUIComponentWithLimitsAndPhysUnit = interface (IMtxUpdatedGUIComponent)
['{CEECE5F3-DA7D-40A6-BC96-CC175182B90A}']
// Grenzen in Basiseinheiten setzen
procedure setLimitsInBaseUnits ( min, max : int64 );
// Schrittweiten zur Änderung des Wertes in Benutzereinheiten setzen (s. auch TInbox)
procedure setChangeStepsInUserUnits ( d_small, d_large : double );
// Getter/Setter für die Property prop_factor (Umrechnungsfaktor)
procedure setPropFactor ( fac : extended );
function getPropFactor() : extended;
// Getter/Setter für die Property PostString (Physikalische Einheit)
procedure setPostString ( ws : string );
function getPostString() : string;
// Getter/Setter für die Property Decimals (Anzahl Nachkommastellen)
procedure setDecimals ( i : integer );
function getDecimals() : integer;
// Anzahl der anzuzeigenden signifikanten Nachkommastellen (bei Wert, der nach der Rundung 0,00.. ergibt)
procedure setDecimals_signif ( i : integer );
function getDecimals_signif() : integer;
// Übersetzt den Text bei einem Wert außerhalb des Bereichs
procedure set_sprach_err ( i : integer );
// Umrechnungsfaktor (Basiseinheiten <-> Benutzereinheiten)
property prop_factor : extended read getPropFactor write setPropFactor;
// Physikalische Einheit (string)
property PostString : string read getPostString write setPostString;
// Anzahl der anzuzeigenden Nachkommastellen
property Decimals : integer read getDecimals write setDecimals;
// Anzahl der anzuzeigenden signifikanten Nachkommastellen (bei Wert, der nach der Rundung 0,00.. ergibt)
property Decimals_signif : integer read getDecimals_signif write setDecimals_signif;
end;
// ===========================================================================
// 2015-11-27 /gsv/:
// Interface: IMtxGUIComponentWithCO
// Allgemeines Interface, um erkennen zu können, dass die GUI-Komponente eines
// der nachfolgenden Interfaces mit Angabe des auszulesenden bzw. zu beschreibenden
// KOs implementiert.
// In der Klasse TUpdateFormWithAutomation werden diese KOs automatisch ermittelt,
// so dass Standard-Aktionen wie "KO auslesen", "KO anzeigen" und
// "durch Benutzer modifizierten Wert schreiben" automatisiert werden können.
// ===========================================================================
IMtxGUIComponentWithCO = interface ( IMtxUpdatedGUIComponent )
['{848BB55C-46D3-4180-BB6C-E593712FB82B}']
// Getter/Setter für die Property WriteAccessRunning
function getWriteAccessRunning() : boolean;
procedure setWriteAccessRunning ( b : boolean );
// Flag: KO-Schreibzugriff aktiv?
property WriteAccessRunning : boolean read getWriteAccessRunning write setWriteAccessRunning;
end;
// ===========================================================================
// 2015-11-27 /gsv/:
// Interface: IMtxGUIComponentWithSingleCO
// Schnittstellenbeschreibung für eine GUI-Komponente, die ein einziges
// normales KO (also kein Multi-KO) ausliest bzw. beschreibt.
// ===========================================================================
IMtxGUIComponentWithSingleCO = interface ( IMtxGUIComponentWithCO )
['{84E1FB69-B349-4CDE-99E3-57565FCF8CE8}']
// Getter/Setter für die Property COData
function getCOData() : TMtxGUICODataSingleCO;
procedure setCOData ( obj : TMtxGUICODataSingleCO );
// KO-Daten (Name, Wert, etc.)
property COData : TMtxGUICODataSingleCO read getCOData write setCOData;
end; // IMtxGUIComponentWithSingleCO = interface ( IMtxGUIComponentWithCO )
// ===========================================================================
// 2015-11-27 /gsv/:
// Interface: IMtxGUIComponentWithControlCO
// Schnittstellenbeschreibung für eine GUI-Komponente, die ein einziges
// Control-KO ausliest bzw. beschreibt.
// ===========================================================================
IMtxGUIComponentWithControlCO = interface ( IMtxGUIComponentWithSingleCO )
['{637D0A82-7076-47E8-9FA5-49D38096BFA9}']
end;
// ===========================================================================
// 2015-11-27 /gsv/:
// Interface: IMtxGUIComponentWithCO64Bit
// Schnittstellenbeschreibung für eine GUI-Komponente, die zwei KOs
// (insgesamt ein 64-Bit Wert, 1. KO High-Anteil, 2. KO Low-Anteil)
// ausliest bzw. beschreibt. Typischer Anwendungsfall: Positionsdaten 64-Bit
// ===========================================================================
IMtxGUIComponentWithCO64Bit = interface ( IMtxGUIComponentWithCO )
['{8936A264-91A0-41BE-9776-DE790FB169F9}']
// Getter/Setter für die Property COData
function getCOData() : TMtxGUICODataInt64;
procedure setCOData ( obj : TMtxGUICODataInt64 );
// KO-Daten (Name, Wert, etc.)
property COData : TMtxGUICODataInt64 read getCOData write setCOData;
end; // IMtxGUIComponentWithCO64Bit = interface ( IMtxGUIComponentWithCO )
// ===========================================================================
// 2015-11-27 /gsv/:
// Interface: IMtxGUIComponentWithSimpleMultiCO
// Schnittstellenbeschreibung für eine GUI-Komponente, die zwei KOs
// (insgesamt ein 64-Bit Wert, 1. KO High-Anteil, 2. KO Low-Anteil)
// ausliest bzw. beschreibt. Typischer Anwendungsfall: Positionsdaten 64-Bit
// ===========================================================================
IMtxGUIComponentWithSimpleMultiCO = interface ( IMtxGUIComponentWithCO )
['{FF192D41-9921-47AA-90BA-BE474EFFF186}']
// Getter/Setter für die Property COData
function getCOData() : TMtxGUICODataSimpleMultiCO;
procedure setCOData ( obj : TMtxGUICODataSimpleMultiCO );
// KO-Daten (Name, Wert, etc.)
property COData : TMtxGUICODataSimpleMultiCO read getCOData write setCOData;
end; // IMtxGUIComponentWithSimpleMultiCO = interface ( IMtxGUIComponentWithCO )
// ===========================================================================
// 2016-09-27 /gsv/:
// Interface: IMtxGUIComponentWithExternalCO
// Basis-Interface für eine GUI-Komponente, die ein KO ausliest bzw. beschreibt.
// Die GUI-Komponente hat in diesem Fall nur eine Objekt-Referenz auf
// das zu verwendete KO (externes KO, z.B. sinnvoll, wenn in einem Fenster mehrere
// Checkboxen / Comboboxen auf das gleiche KO zugreifen).
// ===========================================================================
IMtxGUIComponentWithExternalCO = interface ( IMtxGUIComponentWithCO )
['{297B92E6-E90E-465F-89AF-CDF6BC4D7582}']
end;
// ===========================================================================
// 2016-09-27 /gsv/:
// Interface: IMtxGUIComponentWithExternalSingleCO
// Basis-Interface für eine GUI-Komponente, die ein KO ausliest bzw. beschreibt.
// Die GUI-Komponente hat in diesem Fall nur eine Objekt-Referenz auf
// das zu verwendete KO (externes KO, z.B. sinnvoll, wenn in einem Fenster mehrere
// Checkboxen / Comboboxen auf das gleiche KO zugreifen).
// ===========================================================================
IMtxGUIComponentWithExternalSingleCOReadOnly = interface ( IMtxGUIComponentWithExternalCO )
['{B2089444-9534-4F77-AA20-210C5DE406E2}']
// Getter/Setter für die Property COData
function getCOData() : TMtxCOComponentSingleCOReadOnly;
procedure setCOData ( obj : TMtxCOComponentSingleCOReadOnly );
// KO-Daten (Name, Wert, etc.)
property COData : TMtxCOComponentSingleCOReadOnly read getCOData write setCOData;
end;
// ===========================================================================
// 2016-09-27 /gsv/:
// Interface: IMtxGUIComponentWithExternalSingleCOReadWrite
// Basis-Interface für eine GUI-Komponente, die ein KO ausliest bzw. beschreibt.
// Die GUI-Komponente hat in diesem Fall nur eine Objekt-Referenz auf
// das zu verwendete KO (externes KO, z.B. sinnvoll, wenn in einem Fenster mehrere
// Checkboxen / Comboboxen auf das gleiche KO zugreifen).
// ===========================================================================
IMtxGUIComponentWithExternalSingleCOReadWrite = interface ( IMtxGUIComponentWithExternalCO )
['{10079DE4-FA2A-4C96-8D5A-CF6C0B007BA6}']
// Getter/Setter für die Property COData
function getCOData() : TMtxCOComponentSingleCOReadWrite;
procedure setCOData ( obj : TMtxCOComponentSingleCOReadWrite );
// KO-Daten (Name, Wert, etc.)
property COData : TMtxCOComponentSingleCOReadWrite read getCOData write setCOData;
end;
// ===========================================================================
// 2016-09-27 /gsv/:
// Interface: IMtxGUIComponentWithExternalControlCO
// Schnittstellenbeschreibung für eine GUI-Komponente, die ein einziges
// Control-KO ausliest bzw. beschreibt.
// Das zu verwendete KO ist extern definiert (hier nur als Referenz).
// ===========================================================================
IMtxGUIComponentWithExternalControlCO = interface ( IMtxGUIComponentWithExternalCO )
['{82D7DFDE-30AF-4448-BB38-36F3A7EE8C24}']
// Getter/Setter für die Property COData
function getCOData() : TMtxCOComponentControlCOReadWrite;
procedure setCOData ( obj : TMtxCOComponentControlCOReadWrite );
// KO-Daten (Name, Wert, etc.)
property COData : TMtxCOComponentControlCOReadWrite read getCOData write setCOData;
end;
// ===========================================================================
// 2016-09-27 /gsv/:
// Interface: IMtxCOComponentWithAssociatedGUIComponents
// Schnittstellenbeschreibung für eine KO-Komponente, der weitere GUI-Komponenten
// zugewiesen sind.
// ===========================================================================
IMtxCOComponentWithAssociatedGUIComponents = interface
['{883C2AF6-0FFA-470F-B9FD-D2D2AA4F7DC7}']
// Getter/Setter für die Property AssociatedComponents
function getAssociatedComponents() : TMtxExtCOAssociatedComponentList;
// Liste mit den Komponenten, die mit diesem KO verlinkt sind.
property AssociatedComponents : TMtxExtCOAssociatedComponentList read getAssociatedComponents;
end;
// ===========================================================================
// Klasse: TMtxCOComponentSingleCOBase
// Basisklasse für eine Metronix-Komponente mit KO-Unterstützung
// Die Unterklasse kann einem Fenster vom Typ TUpdateFormWithAutomation
// hinzugefügt werden. Dadurch kann der automatisierte Mechanismus zum
// Lesen/Schreiben von KOs benutzt werden.
// ===========================================================================
TMtxCOComponentBase = class abstract ( TComponent, IMtxUpdatedGUIComponent,
IMtxGUIComponentWithCO,
IMtxCOComponentWithAssociatedGUIComponents )
protected
FEnabled : boolean;
FWriteAccessRunning : boolean;
FOnReset : TNotifyEvent;
FOnCalcValueFromServo : TNotifyEvent;
FAssociatedComponents : TMtxExtCOAssociatedComponentList; // Liste mit den Komponenten, die mit diesem KO verlinkt sind.
// Getter / Setter für die Enabled-Eigenschaft
function GetEnabled() : boolean;
// Der Aufrufparameter muss wegen TControl "Value" heißen!
procedure SetEnabled ( b_on : boolean );
// Getter/Setter für die Property WriteAccessRunning
function getWriteAccessRunning() : boolean;
procedure setWriteAccessRunning ( b : boolean );
// Getter/Setter für die Property AssociatedComponents
function getAssociatedComponents() : TMtxExtCOAssociatedComponentList;
public
constructor Create ( AOwner : TComponent ); override;
destructor Destroy(); override;
// Berechnung Servo --> GUI (==> COValue anzeigen)
procedure calcValueFromServo();
// Komponente zurücksetzen (bei win_reset()).
procedure reset();
property OnReset : TNotifyEvent read FOnReset write FOnReset;
property OnCalcValueFromServo : TNotifyEvent read FOnCalcValueFromServo write FOnCalcValueFromServo;
// Komponente aktiv / inaktiv
property Enabled : boolean read GetEnabled write SetEnabled;
// Flag: KO-Schreibzugriff aktiv?
property WriteAccessRunning : boolean read getWriteAccessRunning write setWriteAccessRunning;
// Liste mit den Komponenten, die mit diesem KO verlinkt sind.
property AssociatedComponents : TMtxExtCOAssociatedComponentList read getAssociatedComponents;
end;
// ===========================================================================
// Klasse: TMtxCOComponentSingleCOBase
// Basisklasse für ein einfaches KO
// ===========================================================================
TMtxCOComponentSingleCOBase = class abstract ( TMtxCOComponentBase, IMtxUpdatedGUIComponent,
IMtxGUIComponentWithCO,
IMtxGUIComponentWithSingleCO,
IMtxCOComponentWithAssociatedGUIComponents )
protected
FCOData : TMtxGUICODataSingleCO;
// Getter/Setter für die Property COData
function getCOData() : TMtxGUICODataSingleCO;
procedure setCOData ( obj : TMtxGUICODataSingleCO );
public
constructor Create ( AOwner : TComponent ); override;
destructor Destroy(); override;
published
// KO-Daten (Name, Wert, etc.)
property COData : TMtxGUICODataSingleCO read getCOData write setCOData;
end; // TMtxCOComponentSingleCOBase
// ===========================================================================
// Klasse: TMtxCOComponentSingleCOReadOnly
// Klasse für das Lesen eines einfachen readonly KOs
// ===========================================================================
TMtxCOComponentSingleCOReadOnly = class ( TMtxCOComponentSingleCOBase, IMtxUpdatedGUIComponent,
IMtxUpdatedGUIComponentReadOnly,
IMtxGUIComponentWithCO,
IMtxGUIComponentWithSingleCO,
IMtxCOComponentWithAssociatedGUIComponents )
public
constructor Create ( AOwner : TComponent ); override;
end; // TMtxCOComponentSingleCOReadOnly
// ===========================================================================
// Klasse: TMtxCOComponentSingleCOReadWrite
// Klasse für das Lesen/Schreiben eines einfachen KOs
// ===========================================================================
TMtxCOComponentSingleCOReadWrite = class ( TMtxCOComponentSingleCOBase, IMtxUpdatedGUIComponent,
IMtxUpdatedGUIComponentReadWrite,
IMtxGUIComponentWithCO,
IMtxGUIComponentWithSingleCO,
IMtxCOComponentWithAssociatedGUIComponents )
protected
b_is_changed : boolean;
FOnCalcValueToServo : TNotifyEvent;
// Getter / Setter der Property is_changed
function getIsChanged() : boolean;
procedure setIsChanged ( b : boolean );
public
constructor Create ( AOwner : TComponent ); override;
// Berechnung GUI --> Servo (==> COValue berechnen/aktualisieren)
procedure calcValueToServo();
published
// is_changed-Property: Sollte nur bei Änderung durch den Benutzer gesetzt werden.
property is_changed : boolean read getIsChanged write setIsChanged default false;
property OnCalcValueToServo : TNotifyEvent read FOnCalcValueToServo write FOnCalcValueToServo;
end; // TMtxCOComponentSingleCOReadWrite
// ===========================================================================
// Klasse: TMtxCOComponentControlCOBase
// Basisklasse für ein einfaches Control-KO
// ===========================================================================
TMtxCOComponentControlCOBase = class abstract ( TMtxCOComponentBase, IMtxUpdatedGUIComponent,
IMtxGUIComponentWithCO,
IMtxGUIComponentWithControlCO,
IMtxCOComponentWithAssociatedGUIComponents )
protected
FCOData : TMtxGUICODataSingleCO;
// Getter/Setter für die Property COData
function getCOData() : TMtxGUICODataSingleCO;
procedure setCOData ( obj : TMtxGUICODataSingleCO );
public
constructor Create ( AOwner : TComponent ); override;
destructor Destroy(); override;
published
// KO-Daten (Name, Wert, etc.)
property COData : TMtxGUICODataSingleCO read getCOData write setCOData;
end; // TMtxCOComponentControlCOBase
// ===========================================================================
// Klasse: TMtxCOComponentControlCOReadOnly
// Klasse für das Lesen eines einfachen readonly Control-KOs
// ===========================================================================
TMtxCOComponentControlCOReadOnly = class ( TMtxCOComponentControlCOBase, IMtxUpdatedGUIComponent,
IMtxUpdatedGUIComponentReadOnly,
IMtxGUIComponentWithCO,
IMtxGUIComponentWithControlCO,
IMtxCOComponentWithAssociatedGUIComponents )
public
constructor Create ( AOwner : TComponent ); override;
end; // TMtxCOComponentControlCOReadOnly
// ===========================================================================
// Klasse: TMtxCOComponentSingleCOBase
// Klasse für das Lesen/Schreiben eines einfachen KOs
// ===========================================================================
TMtxCOComponentControlCOReadWrite = class ( TMtxCOComponentControlCOBase, IMtxUpdatedGUIComponent,
IMtxUpdatedGUIComponentReadWrite,
IMtxGUIComponentWithCO,
IMtxGUIComponentWithControlCO,
IMtxCOComponentWithAssociatedGUIComponents )
protected
b_is_changed : boolean;
FOnCalcValueToServo : TNotifyEvent;
// Getter / Setter der Property is_changed
function getIsChanged() : boolean;
procedure setIsChanged ( b : boolean );
public
constructor Create ( AOwner : TComponent ); override;
// Berechnung GUI --> Servo (==> COValue berechnen/aktualisieren)
procedure calcValueToServo();
published
// is_changed-Property: Sollte nur bei Änderung durch den Benutzer gesetzt werden.
property is_changed : boolean read getIsChanged write setIsChanged default false;
property OnCalcValueToServo : TNotifyEvent read FOnCalcValueToServo write FOnCalcValueToServo;
end; // TMtxCOComponentControlCOReadWrite
// ===========================================================================
// Klasse: TMtxCOComponentInt64COBase
// Basisklasse für ein INT64-KO (Abbildung zweier UINT32-KOs, High + Low Anteil)
// ===========================================================================
TMtxCOComponentInt64COBase = class abstract ( TMtxCOComponentBase, IMtxUpdatedGUIComponent,
IMtxGUIComponentWithCO,
IMtxGUIComponentWithCO64Bit,
IMtxCOComponentWithAssociatedGUIComponents )
protected
FCOData : TMtxGUICODataInt64;
// Getter/Setter für die Property COData
function getCOData() : TMtxGUICODataInt64;
procedure setCOData ( obj : TMtxGUICODataInt64 );
public
constructor Create ( AOwner : TComponent ); override;
destructor Destroy(); override;
published
// KO-Daten (Name, Wert, etc.)
property COData : TMtxGUICODataInt64 read getCOData write setCOData;
end; // TMtxCOComponentInt64COBase
// ===========================================================================
// Klasse: TMtxCOComponentInt64COReadOnly
// Klasse für das Lesen eines readonly INT64-KO (Abbildung zweier UINT32-KOs, High + Low Anteil)
// ===========================================================================
TMtxCOComponentInt64COReadOnly = class ( TMtxCOComponentInt64COBase, IMtxUpdatedGUIComponent,
IMtxUpdatedGUIComponentReadOnly,
IMtxGUIComponentWithCO,
IMtxGUIComponentWithCO64Bit,
IMtxCOComponentWithAssociatedGUIComponents )
public
constructor Create ( AOwner : TComponent ); override;
end; // TMtxCOComponentInt64COReadOnly
// ===========================================================================
// Klasse: TMtxCOComponentInt64COReadWrite
// Klasse für das Lesen/Schreiben eines INT64-KOs (Abbildung zweier UINT32-KOs, High + Low Anteil)
// ===========================================================================
TMtxCOComponentInt64COReadWrite = class ( TMtxCOComponentInt64COBase, IMtxUpdatedGUIComponent,
IMtxUpdatedGUIComponentReadWrite,
IMtxGUIComponentWithCO,
IMtxGUIComponentWithCO64Bit,
IMtxCOComponentWithAssociatedGUIComponents )
protected
b_is_changed : boolean;
FOnCalcValueToServo : TNotifyEvent;
// Getter / Setter der Property is_changed
function getIsChanged() : boolean;
procedure setIsChanged ( b : boolean );
public
constructor Create ( AOwner : TComponent ); override;
// Berechnung GUI --> Servo (==> COValue berechnen/aktualisieren)
procedure calcValueToServo();
published
// is_changed-Property: Sollte nur bei Änderung durch den Benutzer gesetzt werden.
property is_changed : boolean read getIsChanged write setIsChanged default false;
property OnCalcValueToServo : TNotifyEvent read FOnCalcValueToServo write FOnCalcValueToServo;
end; // TMtxCOComponentInt64COReadWrite
// ===========================================================================
// Klasse: TMtxCOComponentSimpleMultiCOBase
// Basisklasse für ein einfaches Multi-KO (1x Zeiger-KO + 1x Daten-KO)
// ===========================================================================
TMtxCOComponentSimpleMultiCOBase = class abstract ( TMtxCOComponentBase, IMtxUpdatedGUIComponent,
IMtxGUIComponentWithCO,
IMtxGUIComponentWithSimpleMultiCO,
IMtxCOComponentWithAssociatedGUIComponents )
protected
FCOData : TMtxGUICODataSimpleMultiCO;
// Getter/Setter für die Property COData
function getCOData() : TMtxGUICODataSimpleMultiCO;
procedure setCOData ( obj : TMtxGUICODataSimpleMultiCO );
public
constructor Create ( AOwner : TComponent ); override;
destructor Destroy(); override;
published
// KO-Daten (Name, Wert, etc.)
property COData : TMtxGUICODataSimpleMultiCO read getCOData write setCOData;
end; // TMtxCOComponentSimpleMultiCOBase
// ===========================================================================
// Klasse: TMtxCOComponentSimpleMultiCOReadWrite
// Klasse für das Lesen/Schreiben eines einfachen Multi-KOs (1x Zeiger-KO + 1x Daten-KO)
// ===========================================================================
TMtxCOComponentSimpleMultiCOReadWrite = class ( TMtxCOComponentSimpleMultiCOBase, IMtxUpdatedGUIComponent,
IMtxUpdatedGUIComponentReadWrite,
IMtxGUIComponentWithCO,
IMtxGUIComponentWithSimpleMultiCO,
IMtxCOComponentWithAssociatedGUIComponents )
protected
b_is_changed : boolean;
FOnCalcValueToServo : TNotifyEvent;
// Getter / Setter der Property is_changed
function getIsChanged() : boolean;
procedure setIsChanged ( b : boolean );
public
constructor Create ( AOwner : TComponent ); override;
// Berechnung GUI --> Servo (==> COValue berechnen/aktualisieren)
procedure calcValueToServo();
published
// is_changed-Property: Sollte nur bei Änderung durch den Benutzer gesetzt werden.
property is_changed : boolean read getIsChanged write setIsChanged default false;
property OnCalcValueToServo : TNotifyEvent read FOnCalcValueToServo write FOnCalcValueToServo;
end; // TMtxCOComponentSimpleMultiCOReadWrite
TMtxGUICheckedInfo = class ( TPersistent )
protected
FMask : int64;
FBitfieldChecked : int64;
FBitfieldUnchecked : int64;
public
constructor Create(); virtual;
published
// Für die Eigenschaft Checked: Maske für das auszuwertende KO
property Mask : int64 read FMask write FMask default 0;
// Für die Eigenschaft Checked: Bitfeld innerhalb der Maske, welches zum Setzen der Checkbox führt bzw. bei
// gesetzter Checkbox in das KO geschrieben wird.
property BitfieldChecked : int64 read FBitfieldChecked write FBitfieldChecked default 0;
// Für die Eigenschaft Checked: Bitfeld innerhalb der Maske, welches zum Löschen der Checkbox führt bzw. bei
// gelöschter Checkbox in das KO geschrieben wird.
property BitfieldUnchecked : int64 read FBitfieldUnchecked write FBitfieldUnchecked default 0;
end;
TMtxStringList = class ( TStringList )
public
function findString ( str : string; var i_inx : integer ) : boolean;
function getNextLine ( var i_inx : integer; var s_line : string ) : boolean;
function getNextLineUntilSectionBegin ( var i_inx : integer; var s_line : string ) : boolean;
function isEmptyString ( str : string ) : boolean;
function isCommentLine ( str : string ) : boolean;
function isSectionBegin ( str : string ) : boolean;
procedure addNewLine();
end;
TMtxWindowPositionEntry = class
private
FWinName : string; // Name des Fensters
FLeft : integer; // Fenster.Left
FTop : integer; // Fenster.Top
public
constructor Create();
// Name des Fensters
property WinName : string read FWinName write FWinName;
// Fenster.Left
property Left : integer read FLeft write FLeft;
// Fenster.Top
property Top : integer read FTop write FTop;
end;
TMtxWindowPositionEntryComparer = class ( TComparer<TMtxWindowPositionEntry> )
public
function Compare ( const Left, Right: TMtxWindowPositionEntry ): Integer; override;
end;
TMtxWindowPositionList = class ( TObjectList<TMtxWindowPositionEntry> )
public
constructor Create();
function getByName ( AWinName : string; var AEntry : TMtxWindowPositionEntry ) : boolean;
function getWinPosByName ( AWinName : string; var ALeft, ATop : integer ) : boolean;
procedure updateWinPos ( AWinName : string; ALeft, ATop : integer );
procedure Add ( AWinName : string; ALeft, ATop : integer ); reintroduce; overload;
end;
// Comparator für TMtxExtCOAssociatedComponentList
TMtxExtCOAssociatedComponentComparer = class ( TComparer<TWinControl> )
function Compare ( const Left, Right: TWinControl ): Integer; override;
end;
// Liste mit den GUI-Komponenten, die mit einem extern definierten KO verlinkt sind.
TMtxExtCOAssociatedComponentList = class ( TObjectList<TWinControl> )
public
constructor Create();
end;
//procedure mmsg (s : string );
implementation
uses Math, MtxUtils;
//procedure mmsg (s : string ); begin WideShowMessage (s); end;
// =============================================================================
// =============================================================================
// C L A S S TBoolean
// =============================================================================
// =============================================================================
// =============================================================================
// Class : TBoolean
// Function : create()
// Creates a default object with value set to false.
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2014-08-20 /gsv/
// History : --
// =============================================================================
constructor TBoolean.create();
begin
Create ( false );
end; // constructor TBoolean.create();
// =============================================================================
// Class : TBoolean
// Function : create()
// Creates a new object with the boolean value b_val.
// Parameter : b_val - The initial boolean value of the object.
// Return : --
// Exceptions : --
// First author : 2014-08-20 /gsv/
// History : --
// =============================================================================
constructor TBoolean.create ( b_val : boolean );
begin
self.b_value := b_val;
inherited Create();
end; // constructor TBoolean.create ( b_val : boolean );
// =============================================================================
// Class : TBoolean
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TBoolean.Clone() : TMtxCloneableObject;
begin
result := TBoolean.create();
TBoolean(result).Value := self.Value;
end; // function TBoolean.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
// C L A S S TDouble
// =============================================================================
// =============================================================================
// =============================================================================
// Class : TDouble
// Function : create()
// Creates a default object with value set to 0.
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2007-11-30 /gsv/
// History : --
// =============================================================================
constructor TDouble.create();
begin
Create ( 0 );
end; // constructor TDouble.create();
// =============================================================================
// Class : TDouble
// Function : create()
// Creates a new object with the double value d_val.
// Parameter : d_val - The initial double value of the object.
// Return : --
// Exceptions : --
// First author : 2007-11-30 /gsv/
// History : --
// =============================================================================
constructor TDouble.create ( d_val : double );
begin
self.d_value := d_val;
inherited Create();
end; // constructor TDouble.create ( d_val : double );
// =============================================================================
// Class : TDouble
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TDouble.Clone() : TMtxCloneableObject;
begin
result := TDouble.create();
TDouble(result).Value := self.Value;
end; // function TDouble.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
// C L A S S TAcknowledgedDouble
// =============================================================================
// =============================================================================
// =============================================================================
// Class : TAcknowledgedDouble
// Function : create()
// Creates a new TAcknowledgedDouble object, initialized with default values.
// Parameter : --
// Return : --
// History : 2007-11-30 /gsv/: d_value is initialized in the inherited constructor!
// ==> Initialization removed.
// =============================================================================
constructor TAcknowledgedDouble.create();
begin
self.b_value_valid := false;
inherited Create();
end; // constructor TAcknowledgedDouble.create();
// =============================================================================
// Class : TAcknowledgedDouble
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TAcknowledgedDouble.Clone() : TMtxCloneableObject;
begin
result := TAcknowledgedDouble.create();
TAcknowledgedDouble(result).Value := self.Value;
TAcknowledgedDouble(result).isValid := self.isValid;
end; // function TAcknowledgedDouble.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
// C L A S S TInteger
// =============================================================================
// =============================================================================
// =============================================================================
// Class : TInteger
// Function : create()
// Konstruktor: Neue Instanz mit Defaultwert 0 erzeugen
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2012-10-05 /gsv/
// History : --
// =============================================================================
constructor TInteger.Create();
begin
Create ( 0 );
end; // constructor TInteger.create();
// =============================================================================
// Class : TInteger
// Function : create()
// Konstruktor: Neue Instanz mit dem vorgegebenen Wert i
// erzeugen
// Parameter : i - Initialwert des Objektes
// Return : --
// Exceptions : --
// First author : 2012-10-05 /gsv/
// History : --
// =============================================================================
constructor TInteger.create ( i : longint );
begin
self.li_value := i;
inherited Create();
end; // constructor TInteger.create ( i : longint );
// =============================================================================
// Class : TInteger
// Function : copyFrom()
// Kopierfunktion - kopiert den Inhalt von src nach self
// Parameter : src - zu kopierendes Objekt
// Return : --
// Exceptions : EInvalidArgument, falls src nicht initialisiert ist.
// First author : 2012-10-05 /gsv/
// History : --
// =============================================================================
procedure TInteger.copyFrom ( src : TInteger );
begin
// Übergabeparameter prüfen
if ( not Assigned ( src ) ) then raise EInvalidArgument.Create ( 'src is not assigned!' );
self.li_value := src.Value;
end; // procedure TInteger.copyFrom ( src : TInteger );
// =============================================================================
// Class : TInteger
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TInteger.Clone() : TMtxCloneableObject;
begin
result := TInteger.create();
TInteger(result).copyFrom ( self );
end; // function TInteger.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
// C L A S S TInt64
// =============================================================================
// =============================================================================
// =============================================================================
// Class : TInt64
// Function : create()
// Creates a default object with value set to 0.
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2007-11-30 /gsv/
// History : --
// =============================================================================
constructor TInt64.create();
begin
Create ( 0 );
end; // constructor TInt64.create();
// =============================================================================
// Class : TInt64
// Function : create()
// Creates a new object with the integer value i64.
// Parameter : i64 - The initial integer value of the object.
// Return : --
// Exceptions : --
// First author : 2007-11-30 /gsv/
// History : --
// =============================================================================
constructor TInt64.create ( i64 : int64 );
begin
self.i64_value := i64;
inherited Create();
end; // constructor TInt64.create ( i64 : int64 );
// =============================================================================
// Class : TInt64
// Function : copyFrom()
// Kopierfunktion - kopiert den Inhalt von src nach self
// Parameter : src - zu kopierendes Objekt
// Return : --
// Exceptions : EInvalidArgument, falls src nicht initialisiert ist.
// First author : 2008-12-02 /gsv/
// History : --
// =============================================================================
procedure TInt64.copyFrom ( src : TInt64 );
begin
// Übergabeparameter prüfen
if ( not Assigned ( src ) ) then raise EInvalidArgument.Create ( 'src is not assigned!' );
self.i64_value := src.Value;
end; // procedure TInt64.copyFrom ( src : TInt64 );
// =============================================================================
// Class : TInt64
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TInt64.Clone() : TMtxCloneableObject;
begin
result := TInt64.create();
TInt64(result).copyFrom ( self );
end; // function TInt64.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
// C L A S S TAcknowledgedInt64
// =============================================================================
// =============================================================================
// =============================================================================
// Class : TAcknowledgedInt64
// Function : create()
// Creates a new TAcknowledgedInt64 object, initialized with default values.
// Parameter : --
// Return : --
// Exceptions : --
// History : 2007-11-30 /gsv/: i64_value is initialized in the inherited constructor!
// ==> Initialization removed.
// =============================================================================
constructor TAcknowledgedInt64.create();
begin
self.b_value_valid := false;
inherited Create();
end; // constructor TAcknowledgedInt64.create();
// =============================================================================
// Class : TAcknowledgedInt64
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TAcknowledgedInt64.Clone() : TMtxCloneableObject;
begin
result := TAcknowledgedInt64.create();
TAcknowledgedInt64(result).copyFrom ( self );
TAcknowledgedInt64(result).isValid := self.isValid;
end; // function TAcknowledgedInt64.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
// C L A S S T M a s k e d T a b l e E n t r y
// =============================================================================
// =============================================================================
// =============================================================================
// Class : TMaskedTableEntry
// Function : create()
// Creates a new TMaskedTableEntry object,
// initialized with default values
// Parameter : --
// Return : --
// Exceptions : --
// History : 2007-11-30 /gsv/: New property "UserData"
// 2009-10-05 /gsv/: Erweiterung list_alt_bitfields
// =============================================================================
constructor TMaskedTableEntry.create();
begin
self.s_alias := '';
self.lw_bitfield := 0;
self.s_text := '';
self.i_text_id := C_TEXT_ID_DEFAULT_VALUE;
self.objUserData := nil;
// 2009-10-05 /gsv/: Liste mit alternativen Bitfeldern
self.list_alt_bitfields := TLongwordList.create();
self.list_alt_bitfields.clear();
self.list_alt_bitfields.AllowDuplicates := false; // Keine Duplikate zulassen
end; // constructor TMaskedTableEntry.create();
// =============================================================================
// Class : TMaskedTableEntry
// Function : destroy
// Destruktor: Gibt den belegten Speicherplatz wieder frei.
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2009-10-05 /gsv/
// History : --
// =============================================================================
destructor TMaskedTableEntry.Destroy();
begin
try
if ( Assigned ( self.objUserData ) ) then self.objUserData.Free();
except on E:Exception do ;
end;
self.list_alt_bitfields.Free();
inherited;
end; // destructor TMaskedTableEntry.Destroy();
// =============================================================================
// Class : TMaskedTableEntry
// Function : copyFrom()
// Copies the entry to this object.
// Parameter : entry - The entry to be copied.
// Return : --
// Exceptions : --
// History : 2007-11-30 /gsv/: New property "UserData"
// 2009-10-05 /gsv/: Erweiterung list_alt_bitfields
// =============================================================================
procedure TMaskedTableEntry.copyFrom ( entry : TMaskedTableEntry );
begin
self.s_alias := entry.s_alias;
self.lw_bitfield := entry.lw_bitfield;
self.s_text := entry.s_text;
self.i_text_id := entry.i_text_id;
// 2014-08-21 /gsv/: Kopiervorgang von UserData verbessert!
// Es wurde eine neue Basisklasse eingeführt, die eine Clone-Funktion
// unterstützt, so dass nicht mehr die Objektinstanz zugewiesen wird,
// sondern eine neue Kopie des Objektes angelegt wird.
// Aktuelles Objekt ggf. vorher freigeben.
if ( Assigned ( self.objUserData ) ) then self.objUserData.Free();
if ( Assigned ( entry.objUserData ) ) then
begin
// Prüfen, ob das neue Object die Clone-Funktion unterstützt
if ( entry.objUserData is TMtxCloneableObject ) then
begin
// Objekt klonen
self.objUserData := TMtxCloneableObject(entry.objUserData).Clone();
end
else
begin
// Keine Clone-Funktion ==> Instanzzuweisung
self.objUserData := entry.objUserData;
end;
end // if ( Assigned ( entry.objUserData ) ) then
else
begin
// entry.UserData nicht initialisiert/zugewiesen
self.objUserData := entry.objUserData;
end; // else, if ( Assigned ( entry.objUserData ) ) then
self.list_alt_bitfields.copyFrom ( entry.list_alt_bitfields );
end; // procedure TMaskedTableEntry.copyFrom()
// =============================================================================
// Class : TMaskedTableEntry
// Function : equals()
// Tests wether this object equals the object.
// Parameter : e - The object to compare this object to.
// Return : true - this object equals e
// false - this object is not equal to e
// Exceptions : --
// =============================================================================
function TMaskedTableEntry.equals ( e : TMaskedTableEntry ) : boolean;
begin
if ( CompareText ( self.s_alias, e.s_alias ) <> 0 ) then
begin
// Bitfeld-Aliases sind unterschiedlich ==> Die Bitfelder sind nicht gleich!
result := false;
exit;
end; // if ( CompareText ( self.s_alias, e.s_alias ) <> 0 ) then
result := (self.lw_bitfield = e.lw_bitfield);
// 2009-10-05 /gsv/: ggf. Alternative Bitfeld-Werte prüfen
if ( (not result) and self.hasAltBitfields() ) then
begin
result := self.AltBitfields.contains ( e.lw_bitfield );
end; // if ( (not result) and self.hasAltBitfields() ) then
end; // function TMaskedTableEntry.equals()
// =============================================================================
// Class : TMaskedTableEntry
// Function : hasAltBitfields()
// Existieren alternative Bitfeld-Definitionen?
// Parameter : --
// Return : TRUE - alternative Bitfeld-Definitionen vorhanden
// FALSE - keine alternative Bitfeld-Definitionen vorhanden
// Exceptions : --
// First author : 2009-10-05 /gsv/
// History : --
// =============================================================================
function TMaskedTableEntry.hasAltBitfields() : boolean;
begin
result := self.list_alt_bitfields.Count > 0;
end; // function TMaskedTableEntry.hasAltBitfields() : boolean;
// =============================================================================
// Class : TMaskedTableEntry
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TMaskedTableEntry.Clone() : TMtxCloneableObject;
begin
result := TMaskedTableEntry.create();
TMaskedTableEntry(result).copyFrom ( self );
end; // function TMaskedTableEntry.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
// C L A S S T M a s k e d T a b l e
// =============================================================================
// =============================================================================
// =============================================================================
// Class :
// Function :
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
// =============================================================================
// Class : TMaskedTable
// Function : create()
// Creates an empty translation table.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
constructor TMaskedTable.create();
begin
// 2013-07-30 /gsv/: Umstellung von TList auf TObjectList.
// Dadurch wird der Speicherplatz beim Löschen der Einträge automatisch freigegeben.
self.entries := TObjectList.Create();
self.entries.OwnsObjects := true;
self.mask.s_alias := '';
self.mask.lw_mask := 0;
self.FOnAdd := nil;
self.FOnClear := nil;
self.FOnDelete := nil;
self.CapitalizeFirstLetter := false;
end; // constructor TMaskedTable.create();
// =============================================================================
// Class : TMaskedTable
// Function : copyFrom
// This function copies the object table in this object.
// If table is not assigned, nothing will be done!
// Only the table data (mask and entries) will be copied!
// Any (event) pointers remain unchanged!
// Parameter : table - The object to copy
// Return : --
// Exceptions : --
// =============================================================================
procedure TMaskedTable.copyFrom ( table : TMaskedTable );
var
i : integer;
tbe : TMaskedTableEntry;
begin
// There is nothing more to do, when table is not assigned!
if ( not Assigned(table) ) then exit;
// first clear the items of this object
self.clear();
// copy the mask
self.mask := table.mask;
// copy the table entries
for i := 0 to table.entries.Count-1 do
begin
tbe := TMaskedTableEntry.create();
tbe.copyFrom ( TMaskedTableEntry(table.entries.Items[i]) );
// 2013-07-30 /gsv/: Falls der Eintrag nicht hinzugefügt werden kann,
// z.B. weil dieser bereits in der Liste enthalten ist, dann die Instanz freigeben,
// damit keine Memory Leaks entstehen.
if ( not self.Add ( tbe ) ) then
begin
tbe.Free();
end;
end; // for i := 0 to table.entries.Count-1 do
end; // procedure TMaskedTable.copyFrom()
// =============================================================================
// Class : TMaskedTable
// Function : destroy()
// Destroys this object and frees the memory,
// allocated by this object.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
destructor TMaskedTable.destroy();
begin
// 2013-02-25 /gsv/: Sämtliche Objekte freigeben, die Memory Leaks verursachen
self.entries.Clear();
self.entries.Free();
inherited Destroy();
end; // destructor TMaskedTable.destroy();
// =============================================================================
// Class : TMaskedTable
// Function : clear()
// Clears the table.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
procedure TMaskedTable.clear();
begin
// clear the entries
self.entries.Clear();
// fire OnClear event
if ( Assigned ( self.FOnClear ) ) then self.FOnClear ( self );
end; // procedure TMaskedTable.clear();
// =============================================================================
// Class : TMaskedTable
// Function : add()
// Adds the given entry to the table.
// This function does nothing,
// if the table already contains the given entry!
// Parameter : entry - The entry to add.
// Return : TRUE - Eintrag hinzugefügt
// FALSE - Eintrag nicht hinzugefügt (ggf. bereis vorhanden)
// Exceptions : --
// History : 2013-07-30 /gsv/: Rückgabewert ergänzt
// =============================================================================
function TMaskedTable.add ( entry : TMaskedTableEntry ) : boolean;
begin
result := false;
// if the entry is not assigned, then there is nothing more to do here!
if ( not Assigned ( entry ) ) then exit;
// The entry will be added to the table, only if the table does not yet contain it!
if ( not self.contains(entry) ) then
begin
// Add the entry to the table
self.entries.Add ( entry );
result := true;
// fire OnAdd event
if ( Assigned ( FOnAdd ) ) then FOnAdd ( self, entry );
end; // if ( not self.contains(entry) ) then
end; // function TMaskedTable.add ( entry : TMaskedTableEntry ) : boolean;
// =============================================================================
// Class : TMaskedTable
// Function : add()
// Adds the given entry to the table.
// This function does nothing,
// if the table already contains the given entry!
// Parameter : alias - The alias of the entry to add
// bitfield - The bitfield of the entry to add
// text - The text of the entry to add
// Return : TRUE - Eintrag hinzugefügt
// FALSE - Eintrag nicht hinzugefügt (ggf. bereis vorhanden)
// Exceptions : --
// History : 2007-11-30 /gsv/: There is a new extended function "add()",
// which is called here.
// 2013-07-30 /gsv/: Rückgabewert ergänzt
// =============================================================================
function TMaskedTable.add ( alias : string; bitfield : longword; text : string ) : boolean;
begin
result := self.add ( alias, bitfield, text, C_TEXT_ID_DEFAULT_VALUE, nil );
end; // function TMaskedTable.add ( alias : string; bitfield : longword; text : string ) : boolean;
// =============================================================================
// Class : TMaskedTable
// Function : add()
// Adds the given entry to the table.
// This function does nothing,
// if the table already contains the given entry!
// Parameter : alias - The alias of the entry to add
// bitfield - The bitfield of the entry to add
// text - The text of the entry to add
// userData - User defined data (may also be nil!)
// Return : TRUE - Eintrag hinzugefügt
// FALSE - Eintrag nicht hinzugefügt (ggf. bereis vorhanden)
// Exceptions : --
// History : 2013-07-30 /gsv/: Rückgabewert ergänzt
// =============================================================================
function TMaskedTable.add ( alias : string; bitfield : longword; text : string; userData : TMtxCloneableObject ) : boolean;
begin
result := self.add ( alias, bitfield, text, C_TEXT_ID_DEFAULT_VALUE, userData );
end; // function TMaskedTable.add ( alias : string; bitfield : longword; text : string; userData : TMtxCloneableObject ) : boolean;
function TMaskedTable.add ( alias : string; bitfield : longword; text : string; userData : TObject ) : boolean;
begin
result := self.add ( alias, bitfield, text, C_TEXT_ID_DEFAULT_VALUE, userData );
end;
// =============================================================================
// Class : TMaskedTable
// Function : add()
// Adds the given entry to the table.
// This function does nothing,
// if the table already contains the given entry!
// Parameter : alias - The alias of the entry to add
// bitfield - The bitfield of the entry to add
// text - The text of the entry to add
// text_id - The text ID (placeholder) for multilanguage texts
//
// Return : TRUE - Eintrag hinzugefügt
// FALSE - Eintrag nicht hinzugefügt (ggf. bereis vorhanden)
// Exceptions : --
// History : 2015-12-02 /gsv/
// =============================================================================
function TMaskedTable.add ( alias : string; bitfield : longword; text : string; text_id : integer ) : boolean;
begin
result := self.add ( alias, bitfield, text, text_id, nil );
end; // function TMaskedTable.add ( ... )
// =============================================================================
// Class : TMaskedTable
// Function : add()
// Adds the given entry to the table.
// This function does nothing,
// if the table already contains the given entry!
// Parameter : alias - The alias of the entry to add
// bitfield - The bitfield of the entry to add
// text - The text of the entry to add
// text_id - The text ID (placeholder) for multilanguage texts
// userData - User defined data (may also be nil!)
// Return : TRUE - Eintrag hinzugefügt
// FALSE - Eintrag nicht hinzugefügt (ggf. bereis vorhanden)
// Exceptions : --
// History : 2015-12-02 /gsv/
// =============================================================================
function TMaskedTable.add ( alias : string; bitfield : longword; text : string; text_id : integer; userData : TObject ) : boolean;
var
tbe : TMaskedTableEntry;
begin
// 2016-09-28 /gsv/: Ggf. den ersten Buchstaben in Großbuchstaben umwandeln
if ( self.CapitalizeFirstLetter ) then
begin
if ( Length(text) >= 1 ) then
begin
text[1] := UpCase ( text[1] );
end;
end;
tbe := TMaskedTableEntry.create();
tbe.Alias := alias;
tbe.Bitfield := bitfield;
tbe.Text := text;
tbe.TextID := text_id;
tbe.UserData := userData;
result := self.add ( tbe );
// 2013-07-30 /gsv/: Memory Leaks beseitigen
// Falls das neue Objekt der Liste nicht hinzugefügt werden konnte, z.B. weil es bereits enthalten ist,
// dann muss die lokale Variable wieder freigegeben werden, da sonst Memory Leaks entstehen.
if ( not result ) then
begin
tbe.Free();
end;
end; // function TMaskedTable.add ( ... )
// =============================================================================
// Class : TMaskedTable
// Function : delete()
// Removes the given entry from the table.
// This function does nothing,
// if the table does not contain the given entry!
// Parameter : entry - The entry to be removed.
// Return : The table entry with the given alias.
// Exceptions : EObjectNotExist, if there is no entry with the given alias.
// =============================================================================
procedure TMaskedTable.delete ( entry : TMaskedTableEntry );
var
tbe : TMaskedTableEntry;
i : integer;
b_entry_deleted : boolean;
begin
b_entry_deleted := false;
// search for the given entry
for i := 0 to self.entries.Count-1 do
begin
tbe := TMaskedTableEntry ( self.entries.Items[i] );
// the given entry has been found?
if ( tbe.equals ( entry ) ) then
begin
self.entries.Delete ( i );
b_entry_deleted := true;
break;
end; // if ( tbe.equals ( entry ) ) then
end; // for i := 0 to self.entries.Count-1 do
// fire OnDelete event, only when the entry was really deleted
if ( b_entry_deleted and Assigned ( FOnDelete ) ) then FOnDelete ( self, entry );
end; // procedure TMaskedTable.delete();
// =============================================================================
// Class : TMaskedTable
// Function : getByAlias()
// Returns the entry with the given alias.
// Parameter : alias - The alias of the entry (bitfield) to search for.
// Return : The table entry with the given alias.
// Exceptions : EObjectNotExist, if there is no entry with the given alias.
// =============================================================================
function TMaskedTable.getByAlias ( alias : string ) : TMaskedTableEntry;
var
tbe : TMaskedTableEntry;
i : integer;
begin
// search for the given entry
for i := 0 to self.entries.Count-1 do
begin
tbe := TMaskedTableEntry ( self.entries.Items[i] );
// the given entry has been found?
if ( tbe.s_alias = alias ) then
begin
result := tbe;
exit;
end; // if ( tbe.s_alias = alias ) then
end; // for i := 0 to self.entries.Count-1 do
// the entry was not found ==> throw new exception
raise EObjectNotExist.Create ( MtxWideFormat ( 'Entry alias="%s" does not exist!', [alias] ) );
end; // function TMaskedTable.getByAlias();
// =============================================================================
// Class : TMaskedTable
// Function : getByBitfield()
// Returns the entry with the given bitfield.
// Parameter : bitfield - The bitfield of the entry to search for.
// Return : The table entry with the given bitfield.
// Exceptions : EObjectNotExist, if there is no entry with the given bitfield.
// =============================================================================
function TMaskedTable.getByBitfield ( bitfield : longword ) : TMaskedTableEntry;
var
i : integer;
begin
if ( not self.getByBitfield ( bitfield, i, result ) ) then
begin
// Eintrag nicht gefunden
raise EObjectNotExist.Create ( MtxWideFormat ( 'Entry bitfield=0x%x does not exist!', [bitfield] ) );
end;
end;
function TMaskedTable.getIndexByBitfield ( bitfield : longword ) : integer;
begin
if ( not getByBitfield ( bitfield, result ) ) then
begin
// Eintrag nicht gefunden.
result := -1;
end;
end;
// =============================================================================
// Class : TMaskedTable
// Function : getByBitfield()
// Eintrag mit dem angegebenen Bitfeld zurückgeben
// Diese Funktion löst keine Exception aus, sondern gibt den
// Status (Eintrag gefunden/nicht gefunden) über den Rückgabewert
// result zurück. Dadurch ist sie effizienter als das Auslösen
// einer Exception.
// Parameter : bitfield - Bitfeld des gesuchten Eintrags
// index - Rückgabe des Index des gefundenen Eintrags,
// -1, falls der Eintrag nicht gefunden wird.
// entry - Rückgabe des gefundenen Eintrags,
// nil, falls der Eintrag nicht gefunden wird.
// Return : true - Eintrag gefunden
// false - Eintrag nicht gefunden
// Exceptions : --
// First author : 2016-09-16 /gsv/
// History : --
// =============================================================================
function TMaskedTable.getByBitfield ( bitfield : longword; var index : integer ) : boolean;
var
entry : TMaskedTableEntry;
begin
result := self.getByBitfield ( bitfield, index, entry );
end;
function TMaskedTable.getByBitfield ( bitfield : longword; var index : integer; var entry : TMaskedTableEntry ) : boolean;
var
tbe : TMaskedTableEntry;
i : integer;
begin
// Interne Liste nach dem Bitfeld durchsuchen
for i := 0 to self.entries.Count-1 do
begin
tbe := TMaskedTableEntry ( self.entries.Items[i] );
// Eintrag gefunden?
// Auch die alternativen Bitfeld-Definitionen berücksichtigen / durchsuchen
if ( (tbe.lw_bitfield = bitfield) or
(tbe.hasAltBitfields() and tbe.AltBitfields.contains(bitfield)) ) then
begin
index := i;
entry := tbe;
result := true;
exit;
end; // if ( tbe.lw_bitfield = bitfield ) then
end; // for i := 0 to self.entries.Count-1 do
// Eintrag nicht gefunden
index := -1;
entry := nil;
result := false;
end; // function TMaskedTable.getByBitfield ( ... )
// =============================================================================
// Class : TMaskedTable
// Function : getByText()
// Returns the entry with the given text.
// Parameter : text - The text of the entry to search for.
// Return : The table entry with the given text.
// Exceptions : EObjectNotExist, if there is no entry with the given text.
// =============================================================================
function TMaskedTable.getByText ( text : string ) : TMaskedTableEntry;
var
tbe : TMaskedTableEntry;
i : integer;
begin
// search for the given entry
for i := 0 to self.entries.Count-1 do
begin
tbe := TMaskedTableEntry ( self.entries.Items[i] );
// the given entry has been found?
if ( tbe.s_text = text ) then
begin
result := tbe;
exit;
end; // if ( tbe.s_text = text ) then
end; // for i := 0 to self.entries.Count-1 do
// the entry was not found ==> throw new exception
raise EObjectNotExist.Create ( MtxWideFormat ( 'Entry text="%s" does not exist!', [text] ) );
end; // function TMaskedTable.getByText()
// =============================================================================
// Class : TMaskedTable
// Function : getMask()
// Returns the mask associated with this table.
// Parameter : --
// Return : The mask associated with this table.
// Exceptions : --
// =============================================================================
function TMaskedTable.getMask : TMaskedTableMask;
begin
result := self.mask;
end; // function TMaskedTable.getMask();
// =============================================================================
// Class : TMaskedTable
// Function : setMask
// Sets the mask, associated with this translation table.
// Parameter : new_mask - The new mask to be set.
// Return : --
// Exceptions : --
// =============================================================================
procedure TMaskedTable.setMask ( new_mask : TMaskedTableMask );
begin
self.mask := new_mask;
end; // procedure TMaskedTable.setMask();
// =============================================================================
// Class : TMaskedTable
// Function : setMask
// Sets/changes the mask, associated with this translation table.
// Parameter : alias - The alias of the mask
// value - The mask value
// Return : --
// Exceptions : --
// =============================================================================
procedure TMaskedTable.setMask ( alias : string; value : longword );
begin
self.mask.s_alias := alias;
self.mask.lw_mask := value;
end; // procedure TMaskedTable.setMask();
// =============================================================================
// Class : TMaskedTable
// Function : isEmpty()
// Tests wether this table is empty or not.
// Parameter : --
// Return : true - This table is empty, i.e. it has no entries!
// false - This table is not empty, i.e. it has at least one entry!
// Exceptions : --
// =============================================================================
function TMaskedTable.isEmpty() : boolean;
begin
result := (self.entries.Count < 1);
end; // function TMaskedTable.isEmpty();
// =============================================================================
// Class : TMaskedTable
// Function : indexOf()
// Returns the index of the given table entry
// Parameter : entry - The entry to get the index of
// Return : index of the given table entry (the index is in range [0...Count) ) or
// -1, if the entry could not be found
// Exceptions : --
// =============================================================================
function TMaskedTable.indexOf ( entry : TMaskedTableEntry ) : integer;
var
i : integer;
begin
result := -1;
for i := 0 to self.entries.Count-1 do
begin
// The entry has been found?
if ( TMaskedTableEntry(self.entries.Items[i]).equals ( entry ) ) then
begin
result := i;
exit;
end;
end; // for i := 0 to self.entries.Count-1 do
end; // function TMaskedTable.indexOf();
// =============================================================================
// Class : TMaskedTable
// Function : contains()
// Tests wether the table contains the given entry.
// Parameter : entry - The entry to be tested
// Return : true - The table contains the given entry.
// false - The table does not contain the given entry.
// Exceptions : --
// =============================================================================
function TMaskedTable.contains ( entry : TMaskedTableEntry ) : boolean;
begin
result := (self.indexOf(entry) >= 0);
end; // function TMaskedTable.contains()
// =============================================================================
// Class : TMaskedTable
// Function : getCount
// Returns the number of entries, contained currently in the table.
// Parameter : --
// Return : number of table entries
// Exceptions : --
// =============================================================================
function TMaskedTable.getCount() : integer;
begin
result := self.entries.Count;
end; // function TMaskedTable.getCount() : integer;
// =============================================================================
// Class : TMaskedTable
// Function :
//
// Parameter : --
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of table entries
// =============================================================================
function TMaskedTable.getEntry ( inx : integer ) : TMaskedTableEntry;
begin
if ( (inx < 0) or (inx >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [inx, self.Count-1] ) );
result := TMaskedTableEntry ( self.entries.Items[inx] );
end; // function TMaskedTable.getEntry ( inx : integer ) : TMaskedTableEntry;
// =============================================================================
// Class : TMaskedTable
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TMaskedTable.Clone() : TMtxCloneableObject;
begin
result := TMaskedTable.create();
TMaskedTable(result).copyFrom ( self );
end; // function TMaskedTable.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
//
// K L A S S E TDoubleList
//
// =============================================================================
// =============================================================================
// =============================================================================
// Constructor : create
// Creates a new object, initialized with default values.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
constructor TDoubleList.create();
begin
self.list_values := TList.Create();
end; // constructor TDoubleList.create();
// =============================================================================
// Destructor : destroy
// Frees the memory allocated by this object.
// Parameter : --
// Return : --
// =============================================================================
destructor TDoubleList.destroy();
begin
self.clear();
self.list_values.Free();
inherited Destroy();
end; // destructor TDoubleList.destroy();
// =============================================================================
// Function : copyFrom
// Copies the contents of list to the calling object.
// Parameter : list - The double list to be copied.
// Return : --
// Exceptions : --
// =============================================================================
procedure TDoubleList.copyFrom ( list : TDoubleList );
var
i : integer;
begin
self.clear(); // Clear the internal list
// If the list to be copied is not assigned, then do nothing. ==> self = empty!
if ( not Assigned ( list ) ) then exit;
// Copy the contents of list to the calling object self
for i := 0 to list.Count-1 do
self.add ( list.get(i) );
end; // procedure TDoubleList.copyFrom ( list : TDoubleList );
// =============================================================================
// Class : TDoubleList
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TDoubleList.Clone() : TMtxCloneableObject;
begin
result := TDoubleList.create();
TDoubleList(result).copyFrom ( self );
end; // function TDoubleList.Clone() : TMtxCloneableObject;
// =============================================================================
// Function : getCount
// Returns the number of elements in the list.
// Parameter : --
// Return : Number of elements in the list
// Exceptions : --
// =============================================================================
function TDoubleList.getCount() : integer;
begin
result := self.list_values.Count;
end; // function TDoubleList.getCount() : integer;
// =============================================================================
// Function : update
// Updates the entry at the specified index
// Parameter : index - the index of the entry to be updated
// value - the new value of the entry
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
procedure TDoubleList.update ( index : integer; value : double );
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
PDouble(self.list_values[index])^ := value;
end; // procedure TDoubleList.update ( index : integer; value : double );
// =============================================================================
// Function : get
// Returns the element (double-value) at the specified index.
// Parameter : index - index of the element to be returned
// Return : The element (double value) at the specified index.
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
function TDoubleList.get ( index : integer ) : double;
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
// The index is valid ==> return the double value at the specified index
result := PDouble(self.list_values.Items[index])^;
end; // function TDoubleList.get ( index : integer ) : double;
// =============================================================================
// Function : add
// Adds the value at the end of the list.
// The list can contain the same value more than once.
// Parameter : value - the value to be added
// Return : --
// Exceptions : --
// =============================================================================
procedure TDoubleList.add ( value : double );
var
ptr_value : PDouble;
begin
New ( ptr_value );
ptr_value^ := value;
self.list_values.Add ( ptr_value );
end; // procedure TDoubleList.add ( value : double );
// =============================================================================
// Function : add
// Adds the value at the specified index in the list.
// The list can contain the same value more than once.
// Parameter : index - the index in the list, at which the value will be added.
// value - the value to be added
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index > number of elements in the list
// =============================================================================
procedure TDoubleList.add ( index : integer; value : double );
var
ptr_value : PDouble;
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index > self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
New ( ptr_value );
ptr_value^ := value;
self.list_values.Insert ( index, ptr_value );
end; // procedure TDoubleList.add ( index : integer; value : double );
// =============================================================================
// Function : clear
// Clears the contents of the list and frees the memory,
// allocated by the elements of the list.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
procedure TDoubleList.clear();
var
i : integer;
begin
for i := 0 to self.list_values.Count-1 do
Dispose ( self.list_values.Items[i] );
self.list_values.Clear();
end; // procedure TDoubleList.clear();
// =============================================================================
// Function : isEmpty
// Tests wether the list is empty or not.
// Parameter : --
// Return : true - the list is empty
// Exceptions : --
// =============================================================================
function TDoubleList.isEmpty() : boolean;
begin
result := self.Count > 0;
end; // function TDoubleList.isEmpty() : boolean;
// =============================================================================
// =============================================================================
//
// C L A S S TAcknowledgedDoubleList
//
// =============================================================================
// =============================================================================
// =============================================================================
// Constructor : create
// Creates a new empty list.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
constructor TAcknowledgedDoubleList.create();
begin
self.list_values := TList.Create();
end; // constructor TAcknowledgedDoubleList.create();
// =============================================================================
// Destructor : destroy
// Frees the memory allocated by this object.
// Parameter : --
// Return : --
// =============================================================================
destructor TAcknowledgedDoubleList.destroy();
begin
self.clear();
self.list_values.Free();
inherited Destroy();
end; // destructor TAcknowledgedDoubleList.destroy();
// =============================================================================
// Function : copyFrom
// Copies the contents of list to the calling object.
// Parameter : list - The acknowledged double list to be copied.
// Return : --
// Exceptions : --
// =============================================================================
procedure TAcknowledgedDoubleList.copyFrom ( list : TAcknowledgedDoubleList );
var
i : integer;
begin
self.clear(); // Clear the internal list
// If the list to be copied is not assigned, then do nothing. ==> self = empty!
if ( not Assigned ( list ) ) then exit;
// Copy the contents of list to the calling object self
for i := 0 to list.Count-1 do
self.add ( list.get(i) );
end; // procedure TAcknowledgedDoubleList.copyFrom ( list : TAcknowledgedDoubleList );
// =============================================================================
// Function : getCount
// Returns the number of elements in the list.
// Parameter : --
// Return : Number of elements in the list
// Exceptions : --
// =============================================================================
function TAcknowledgedDoubleList.getCount() : integer;
begin
result := self.list_values.Count;
end; // function TAcknowledgedDoubleList.getCount() : integer;
// =============================================================================
// Function : get
// Returns the entry at the specified index.
// Parameter : index - index of the element to be returned
// Return : The entry at the specified index.
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
function TAcknowledgedDoubleList.get ( index : integer ) : TAcknowledgedDouble;
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
// The index is valid ==> return the entry at the specified index
result := PAcknowledgedDouble(self.list_values.Items[index])^;
end; // function TAcknowledgedDoubleList.get ( index : integer ) : TAcknowledgedDouble;
// =============================================================================
// Function : add
// Adds the value at the end of the list.
// The list can contain the same value more than once.
// Parameter : value - the value to be added
// Return : --
// Exceptions : --
// =============================================================================
procedure TAcknowledgedDoubleList.add ( value : double; b_valid : boolean );
var
ack_double : TAcknowledgedDouble;
begin
ack_double := TAcknowledgedDouble.create();
ack_double.Value := value;
ack_double.isValid := b_valid;
self.add ( ack_double );
end; // procedure TAcknowledgedDoubleList.add ( value : TAcknowledgedDouble );
// =============================================================================
// Function : add
// Adds the value at the end of the list.
// The list can contain the same value more than once.
// Parameter : value - the value to be added
// Return : --
// Exceptions : --
// =============================================================================
procedure TAcknowledgedDoubleList.add ( value : TAcknowledgedDouble );
var
ptr_value : PAcknowledgedDouble;
begin
New ( ptr_value );
ptr_value^ := value;
self.list_values.Add ( ptr_value );
end; // procedure TAcknowledgedDoubleList.add ( value : TAcknowledgedDouble );
// =============================================================================
// Function : add
// Adds the value at the specified index in the list.
// The list can contain the same value more than once.
// Parameter : index - the index in the list, at which the value will be added.
// value - the value to be added
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index > number of elements in the list
// =============================================================================
procedure TAcknowledgedDoubleList.add ( index : integer; value : TAcknowledgedDouble );
var
ptr_value : PAcknowledgedDouble;
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index > self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
New ( ptr_value );
ptr_value^ := value;
self.list_values.Insert ( index, ptr_value );
end; // procedure TAcknowledgedDoubleList.add ( index : integer; value : TAcknowledgedDouble );
// =============================================================================
// Function : update
// Updates the entry at the specified index
// Parameter : index - the index of the entry to be updated
// entry - the new value of the entry
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
procedure TAcknowledgedDoubleList.update ( index : integer; entry : TAcknowledgedDouble );
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
self.list_values[index] := entry;
end; // procedure TAcknowledgedDoubleList.update ( index : integer; entry : TAcknowledgedDouble );
// =============================================================================
// Function : update
// Updates the double value of the entry at the specified index
// Parameter : index - the index of the entry to be updated
// value - the new double value of the entry
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
procedure TAcknowledgedDoubleList.update ( index : integer; d_value : double );
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
PAcknowledgedDouble(self.list_values[index])^.Value := d_value;
end; // procedure TAcknowledgedDoubleList.update ( index : integer; d_value : double );
// =============================================================================
// Function : update
// Updates the boolean value of the entry at the specified index
// Parameter : index - the index of the entry to be updated
// b_valid - the new boolean value of the entry
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
procedure TAcknowledgedDoubleList.update ( index : integer; b_valid : boolean );
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
PAcknowledgedDouble(self.list_values[index])^.isValid := b_valid;
end; // procedure TAcknowledgedDoubleList.update ( index : integer; b_valid : boolean );
// =============================================================================
// Function : clear
// Clears the contents of the list and frees the memory,
// allocated by the elements of the list.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
procedure TAcknowledgedDoubleList.clear();
var
i : integer;
begin
for i := 0 to self.list_values.Count-1 do
Dispose ( self.list_values.Items[i] );
self.list_values.Clear();
end; // procedure TAcknowledgedDoubleList.clear();
// =============================================================================
// Function : isEmpty
// Tests whether the list is empty or not.
// Parameter : --
// Return : true - the list is empty
// Exceptions : --
// =============================================================================
function TAcknowledgedDoubleList.isEmpty() : boolean;
begin
result := self.Count > 0;
end; // function TAcknowledgedDoubleList.isEmpty() : boolean;
// =============================================================================
// Class : TAcknowledgedDoubleList
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TAcknowledgedDoubleList.Clone() : TMtxCloneableObject;
begin
result := TAcknowledgedDoubleList.create();
TAcknowledgedDoubleList(result).copyFrom ( self );
end; // function TAcknowledgedDoubleList.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
//
// C L A S S TInt64List
//
// =============================================================================
// =============================================================================
// =============================================================================
// Constructor : create
// Creates a new object, initialized with default values.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
constructor TInt64List.create();
begin
self.list_values := TList.Create();
end; // constructor TInt64List.create();
// =============================================================================
// Destructor : destroy
// Frees the memory allocated by this object.
// Parameter : --
// Return : --
// =============================================================================
destructor TInt64List.destroy();
begin
self.clear();
self.list_values.Free();
inherited Destroy();
end; // destructor TInt64List.destroy();
// =============================================================================
// Function : copyFrom
// Copies the contents of list to the calling object.
// Parameter : list - The int64 list to be copied.
// Return : --
// Exceptions : --
// =============================================================================
procedure TInt64List.copyFrom ( list : TInt64List );
var
i : integer;
begin
self.clear(); // Clear the internal list
// If the list to be copied is not assigned, then do nothing. ==> self = empty!
if ( not Assigned ( list ) ) then exit;
// Copy the contents of list to the calling object self
for i := 0 to list.Count-1 do
self.add ( list.get(i) );
end; // procedure TInt64List.copyFrom ( list : TInt64List );
// =============================================================================
// Function : getCount
// Returns the number of elements in the list.
// Parameter : --
// Return : Number of elements in the list
// Exceptions : --
// =============================================================================
function TInt64List.getCount() : integer;
begin
result := self.list_values.Count;
end; // function TInt64List.getCount() : integer;
// =============================================================================
// Function : get
// Returns the element (int64-value) at the specified index.
// Parameter : index - index of the element to be returned
// Return : The element (int64 value) at the specified index.
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
function TInt64List.get ( index : integer ) : int64;
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
// The index is valid ==> return the double value at the specified index
result := PInt64(self.list_values.Items[index])^;
end; // function TInt64List.get ( index : integer ) : int64;
// =============================================================================
// Function : add
// Adds the value at the end of the list.
// The list can contain the same value more than once.
// Parameter : value - the value to be added
// Return : --
// Exceptions : --
// =============================================================================
procedure TInt64List.add ( value : int64 );
var
ptr_value : PInt64;
begin
New ( ptr_value );
ptr_value^ := value;
self.list_values.Add ( ptr_value );
end; // procedure TInt64List.add ( value : int64 );
// =============================================================================
// Function : add
// Adds the value at the specified index in the list.
// The list can contain the same value more than once.
// Parameter : index - the index in the list, at which the value will be added.
// value - the value to be added
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index > number of elements in the list
// =============================================================================
procedure TInt64List.add ( index : integer; value : int64 );
var
ptr_value : PInt64;
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index > self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
New ( ptr_value );
ptr_value^ := value;
self.list_values.Insert ( index, ptr_value );
end; // procedure TInt64List.add ( index : integer; value : int64 );
// =============================================================================
// Function : update
// Updates the entry at the specified index
// Parameter : index - the index of the entry to be updated
// value - the new value of the entry
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
procedure TInt64List.update ( index : integer; value : int64 );
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
PInt64(self.list_values[index])^ := value;
end; // procedure TInt64List.update ( index : integer; value : int64 );
// =============================================================================
// Function : clear
// Clears the contents of the list and frees the memory,
// allocated by the elements of the list.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
procedure TInt64List.clear();
var
i : integer;
begin
for i := 0 to self.list_values.Count-1 do
Dispose ( self.list_values.Items[i] );
self.list_values.Clear();
end; // procedure TInt64List.clear();
// =============================================================================
// Function : isEmpty
// Tests wether the list is empty or not.
// Parameter : --
// Return : true - the list is empty
// Exceptions : --
// =============================================================================
function TInt64List.isEmpty() : boolean;
begin
result := self.Count > 0;
end; // function TInt64List.isEmpty() : boolean;
// =============================================================================
// Class : TInt64List
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TInt64List.Clone() : TMtxCloneableObject;
begin
result := TInt64List.create();
TInt64List(result).copyFrom ( self );
end; // function TInt64List.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
//
// C L A S S TLongwordList (2009-10-05 /gsv/)
//
// =============================================================================
// =============================================================================
// =============================================================================
// Constructor : create
// Creates a new object, initialized with default values.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
constructor TLongwordList.create();
begin
self.list_values := TList.Create();
self.AllowDuplicates := true;
end; // constructor TLongwordList.create();
// =============================================================================
// Destructor : destroy
// Frees the memory allocated by this object.
// Parameter : --
// Return : --
// =============================================================================
destructor TLongwordList.destroy();
begin
self.clear();
self.list_values.Free();
inherited Destroy();
end; // destructor TLongwordList.destroy();
// =============================================================================
// Function : copyFrom
// Copies the contents of list to the calling object.
// Parameter : list - The longword list to be copied.
// Return : --
// Exceptions : --
// =============================================================================
procedure TLongwordList.copyFrom ( list : TLongwordList );
var
i : integer;
begin
self.clear(); // Clear the internal list
// If the list to be copied is not assigned, then do nothing. ==> self = empty!
if ( not Assigned ( list ) ) then exit;
// Copy the contents of list to the calling object self
for i := 0 to list.Count-1 do
self.add ( list.get(i) );
end; // procedure TLongwordList.copyFrom ( list : TLongwordList );
// =============================================================================
// Class : TLongwordList
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TLongwordList.Clone() : TMtxCloneableObject;
begin
result := TLongwordList.create();
TLongwordList(result).copyFrom ( self );
end; // function TLongwordList.Clone() : TMtxCloneableObject;
// =============================================================================
// Function : getCount
// Returns the number of elements in the list.
// Parameter : --
// Return : Number of elements in the list
// Exceptions : --
// =============================================================================
function TLongwordList.getCount() : integer;
begin
result := self.list_values.Count;
end; // function TLongwordList.getCount() : integer;
// =============================================================================
// Function : get
// Returns the element (longword-value) at the specified index.
// Parameter : index - index of the element to be returned
// Return : The element (longword value) at the specified index.
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
function TLongwordList.get ( index : integer ) : longword;
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
// The index is valid ==> return the double value at the specified index
result := PLongword(self.list_values.Items[index])^;
end; // function TLongwordList.get ( index : integer ) : longword;
// =============================================================================
// Function : add
// Adds the value at the end of the list.
// The list can contain the same value more than once.
// Parameter : value - the value to be added
// Return : --
// Exceptions : EObjectAlreadyExist, falls AllowDuplicates = false und
// value bereits in der Liste enthalten ist.
// =============================================================================
procedure TLongwordList.add ( value : longword );
var
ptr_value : PLongword;
begin
// 2009-10-05 /gsv/: Ggf. keine Duplicate zulassen und Exception auslösen
if ( (not self.AllowDuplicates) and self.contains(value) ) then
begin
raise EObjectAlreadyExist.Create ( 'Value 0x' + SysUtils.IntToHex(value,8) + ' has already been contained in the list!' );
end;
New ( ptr_value );
ptr_value^ := value;
self.list_values.Add ( ptr_value );
end; // procedure TLongwordList.add ( value : longword );
// =============================================================================
// Function : add
// Adds the value at the specified index in the list.
// The list can contain the same value more than once.
// Parameter : index - the index in the list, at which the value will be added.
// value - the value to be added
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index > number of elements in the list
// =============================================================================
procedure TLongwordList.add ( index : integer; value : longword );
var
ptr_value : PLongword;
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index > self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
New ( ptr_value );
ptr_value^ := value;
self.list_values.Insert ( index, ptr_value );
end; // procedure TLongwordList.add ( index : integer; value : longword );
// =============================================================================
// Function : update
// Updates the entry at the specified index
// Parameter : index - the index of the entry to be updated
// value - the new value of the entry
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
procedure TLongwordList.update ( index : integer; value : longword );
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
PLongword(self.list_values[index])^ := value;
end; // procedure TLongwordList.update ( index : integer; value : longword );
// =============================================================================
// Function : clear
// Clears the contents of the list and frees the memory,
// allocated by the elements of the list.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
procedure TLongwordList.clear();
var
i : integer;
begin
for i := 0 to self.list_values.Count-1 do
Dispose ( self.list_values.Items[i] );
self.list_values.Clear();
end; // procedure TLongwordList.clear();
// =============================================================================
// Function : isEmpty
// Tests wether the list is empty or not.
// Parameter : --
// Return : true - the list is empty
// Exceptions : --
// =============================================================================
function TLongwordList.isEmpty() : boolean;
begin
result := self.Count > 0;
end; // function TLongwordList.isEmpty() : boolean;
// =============================================================================
// Class : TLongwordList
// Function : contains()
// Prüft, ob ein Longword-Wert in der Liste bereits enthalten ist.
// Parameter : lw - zu prüfender Wert
// Return : TRUE - lw ist in der Liste bereits vorhanden
// FALSE - lw ist in der Liste nicht vorhanden
// Exceptions : --
// First author : 2009-10-05 /gsv/
// History : --
// =============================================================================
function TLongwordList.contains ( lw : longword ) : boolean;
var
i : integer;
begin
// Liste nach dem Wert durchsuchen
for i := 0 to self.Count-1 do
begin
if ( lw = self.get(i) ) then
begin
// Wert gefunden ==> Abbruch
result := true;
exit;
end; // if ( lw = self.get(i) ) then
end; // for i := 0 to self.Count-1 do
// Wert nicht gefunden
result := false;
end; // function TLongwordList.contains ( lw : longword ) : boolean;
// =============================================================================
// =============================================================================
//
// C L A S S TByteList
//
// =============================================================================
// =============================================================================
// =============================================================================
// Constructor : create
// Creates a new object, initialized with default values.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
constructor TByteList.create();
begin
self.list_values := TList.Create();
end; // constructor TByteList.create();
// =============================================================================
// Destructor : destroy
// Frees the memory allocated by this object.
// Parameter : --
// Return : --
// =============================================================================
destructor TByteList.destroy();
begin
self.clear();
self.list_values.Free();
inherited Destroy();
end; // destructor TByteList.destroy();
// =============================================================================
// Function : copyFrom
// Copies the contents of list to the calling object.
// Parameter : list - The byte list to be copied.
// Return : --
// Exceptions : --
// =============================================================================
procedure TByteList.copyFrom ( list : TByteList );
var
i : integer;
begin
self.clear(); // Clear the internal list
// If the list to be copied is not assigned, then do nothing. ==> self = empty!
if ( not Assigned ( list ) ) then exit;
// Copy the contents of list to the calling object self
for i := 0 to list.Count-1 do
self.add ( list.get(i) );
end; // procedure TByteList.copyFrom ( list : TByteList );
// =============================================================================
// Function : getCount
// Returns the number of elements in the list.
// Parameter : --
// Return : Number of elements in the list
// Exceptions : --
// =============================================================================
function TByteList.getCount() : integer;
begin
result := self.list_values.Count;
end; // function TByteList.getCount() : integer;
// =============================================================================
// Function : get
// Returns the element (byte-value) at the specified index.
// Parameter : index - index of the element to be returned
// Return : The element (byte value) at the specified index.
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
function TByteList.get ( index : integer ) : byte;
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
// The index is valid ==> return the double value at the specified index
result := Pbyte(self.list_values.Items[index])^;
end; // function TByteList.get ( index : integer ) : byte;
// =============================================================================
// Function : add
// Adds the value at the end of the list.
// The list can contain the same value more than once.
// Parameter : value - the value to be added
// Return : --
// Exceptions : --
// =============================================================================
procedure TByteList.add ( value : byte );
var
ptr_value : Pbyte;
begin
New ( ptr_value );
ptr_value^ := value;
self.list_values.Add ( ptr_value );
end; // procedure TByteList.add ( value : byte );
// =============================================================================
// Function : add
// Adds the value at the specified index in the list.
// The list can contain the same value more than once.
// Parameter : index - the index in the list, at which the value will be added.
// value - the value to be added
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index > number of elements in the list
// =============================================================================
procedure TByteList.add ( index : integer; value : byte );
var
ptr_value : Pbyte;
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index > self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
New ( ptr_value );
ptr_value^ := value;
self.list_values.Insert ( index, ptr_value );
end; // procedure TByteList.add ( index : integer; value : byte );
// =============================================================================
// Function : update
// Updates the entry at the specified index
// Parameter : index - the index of the entry to be updated
// value - the new value of the entry
// Return : --
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of elements in the list
// =============================================================================
procedure TByteList.update ( index : integer; value : byte );
begin
// When the specified index is invalid, a new exception is thrown!
if ( (index < 0) or (index >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [index, self.Count-1] ) );
Pbyte(self.list_values[index])^ := value;
end; // procedure TByteList.update ( index : integer; value : byte );
// =============================================================================
// Function : clear
// Clears the contents of the list and frees the memory,
// allocated by the elements of the list.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
procedure TByteList.clear();
var
i : integer;
begin
for i := 0 to self.list_values.Count-1 do
Dispose ( self.list_values.Items[i] );
self.list_values.Clear();
end; // procedure TByteList.clear();
// =============================================================================
// Function : isEmpty
// Tests wether the list is empty or not.
// Parameter : --
// Return : true - the list is empty
// Exceptions : --
// =============================================================================
function TByteList.isEmpty() : boolean;
begin
result := self.Count > 0;
end; // function TByteList.isEmpty() : boolean;
// =============================================================================
// Class : TByteList
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TByteList.Clone() : TMtxCloneableObject;
begin
result := TByteList.create();
TByteList(result).copyFrom ( self );
end; // function TByteList.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
//
// C L A S S TFraction
//
// =============================================================================
// =============================================================================
// =============================================================================
// Constructor : create
// Creates a new object, initialized with default values.
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
constructor TFraction.create();
begin
self.i64_numerator := 0;
self.i64_divisor := 1;
self.refreshDecimalFraction();
end; // constructor TFraction.create();
// =============================================================================
// Function : setNumerator
// Sets the numerator of the fraction and recalculates
// the decimal fraction.
// Parameter : new_numerator - the new numerator to set
// Return : --
// Exceptions : --
// =============================================================================
procedure TFraction.setNumerator ( new_numerator : int64 );
begin
self.i64_numerator := new_numerator;
// recalculate the decimal fraction
self.refreshDecimalFraction();
end; // procedure TFraction.setNumerator ( new_numerator : int64 );
// =============================================================================
// Function : setDivisor
// Sets the divisor of the fraction and recalculates
// the decimal fraction.
// Parameter : new_divisor - the new divisor to set
// Return : --
// Exceptions : EInvalidArgument, if new_divisor equals 0.
// =============================================================================
procedure TFraction.setDivisor ( new_divisor : int64 );
begin
if ( new_divisor = 0 ) then raise EInvalidArgument.Create ( 'The divisor cannot be 0!' );
self.i64_divisor := new_divisor;
// recalculate the decimal fraction
self.refreshDecimalFraction();
end; // procedure TFraction.setDivisor ( new_divisor : int64 );
// =============================================================================
// Function : refreshDecimalFraction
// Recalculates/refreshes the corresponding decimal fraction
// Parameter : --
// Return : --
// Exceptions : --
// =============================================================================
procedure TFraction.refreshDecimalFraction();
begin
self.d_decimal_fraction := self.i64_numerator / self.i64_divisor;
end; // procedure TFraction.refreshDecimalFraction();
// =============================================================================
// Function : equals
// Tests wether this object equals to the object fraction.
// Parameter : fraction - the object to compare this object with
// Return : true - this object equals fraction
// Exceptions : --
// =============================================================================
function TFraction.equals ( fraction : TFraction ) : boolean;
begin
if ( fraction = nil ) then begin result := false; exit; end;
if ( fraction = self ) then begin result := true; exit; end;
result := ((self.Numerator = fraction.Numerator) and
(self.Divisor = fraction.Divisor ) ) OR
(self.DecimalFraction = fraction.DecimalFraction);
end; // function TFraction.equals ( fraction : TFraction );
// =============================================================================
// Class : TFraction
// Function : getGCD()
// Berechnet den größten gemeinsamen Teiler von
// Zähler und Nenner und gibt diesen züruck.
// Berechnung des GGTs nach dem Euklidischen Algorithmus
// mit Modulo-Operation.
// Parameter : --
// Return : GGT(numeration,divisor)
// Exceptions : --
// First author : 2009-11-21 /gsv/
// History : --
// =============================================================================
function TFraction.getGCD() : int64;
var
i64_rest, i64_a, i64_b : int64;
begin
i64_a := Abs(Self.Numerator);
i64_b := Abs(Self.Divisor);
// Euklidischer Algorithmus mit Modulo-Operation
repeat
i64_rest := i64_a mod i64_b;
i64_a := i64_b;
i64_b := i64_rest;
until ( i64_rest = 0 );
result := i64_a;
end; // function TFraction.getGCD() : int64;
// =============================================================================
// Class : TFraction
// Function : shorten()
// Bruch kürzen
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2009-11-21 /gsv/
// History : --
// =============================================================================
procedure TFraction.shorten();
var
i64_gcd : int64;
begin
// Größten gemeinsamen Teiler von Zähler und Nenner ermitteln
i64_gcd := self.getGCD();
Numerator := Numerator div i64_gcd;
Divisor := Divisor div i64_gcd;
end; // procedure TFraction.shorten();
// =============================================================================
// Class : TFraction
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TFraction.Clone() : TMtxCloneableObject;
begin
result := TFraction.create();
TFraction(result).Numerator := self.Numerator;
TFraction(result).Divisor := self.Divisor;
TFraction(result).d_decimal_fraction := self.DecimalFraction;
end; // function TFraction.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
//
// C L A S S TBitEntry
//
// =============================================================================
// =============================================================================
// =============================================================================
// Class : TBitListEntry
// Function : create
// Creates a new object of this class, initialized with
// default values.
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2007-07-11 /gsv/
// History : --
// =============================================================================
constructor TBitListEntry.create();
begin
self.create ( '', 0, '', false );
end; // constructor TBitListEntry.create();
// =============================================================================
// Class : TBitListEntry
// Function : create
// Creates a new object of this class.
// Parameter : s_alias - Alias for the symbolic access to this bit,
// e.g. in a BitList (it must be unique!).
// bit - The bit value to be tested,
// e.g. 0x80000000 = Bit31, 0x00000001 = Bit0
// s_text - Textual description of the bit
// inv_logic - The bit has inverted logic?
// (placeholder for the later bit evaluation)
// Return : --
// Exceptions : --
// First author : 2007-07-11 /gsv/
// History : --
// =============================================================================
constructor TBitListEntry.create ( s_alias : string; bit : longword; s_text : string;
inv_logic : boolean = C_DEF_BIT_INV_LOGIC );
begin
self.str_alias := s_alias;
self.lw_bit := bit;
self.str_text := s_text;
self.b_inv_logic := inv_logic;
self.i64_user_data := 0;
end; // constructor TBitListEntry.create();
// =============================================================================
// Class : TBitListEntry
// Function : destroy
// Frees the memory allocated by this object.
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2007-07-11 /gsv/
// History : --
// =============================================================================
destructor TBitListEntry.destroy();
begin
inherited;
end; // destructor TBitListEntry.destroy();
// =============================================================================
// Class : TBitListEntry
// Function : equals
// Tests wether this bit entry equals the bit entry e.
// Parameter : e - the entry to test this with
// Return : true - self equals e
// Exceptions : --
// First author : 2007-07-11 /gsv/
// History : --
// =============================================================================
function TBitListEntry.equals ( e : TBitListEntry ) : boolean;
begin
result := (self.str_alias = e.str_alias) and (self.lw_bit = e.lw_bit);
end; // function TBitListEntry.equals ( e : TBitListEntry ) : boolean;
// =============================================================================
// Class : TBitListEntry
// Function : copyFrom
// Copies the entry in this object.
// No changes are made if the entry is not assigned!
// Parameter : entry - the bit list entry to copy
// Return : --
// Exceptions : --
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
procedure TBitListEntry.copyFrom ( entry : TBitListEntry );
begin
// If the entry is not assigned, then there is nothing more to do.
if ( not Assigned ( entry ) ) then exit;
// Copy the entry in self
self.Alias := entry.Alias;
self.Bit := entry.Bit;
self.Text := entry.Text;
self.UserData := entry.UserData;
self.InvLogic := entry.InvLogic;
end; // procedure TBitListEntry.copyFrom ( entry : TBitListEntry );
// =============================================================================
// Class : TBitListEntry
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TBitListEntry.Clone() : TMtxCloneableObject;
begin
result := TBitListEntry.create();
TBitListEntry(result).copyFrom ( self );
end; // function TBitListEntry.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
//
// C L A S S TBitList
//
// =============================================================================
// =============================================================================
// =============================================================================
// Class : TBitList
// Function : create
// Creates an empty bit list
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2007-07-11 /gsv/
// History : --
// =============================================================================
constructor TBitList.create();
begin
inherited;
self.entries := TList.Create();
end; // constructor TBitList.create();
// =============================================================================
// Class : TBitList
// Function : destroy
// Frees the memory, allocated by this object.
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2007-07-11 /gsv/
// History : --
// =============================================================================
destructor TBitList.destroy();
begin
self.clear();
self.entries.Free;
end; // destructor TBitList.destroy();
// =============================================================================
// Class : TBitList
// Function : indexOf()
// Returns the index of the given bit entry in the list
// Parameter : entry - The entry to get the index of
// Return : index of the given table entry (the index is in range [0...Count) )
// -1, if the entry could not be found
// Exceptions : --
// =============================================================================
function TBitList.indexOf ( entry : TBitListEntry ) : integer;
var
i : integer;
begin
result := -1; // For the case that the entry does not exist
for i := 0 to self.entries.Count-1 do
begin
// The entry has been found?
if ( TBitListEntry(self.entries.Items[i]).equals ( entry ) ) then
begin
result := i;
exit;
end;
end; // for i := 0 to self.entries.Count-1 do
end; // function TBitList.indexOf();
// =============================================================================
// Class : TBitList
// Function : getCount
// Returns the number of entries, currently contained in the list.
// Parameter : --
// Return : see above
// Exceptions : --
// First author : 2007-07-11 /gsv/
// History : --
// =============================================================================
function TBitList.getCount() : integer;
begin
result := self.entries.Count;
end; // function TBitList.getCount() : integer;
// =============================================================================
// Class : TBitList
// Function : isEmpty
// Tests wether the list is empty or not.
// Parameter : --
// Return : true - the list is empty
// Exceptions : --
// First author : 2007-07-11 /gsv/
// History : --
// =============================================================================
function TBitList.isEmpty() : boolean;
begin
result := self.getCount() <= 0;
end; // function TBitList.isEmpty() : boolean;
// =============================================================================
// Class : TBitList
// Function : clear
// Clears the list, the contents will be deleted
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2007-07-11 /gsv/
// History : --
// =============================================================================
procedure TBitList.clear();
var
i : integer;
begin
for i := 0 to self.entries.Count-1 do
begin
TBitListEntry(entries[i]).Free();
end;
self.entries.Clear();
end; // procedure TBitList.clear();
// =============================================================================
// Class : TBitList
// Function : add
// Adds the given entry to the table.
// This function does nothing,
// if the table already contains the given entry!
// Parameter : entry - The entry to add.
// Return : --
// Exceptions : --
// First author : 2007-07-11 /gsv/
// History : --
// =============================================================================
procedure TBitList.add ( entry : TBitListEntry );
begin
// if the entry is not assigned, then there is nothing more to do here!
if ( not Assigned ( entry ) ) then exit;
// The entry will be added to the table, only if the table does not yet contain it!
if ( not self.contains(entry) ) then
begin
// Add the entry to the table
self.entries.Add ( entry );
end; // if ( not self.contains(entry) ) then
end; // procedure TBitList.add();
// =============================================================================
// Class : TBitList
// Function : add
// Adds the given entry to the table.
// This function does nothing,
// if the table already contains the given entry!
// Parameter : alias - The alias of the entry to add
// bit - The bit of the entry to add
// text - The text of the entry to add
// inv_logic - Placeholder: The bit will be evaluated as
// "normal" or inverted logic.
// Return : --
// Exceptions : --
// First author : 2007-07-11 /gsv/
// History : --
// =============================================================================
procedure TBitList.add ( alias : string; bit : longword; text : string;
inv_logic : boolean = C_DEF_BIT_INV_LOGIC );
var
entry : TBitListEntry;
begin
entry := TBitListEntry.create ( alias, bit, text, inv_logic );
self.add ( entry );
end; // procedure TBitList.add ( alias : string; bit : longword; text : string );
// =============================================================================
// Class : TBitList
// Function : delete()
// Removes the given entry from the list.
// This function does nothing,
// if the table does not contain the given entry!
// Parameter : entry - The entry to be removed.
// Return : The table entry with the given alias.
// Exceptions : EObjectNotExist, if there is no entry with the given alias.
// =============================================================================
procedure TBitList.delete ( entry : TBitListEntry );
var
tbe : TBitListEntry;
i : integer;
begin
// search for the given entry
for i := 0 to self.entries.Count-1 do
begin
tbe := TBitListEntry ( self.entries.Items[i] );
// the given entry has been found?
if ( tbe.equals ( entry ) ) then
begin
self.entries.Delete ( i );
exit;
end; // if ( tbe.equals ( entry ) ) then
end; // for i := 0 to self.entries.Count-1 do
// The searched object does not exist
raise EObjectNotExist.Create ( Format ( 'Bit %s (0x%s) does not exist!', [entry.Alias, SysUtils.IntToHex(entry.Bit, 8)] ) );
end; // procedure TBitList.delete();
// =============================================================================
// Class : TBitList
// Function : Returns the entry at index inx.
//
// Parameter : inx - the index of the entry to be returned
// Return : see above
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of table entries
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
function TBitList.getEntry ( inx : integer ) : TBitListEntry;
begin
if ( (inx < 0) or (inx >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [inx, self.Count-1] ) );
result := TBitListEntry ( self.entries.Items[inx] );
end; // function TBitList.getEntry ( inx : integer ) : TBitListEntry;
// =============================================================================
// Class : TBitList
// Function : getByAlias()
// Returns the entry with the given alias.
// Parameter : alias - The alias of the entry to search for.
// Return : The bit list entry with the given alias.
// Exceptions : EObjectNotExist, if there is no entry with the given alias.
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
function TBitList.getByAlias ( alias : string ) : TBitListEntry;
var
entry : TBitListEntry;
i : integer;
begin
// search for the given entry
for i := 0 to self.entries.Count-1 do
begin
entry := TBitListEntry ( self.entries.Items[i] );
// the given entry has been found?
if ( entry.Alias = alias ) then
begin
result := entry;
exit;
end; // if ( entry.Alias = alias ) then
end; // for i := 0 to self.entries.Count-1 do
// the entry was not found ==> throw new exception
raise EObjectNotExist.Create ( MtxWideFormat ( 'Entry alias="%s" does not exist!', [alias] ) );
end; // function TBitList.getByAlias();
// =============================================================================
// Class : TBitList
// Function : getByBit
// Returns the entry with the given bit.
// Parameter : bit - The bit of the entry to search for.
// Return : The list entry with the given bit.
// Exceptions : EObjectNotExist, if there is no entry with the given bit.
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
function TBitList.getByBit ( bit : longword ) : TBitListEntry;
var
entry : TBitListEntry;
i : integer;
begin
// search for the given entry
for i := 0 to self.entries.Count-1 do
begin
entry := TBitListEntry ( self.entries.Items[i] );
// the given entry has been found?
if ( entry.Bit = bit ) then
begin
result := entry;
exit;
end; // if ( entry.Bit = bit ) then
end; // for i := 0 to self.entries.Count-1 do
// the entry was not found ==> throw new exception
raise EObjectNotExist.Create ( MtxWideFormat ( 'Entry bit=0x%x does not exist!', [bit] ) );
end; // function TBitList.getByBit()
// =============================================================================
// Class : TBitList
// Function : getByText
// Returns the entry with the given text.
// Parameter : text - The text of the entry to search for.
// Return : The list entry with the given text.
// Exceptions : EObjectNotExist, if there is no entry with the given text.
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
function TBitList.getByText ( text : string ) : TBitListEntry;
var
entry : TBitListEntry;
i : integer;
begin
// search for the given entry
for i := 0 to self.entries.Count-1 do
begin
entry := TBitListEntry ( self.entries.Items[i] );
// the given entry has been found?
if ( entry.Text = text ) then
begin
result := entry;
exit;
end; // if ( entry.Text = text ) then
end; // for i := 0 to self.entries.Count-1 do
// the entry was not found ==> throw new exception
raise EObjectNotExist.Create ( MtxWideFormat ( 'Entry text="%s" does not exist!', [text] ) );
end; // function TBitList.getByText()
// =============================================================================
// Class : TBitList
// Function : contains
// Tests whether the list contains the given entry.
// Parameter : entry - The entry to be tested
// Return : true - The list contains the given entry.
// false - The list does not contain the given entry.
// Exceptions : --
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
function TBitList.contains ( entry : TBitListEntry ) : boolean;
begin
result := (self.indexOf(entry) >= 0);
end; // function TBitList.contains()
// =============================================================================
// Class : TBitList
// Function : copyFrom
// This function copies the object list in this object.
// If list is not assigned, nothing will be done!
// Parameter : list - the list to copy
// Return : --
// Exceptions : --
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
procedure TBitList.copyFrom ( list : TBitList );
var
i : integer;
entry : TBitListEntry;
begin
// There is nothing more to do, when list is not assigned!
if ( not Assigned(list) ) then exit;
// first clear the items of this object
self.clear();
// copy the list entries
for i := 0 to list.entries.Count-1 do
begin
entry := TBitListEntry.create();
entry.copyFrom ( TBitListEntry(list.entries.Items[i]) );
self.Add ( entry );
end; // for i := 0 to list.entries.Count-1 do
end; // procedure TBitList.copyFrom()
// =============================================================================
// Class : TBitList
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TBitList.Clone() : TMtxCloneableObject;
begin
result := TBitList.create();
TBitList(result).copyFrom ( self );
end; // function TBitList.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
//
// C L A S S TMaskedTableList
//
// =============================================================================
// =============================================================================
// =============================================================================
// Class : TMaskedTableList
// Function : create
// Creates an empty list
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
constructor TMaskedTableList.create();
begin
// 2013-07-30 /gsv/: Umstellung von TList auf TObjectList.
// Dadurch wird der Speicherplatz beim Löschen der Einträge automatisch freigegeben.
self.entries := TObjectList.Create();
self.entries.OwnsObjects := true;
end; // constructor TMaskedTableList.create();
// =============================================================================
// Class : TMaskedTableList
// Function : destroy
// Frees the memory, allocated by this object.
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
destructor TMaskedTableList.destroy();
begin
self.entries.Free;
end; // destructor TMaskedTableList.destroy();
// =============================================================================
// Class : TMaskedTableList
// Function : clear
// Clears the contents of this list.
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
procedure TMaskedTableList.clear();
begin
self.entries.Clear();
end; // procedure TMaskedTableList.clear();
// =============================================================================
// Class : TMaskedTableList
// Function : add
// Adds the table to the list
// Parameter : table - the table to be add
// Return : --
// Exceptions : --
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
procedure TMaskedTableList.add ( table : TMaskedTable );
begin
self.entries.Add ( table );
end; // procedure TMaskedTableList.add ( table : TMaskedTable );
// =============================================================================
// Class : TMaskedTableList
// Function : getCount
// Returns the number of elements in the list.
// Parameter : --
// Return : number of parameters currently contained in the list
// Exceptions : --
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
function TMaskedTableList.getCount() : integer;
begin
result := self.entries.Count;
end; // function TMaskedTableList.getCount() : integer;
// =============================================================================
// Class : TMaskedTableList
// Function : getTable
// Returns the table at index inx
// Parameter : inx - index of the table to return
// Return : the table at index inx
// Exceptions : EIndexOutOfBounds, if the specified index is invalid, i.e.
// index < 0 or index >= number of table entries
// First author : 2007-07-13 /gsv/
// History : --
// =============================================================================
function TMaskedTableList.getTable ( inx : integer ) : TMaskedTable;
begin
if ( (inx < 0) or (inx >= self.Count) ) then
raise EIndexOutOfBounds.create ( format ( 'The index %d is not in range [0...%d]!', [inx, self.Count-1] ) );
result := TMaskedTable ( self.entries.Items[inx] );
end; // function TMaskedTableList.getTable ( inx : integer ) : TMaskedTable;
// =============================================================================
// Class : TMaskedTableList
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function TMaskedTableList.Clone() : TMtxCloneableObject;
var
i : integer;
begin
result := TMaskedTableList.create();
for i := 0 to self.Count-1 do
begin
TMaskedTableList(result).add ( TMaskedTable ( self.getTable(i).Clone() ) );
end;
end; // function TMaskedTableList.Clone() : TMtxCloneableObject;
// =============================================================================
// =============================================================================
//
// K L A S S E TOszCluster
//
// =============================================================================
// =============================================================================
// =============================================================================
// Class : TOszCluster
// Function : create()
// Konstruktor: Neues Objekt mit Default-Werten erzeugen
// Parameter : --
// Return : --
// Exceptions : --
// First author : 2008-11-06 /she/
// History : --
// =============================================================================
constructor TOszCluster.Create();
begin
self.iChannel := 0;
self.iCluster := 0;
self.str_answer := '';
StringOfChar( '0', 16 * 8 ); // 16 * 8-stellige Null
end; // constructor TOszCluster.Create();
// =============================================================================
// Class : TOszCluster
// Function : copyFrom
// Kopierfunktion: Kopiert osz in self
// Parameter : osz - zu kopierendes Objekt in self
// Return : --
// Exceptions : --
// First author : 2008-11-13 /she/
// History : --
// =============================================================================
procedure TOszCluster.copyFrom ( const osz : TOszCluster );
begin
self.iChannel := osz.iChannel;
self.iCluster := osz.iCluster;
self.str_answer := osz.str_answer;
end; // procedure TOszCluster.copyFrom ( const osz : TOszCluster );
// =============================================================================
// Class : TOszCluster
// Function : getlong()
// Datentwort aus Cluster-Struktur auslesen
// Parameter : i : Index des Datenwortes (0...15)
// Return : Datenlongwort
// Exceptions : ERangeError, falls ein Fehler bei der Konvertierung auftritt.
// First author : 2008-11-06 /she/
// History : --
// =============================================================================
function ToszCluster.getlong ( i : integer ) : longword;
var
code: integer;
begin
Val( '$' + Copy( self.Answer, 1 + 8*i, 8 ), Result, code );
if ( code <> 0 ) then
begin
raise ERangeError.Create ( 'fatal error ToszCluster.getlong' );
Result := 0;
end;
end; // function ToszCluster.getlong ( i : integer ) : longword;
// =============================================================================
// Class : ToszCluster
// Function : Clone()
// Erstellt eine neue Kopie des Objektes
// Hinweis: Der Aufrufer muss sich um die Freigabe des
// Objektes kümmern!
// Parameter : --
// Return : neue Kopie von self
// Exceptions : --
// First author : 2014-08-21 /gsv/
// History : --
// =============================================================================
function ToszCluster.Clone() : TMtxCloneableObject;
begin
result := ToszCluster.create();
ToszCluster(result).copyFrom ( self );
end; // function ToszCluster.Clone() : TMtxCloneableObject;
constructor TMtxGUICODataBase.Create();
begin
inherited Create();
self.i64Value := 0;
self.i64ValueBackup := 0;
self.i64ValueOI := 0;
self.bHasOIValue := false;
self.bReadCyclic := false;
self.bReadORValue := true;
self.bReadOIValue := false;
self.bRestoreOldValue := true;
end;
procedure TMtxGUICODataBase.copyFrom ( obj : TMtxGUICODataBase );
begin
if ( not Assigned ( obj ) ) then exit;
self.Value := obj.Value;
self.ValueBackup := obj.Value;
self.ValueOI := obj.Value;
self.HasOIValue := obj.HasOIValue;
self.ReadCyclic := obj.ReadCyclic;
self.ReadORValue := obj.ReadORValue;
self.ReadOIValue := obj.ReadOIValue;
self.RestoreOldValue := obj.RestoreOldValue;
end;
constructor TMtxGUICODataSingleCO.Create();
begin
inherited Create();
self.sName := '';
end;
procedure TMtxGUICODataSingleCO.copyFrom ( obj : TMtxGUICODataBase );
begin
if ( not Assigned ( obj ) ) then exit;
inherited copyFrom ( obj );
if ( obj is TMtxGUICODataSingleCO ) then
begin
self.Name := TMtxGUICODataSingleCO(obj).Name;
end;
end;
constructor TMtxGUICODataInt64.Create();
begin
inherited Create();
self.sNameHigh := '';
self.sNameLow := '';
end;
procedure TMtxGUICODataInt64.copyFrom ( obj : TMtxGUICODataBase );
begin
if ( not Assigned ( obj ) ) then exit;
inherited copyFrom ( obj );
if ( obj is TMtxGUICODataInt64 ) then
begin
self.NameHigh := TMtxGUICODataInt64(obj).NameHigh;
self.NameLow := TMtxGUICODataInt64(obj).NameLow;
end;
end;
constructor TMtxGUICODataSimpleMultiCO.Create();
begin
self.FPointerCOName := '';
self.FPointerCOMin := 0;
self.FPointerCOMax := 0;
self.FPointerCOVal := 0;
self.FDataCOInfo := TMtxGUICODataSingleCO.Create();
self.FDataCOValues := TInt64List.create();
self.FDataCOValuesBackup := TInt64List.create();
inherited;
end;
procedure TMtxGUICODataSimpleMultiCO.copyFrom ( obj : TMtxGUICODataSimpleMultiCO );
begin
if ( not Assigned ( obj ) ) then exit;
self.PointerCOName := obj.PointerCOName;
self.PointerCOVal := obj.PointerCOVal;
self.PointerCOMin := obj.PointerCOMin;
self.PointerCOMax := obj.PointerCOMax;
self.DataCOInfo.copyFrom ( obj.DataCOInfo );
self.DataCOValues.copyFrom ( obj.DataCOValues );
self.DataCOValuesBackup.copyFrom ( obj.DataCOValuesBackup );
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentBase
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentBase.Create ( AOwner : TComponent );
begin
FOnReset := nil;
FOnCalcValueFromServo := nil;
FEnabled := true;
FWriteAccessRunning := false;
FAssociatedComponents := TMtxExtCOAssociatedComponentList.Create(); // Liste mit den Komponenten, die mit diesem KO verlinkt sind.
inherited Create ( AOwner );
end;
destructor TMtxCOComponentBase.Destroy();
begin
self.FAssociatedComponents.Free();
inherited Destroy();
end;
// Berechnung Servo --> GUI (==> COValue anzeigen)
procedure TMtxCOComponentBase.calcValueFromServo();
begin
if ( Assigned ( FOnCalcValueFromServo ) ) then
begin
FOnCalcValueFromServo ( self );
end;
end;
// Komponente zurücksetzen (bei win_reset()).
procedure TMtxCOComponentBase.reset();
begin
if ( Assigned ( FOnReset ) ) then
begin
FOnReset ( self );
end;
end;
// Getter / Setter für die Enabled-Eigenschaft
function TMtxCOComponentBase.GetEnabled() : boolean;
begin
result := FEnabled;
end;
procedure TMtxCOComponentBase.SetEnabled ( b_on : boolean );
begin
FEnabled := b_on;
end;
// Getter/Setter für die Property WriteAccessRunning
function TMtxCOComponentBase.getWriteAccessRunning() : boolean;
begin
result := FWriteAccessRunning;
end;
procedure TMtxCOComponentBase.setWriteAccessRunning ( b : boolean );
begin
FWriteAccessRunning := b;
end;
// Getter/Setter für die Property AssociatedComponents
function TMtxCOComponentBase.getAssociatedComponents() : TMtxExtCOAssociatedComponentList;
begin
result := self.FAssociatedComponents;
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentSingleCOBase
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentSingleCOBase.Create ( AOwner : TComponent );
begin
// KO-Struktur intialisieren + weitere Initialisierungen vor dem inherited Konstruktor,
self.FCOData := TMtxGUICODataSingleCO.Create();
inherited Create ( AOwner );
end;
destructor TMtxCOComponentSingleCOBase.Destroy();
begin
FCOData.Free();
inherited Destroy();
end;
// Getter/Setter für die Property COData
function TMtxCOComponentSingleCOBase.getCOData() : TMtxGUICODataSingleCO;
begin
result := FCOData;
end;
procedure TMtxCOComponentSingleCOBase.setCOData ( obj : TMtxGUICODataSingleCO );
begin
self.FCOData.copyFrom ( obj );
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentSingleCOReadWrite
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentSingleCOReadOnly.Create ( AOwner : TComponent );
begin
inherited Create ( AOwner );
self.FCOData.RestoreOldValue := false;
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentSingleCOReadWrite
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentSingleCOReadWrite.Create ( AOwner : TComponent );
begin
self.b_is_changed := false;
self.FOnCalcValueToServo := nil;
inherited Create ( AOwner );
end;
// Getter / Setter der Property is_changed
function TMtxCOComponentSingleCOReadWrite.getIsChanged() : boolean;
begin
result := self.b_is_changed;
end;
procedure TMtxCOComponentSingleCOReadWrite.setIsChanged ( b : boolean );
begin
self.b_is_changed := b;
end;
// Berechnung GUI --> Servo (==> COValue berechnen/aktualisieren)
procedure TMtxCOComponentSingleCOReadWrite.calcValueToServo();
begin
if ( Assigned ( FOnCalcValueToServo ) ) then
begin
FOnCalcValueToServo ( self );
end;
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentControlCOBase
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentControlCOBase.Create ( AOwner : TComponent );
begin
// KO-Struktur intialisieren + weitere Initialisierungen vor dem inherited Konstruktor,
self.FCOData := TMtxGUICODataSingleCO.Create();
inherited Create ( AOwner );
end;
destructor TMtxCOComponentControlCOBase.Destroy();
begin
FCOData.Free();
inherited Destroy();
end;
// Getter/Setter für die Property COData
function TMtxCOComponentControlCOBase.getCOData() : TMtxGUICODataSingleCO;
begin
result := FCOData;
end;
procedure TMtxCOComponentControlCOBase.setCOData ( obj : TMtxGUICODataSingleCO );
begin
self.FCOData.copyFrom ( obj );
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentControlCOReadOnly
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentControlCOReadOnly.Create ( AOwner : TComponent );
begin
inherited Create ( AOwner );
self.FCOData.RestoreOldValue := false;
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentControlCOReadWrite
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentControlCOReadWrite.Create ( AOwner : TComponent );
begin
self.b_is_changed := false;
self.FOnCalcValueToServo := nil;
inherited Create ( AOwner );
end;
// Getter / Setter der Property is_changed
function TMtxCOComponentControlCOReadWrite.getIsChanged() : boolean;
begin
result := self.b_is_changed;
end;
procedure TMtxCOComponentControlCOReadWrite.setIsChanged ( b : boolean );
begin
self.b_is_changed := b;
end;
// Berechnung GUI --> Servo (==> COValue berechnen/aktualisieren)
procedure TMtxCOComponentControlCOReadWrite.calcValueToServo();
begin
if ( Assigned ( FOnCalcValueToServo ) ) then
begin
FOnCalcValueToServo ( self );
end;
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentInt64COBase
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentInt64COBase.Create ( AOwner : TComponent );
begin
// KO-Struktur intialisieren + weitere Initialisierungen vor dem inherited Konstruktor,
self.FCOData := TMtxGUICODataInt64.Create();
inherited Create ( AOwner );
end;
destructor TMtxCOComponentInt64COBase.Destroy();
begin
FCOData.Free();
inherited Destroy();
end;
// Getter/Setter für die Property COData
function TMtxCOComponentInt64COBase.getCOData() : TMtxGUICODataInt64;
begin
result := FCOData;
end;
procedure TMtxCOComponentInt64COBase.setCOData ( obj : TMtxGUICODataInt64 );
begin
self.FCOData.copyFrom ( obj );
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentInt64COReadOnly
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentInt64COReadOnly.Create ( AOwner : TComponent );
begin
inherited Create ( AOwner );
self.FCOData.RestoreOldValue := false;
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentInt64COReadWrite
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentInt64COReadWrite.Create ( AOwner : TComponent );
begin
self.b_is_changed := false;
self.FOnCalcValueToServo := nil;
inherited Create ( AOwner );
end;
// Getter / Setter der Property is_changed
function TMtxCOComponentInt64COReadWrite.getIsChanged() : boolean;
begin
result := self.b_is_changed;
end;
procedure TMtxCOComponentInt64COReadWrite.setIsChanged ( b : boolean );
begin
self.b_is_changed := b;
end;
// Berechnung GUI --> Servo (==> COValue berechnen/aktualisieren)
procedure TMtxCOComponentInt64COReadWrite.calcValueToServo();
begin
if ( Assigned ( FOnCalcValueToServo ) ) then
begin
FOnCalcValueToServo ( self );
end;
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentSimpleMultiCOBase
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentSimpleMultiCOBase.Create ( AOwner : TComponent );
begin
// KO-Struktur intialisieren + weitere Initialisierungen vor dem inherited Konstruktor,
self.FCOData := TMtxGUICODataSimpleMultiCO.Create();
inherited Create ( AOwner );
end;
destructor TMtxCOComponentSimpleMultiCOBase.Destroy();
begin
FCOData.Free();
inherited Destroy();
end;
// Getter/Setter für die Property COData
function TMtxCOComponentSimpleMultiCOBase.getCOData() : TMtxGUICODataSimpleMultiCO;
begin
result := FCOData;
end;
procedure TMtxCOComponentSimpleMultiCOBase.setCOData ( obj : TMtxGUICODataSimpleMultiCO );
begin
self.FCOData.copyFrom ( obj );
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxCOComponentSimpleMultiCOReadWrite
//
// =============================================================================
// =============================================================================
constructor TMtxCOComponentSimpleMultiCOReadWrite.Create ( AOwner : TComponent );
begin
self.b_is_changed := false;
self.FOnCalcValueToServo := nil;
inherited Create ( AOwner );
end;
// Getter / Setter der Property is_changed
function TMtxCOComponentSimpleMultiCOReadWrite.getIsChanged() : boolean;
begin
result := self.b_is_changed;
end;
procedure TMtxCOComponentSimpleMultiCOReadWrite.setIsChanged ( b : boolean );
begin
self.b_is_changed := b;
end;
// Berechnung GUI --> Servo (==> COValue berechnen/aktualisieren)
procedure TMtxCOComponentSimpleMultiCOReadWrite.calcValueToServo();
begin
if ( Assigned ( FOnCalcValueToServo ) ) then
begin
FOnCalcValueToServo ( self );
end;
end;
constructor TMtxGUICheckedInfo.Create();
begin
inherited Create();
self.FMask := 0;
self.FBitfieldChecked := 0;
self.FBitfieldUnchecked := 0;
end;
// =============================================================================
// Class : TMtxStringList
// Function : findString()
// Suchfunktion: Nach einem beliebigen String suchen
// Parameter : str - String, nach dem gesucht wird
// i_inx - Rückgabe: Index, an dem der gesuchte String gefunden wurde.
// Return : true - String gefunden
// Exceptions : --
// First author : 2016-01-25 /gsv/
// History : --
// =============================================================================
function TMtxStringList.findString ( str : string; var i_inx : integer ) : boolean;
var
i : integer;
begin
for i:= 0 to self.Count-1 do
begin
if ( StringCompareICase ( self.Strings[i], str ) ) then
begin
// Eintrag gefunden ==> Funktion beenden
i_inx := i;
result := true;
exit;
end;
end;
// Eintrag nicht gefunden
result := false;
end; // function TMtxStringList.findString ( ... )
function TMtxStringList.getNextLine ( var i_inx : integer; var s_line : string ) : boolean;
var
i : integer;
s : string;
begin
for i := i_inx+1 to self.Count-1 do
begin
s := self.Strings[i];
if ( not (self.isEmptyString ( s ) or
self.isCommentLine ( s )) ) then
begin
i_inx := i;
s_line := s;
result := true;
exit;
end;
end;
// Liste zu Ende
result := false;
end; // function TMtxStringList.getNextLine ( var i_inx : integer ) : boolean;
function TMtxStringList.getNextLineUntilSectionBegin ( var i_inx : integer; var s_line : string ) : boolean;
var
i : integer;
s : string;
begin
i := i_inx;
result := getNextLine ( i, s );
if ( result ) then
begin
result := not isSectionBegin ( s );
if ( result ) then
begin
i_inx := i;
s_line := s;
end;
end;
end; // function TMtxStringList.getNextLineUntilSectionBegin ( var i_inx : integer; var s_line : string ) : boolean;
function TMtxStringList.isEmptyString ( str : string ) : boolean;
begin
result := Trim(str) = '';
end; // function TMtxStringList.isEmptyString ( str : string ) : boolean;
function TMtxStringList.isCommentLine ( str : string ) : boolean;
begin
if ( self.isEmptyString ( str ) ) then
begin
result := false;
end
else
begin
result := str[1] = C_CHAR_COMMENT_LINE;
end;
end; // function TMtxStringList.isCommentLine ( str : string ) : boolean;
function TMtxStringList.isSectionBegin ( str : string ) : boolean;
begin
if ( self.isEmptyString ( str ) ) then
begin
result := false;
end
else
begin
result := str[1] = '[';
end;
end; // function TMtxStringList.isSectionBegin ( str : string ) : boolean;
procedure TMtxStringList.addNewLine();
begin
self.Add ( '' );
end;
{$IFDEF DELPHI_XE_UP}
constructor TMtxThread.Create();
begin
inherited Create();
end;
{$ENDIF}
constructor TMtxThread.Create ( CreateSuspended: Boolean );
begin
FSuspendEvent := TEvent.Create();
FCreateSuspendedMtx := CreateSuspended;
if ( FCreateSuspendedMtx ) then FSuspendEvent.ResetEvent()
else FSuspendEvent.SetEvent();
inherited Create ( CreateSuspended );
end;
destructor TMtxThread.Destroy();
begin
inherited;
FSuspendEvent.Free();
end;
{$IFDEF DELPHI_XE_UP}
procedure TMtxThread.TerminatedSet();
begin
inherited;
self.FSuspendEvent.SetEvent();
end;
{$ENDIF}
procedure TMtxThread.SuspendWork();
begin
self.FSuspendEvent.ResetEvent();
end;
procedure TMtxThread.ResumeWork();
begin
//if ( not isSuspended() ) then exit;
self.FSuspendEvent.SetEvent();
// Falls der Thread als Suspenden erstellt wurde, dann diesen über die
// Start-Funktion initial anstarten.
if ( FCreateSuspendedMtx ) then
begin
FCreateSuspendedMtx := false;
{$IFDEF DELPHI_XE_UP}
self.Start();
{$ELSE}
while ( self.Suspended ) do self.Resume();
{$ENDIF}
end;
end;
procedure TMtxThread.CheckHandleSuspended();
begin
{
if ( WaitForSingleObject( FSuspendEvent, INFINITE ) = WAIT_OBJECT_0 ) then
begin
FSuspendEvent.ResetEvent();
end;
}
FSuspendEvent.WaitFor ( INFINITE );
//FSuspendEvent.ResetEvent();
end;
function TMtxThread.isSuspended() : boolean;
begin
result := self.Suspended;
end;
// =============================================================================
// =============================================================================
//
// K L A S S E TMtxWindowPositionEntry
//
// =============================================================================
// =============================================================================
constructor TMtxWindowPositionEntry.Create();
begin
self.FWinName := '';
self.FLeft := C_MTX_DEF_WIN_POS_LEFT;
self.FTOP := C_MTX_DEF_WIN_POS_TOP;
end;
function TMtxWindowPositionEntryComparer.Compare ( const Left, Right: TMtxWindowPositionEntry ): Integer;
begin
result := CompareText ( Left.WinName, Right.WinName );
end;
constructor TMtxWindowPositionList.Create();
begin
inherited Create ( TMtxWindowPositionEntryComparer.Create(), true );
end;
function TMtxWindowPositionList.getByName ( AWinName : string; var AEntry : TMtxWindowPositionEntry ) : boolean;
var
i : integer;
entry : TMtxWindowPositionEntry;
begin
for i := 0 to self.Count-1 do
begin
entry := self.Items[i];
if ( StringCompareICase ( entry.FWinName, AWinName ) ) then
begin
// Eintrag gefunden
AEntry := entry;
result := true;
exit;
end;
end; // for i := 0 to self.Count-1 do
// Eintrag nicht gefunden
result := false;
end; // function TMtxWindowPositionList.getByName ( AWinName : string; var AEntry : TMtxWindowPositionEntry ) : boolean;
function TMtxWindowPositionList.getWinPosByName ( AWinName : string; var ALeft, ATop : integer ) : boolean;
var
entry : TMtxWindowPositionEntry;
begin
result := getByName ( AWinName, entry );
if ( result ) then
begin
// Eintrag gefunden
ALeft := entry.Left;
ATop := entry.Top;
end
else
begin
// Eintrag nicht gefunden ==> Default Window-Position zurückgeben
ALeft := C_MTX_DEF_WIN_POS_LEFT;
ATop := C_MTX_DEF_WIN_POS_TOP;
end;
end; // function TMtxWindowPositionList.getWinPosByName ( AWinName : string; var ALeft, ATop : integer ) : boolean;
procedure TMtxWindowPositionList.updateWinPos ( AWinName : string; ALeft, ATop : integer );
var
entry : TMtxWindowPositionEntry;
b_found : boolean;
begin
b_found := getByName ( AWinName, entry );
if ( b_found ) then
begin
// Entrag existiert bereits
entry.Left := ALeft;
entry.Top := ATop;
end
else
begin
// Eintrag existiert nicht ==> Neu anlegen
entry := TMtxWindowPositionEntry.Create();
entry.WinName := AWinName;
entry.Left := ALeft;
entry.Top := ATop;
self.Add ( entry );
end;
end; // procedure TMtxWindowPositionList.updateWinPos ( AWinName : string; ALeft, ATop : integer );
procedure TMtxWindowPositionList.Add ( AWinName : string; ALeft, ATop : integer );
var
entry : TMtxWindowPositionEntry;
begin
// Falls der Eintrag bereits existiert, dann dieses nicht nochmal hinzufügen.
if ( self.getByName ( AWinName, entry ) ) then
begin
exit;
end;
entry := TMtxWindowPositionEntry.Create();
entry.WinName := AWinName;
entry.Left := ALeft;
entry.Top := ATop;
self.Add ( entry );
end;
function TMtxExtCOAssociatedComponentComparer.Compare ( const Left, Right: TWinControl ): Integer;
begin
result := CompareText ( Left.Name, Right.Name );
end;
constructor TMtxExtCOAssociatedComponentList.Create();
begin
// Diese Liste enthält nur Referenzen auf GUI-Komponenten,
// die anderweitig freigegeben werden.
inherited Create ( TMtxExtCOAssociatedComponentComparer.Create(), false );
end;
end.
|
unit ThreadIndexUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, ZAbstractRODataset,
ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit,
cxLabel, cxProgressBar, System.Math;
type
TOnError = procedure(AError: string) of object;
TOnFinish = procedure of object;
TOnMessage = procedure(AText: string) of object;
TOnAddLog = procedure(AText: string) of object;
TOnProgress = procedure(AText: string; AFunctionRecordPos, AFunctionRecordMax : Integer) of object;
// Поток для Переноса функций
TIndexThread = class(TThread)
private
{ Private declarations }
FHostName: String;
FDatabase: String;
FUser: String;
FPassword: String;
FPort: Integer;
FLibraryLocation: String;
FZConnection: TZConnection;
FZQueryTable: TZQuery;
FZQueryExecute: TZQuery;
FError: String;
FOnError: TOnError;
FOnFinish: TOnFinish;
FOnMessage: TOnMessage;
FOnAddLog: TOnAddLog;
FOnProgress: TOnProgress;
protected
procedure Execute; override;
property OnError: TOnError read FOnError write FOnError;
property OnFinish: TOnFinish read FOnFinish write FOnFinish;
property OnMessage: TOnMessage read FOnMessage write FOnMessage;
property OnAddLog: TOnAddLog read FOnAddLog write FOnAddLog;
property OnProgress: TOnProgress read FOnProgress write FOnProgress;
end;
TThreadIndexForm = class(TForm)
PanelMain: TPanel;
Panel1: TPanel;
Button1: TButton;
pbAll: TcxProgressBar;
lblActionTake: TcxLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SnapshotThreadError(AError: string);
procedure SnapshotThreadFinish;
procedure SnapshotThreadMessage(AText: string);
procedure SnapshotThreadAddLog(AText: string);
procedure SnapshotThreadProgress(AText: string; AFunctionRecordPos, AFunctionRecordMax : Integer);
private
{ Private declarations }
FFunctionThread : TIndexThread;
FError: String;
public
{ Public declarations }
property Error: String read FError;
end;
implementation
{$R *.dfm}
Uses MainUnit, UnitConst;
procedure TThreadIndexForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if not FFunctionThread.Finished then
begin
if FFunctionThread.Terminated then Action := caNone
else if MessageDlg('Выполняеться создание индексов.'#13#10#13#10'Прервать?', mtInformation, mbOKCancel, 0) = mrOk then
begin
FFunctionThread.FError := 'Прервано пользователем.';
FFunctionThread.Terminate;
Action := caNone;
end else Action := caNone;
end else
begin
FError := FFunctionThread.FError;
end;
end;
procedure TThreadIndexForm.FormCreate(Sender: TObject);
begin
FError := '';
FFunctionThread := TIndexThread.Create(True);
FFunctionThread.FreeOnTerminate:=False;
FFunctionThread.FHostName := MainForm.edtSlaveServer.Text;
FFunctionThread.FDatabase := MainForm.edtSlaveDatabase.Text;
FFunctionThread.FUser := MainForm.edtSlaveUser.Text;
FFunctionThread.FPassword := MainForm.edtSlavePassword.Text;
FFunctionThread.FPort := StrToInt(MainForm.edtSlavePort.Text);
FFunctionThread.FLibraryLocation := MainForm.ZConnection.LibraryLocation;
FFunctionThread.OnError := SnapshotThreadError;
FFunctionThread.OnFinish := SnapshotThreadFinish;
FFunctionThread.OnMessage := SnapshotThreadMessage;
FFunctionThread.OnAddLog := SnapshotThreadAddLog;
FFunctionThread.OnProgress := SnapshotThreadProgress
end;
procedure TThreadIndexForm.FormDestroy(Sender: TObject);
begin
FFunctionThread.Free;
end;
procedure TThreadIndexForm.FormShow(Sender: TObject);
begin
FFunctionThread.Resume;
end;
procedure TThreadIndexForm.SnapshotThreadError(AError: string);
begin
// inc(FErrors);
// FSnapshotTableHasErrors := true;
// UpdateSnapshotErrors;
// SnapshotLog.Lines.Add(AError);
// SaveSnapshotLog(AError);
end;
procedure TThreadIndexForm.SnapshotThreadFinish;
begin
TThread.CreateAnonymousThread(procedure
begin
TThread.Synchronize(nil,
procedure
begin
while not FFunctionThread.Finished do Sleep(1000);
Close;
end)
end).Start;
end;
procedure TThreadIndexForm.SnapshotThreadMessage(AText: string);
begin
lblActionTake.Caption := AText;
end;
procedure TThreadIndexForm.SnapshotThreadAddLog(AText: string);
begin
MainForm.SaveBranchServiceLog(AText);
end;
procedure TThreadIndexForm.SnapshotThreadProgress(AText: string; AFunctionRecordPos, AFunctionRecordMax : Integer);
begin
lblActionTake.Caption := AText;
pbAll.Properties.Max := AFunctionRecordMax;
pbAll.Position := AFunctionRecordPos;
end;
{ TCheckConnectThread }
procedure TIndexThread.Execute;
var S: String;
I, nIndex: Integer;
List: TStringList;
begin
FError := '';
if Assigned(OnAddLog) then OnAddLog('Подключаемся к базе данных Slave.');
if Assigned(OnMessage) then OnMessage('Подключаемся к базе данных Slave.');
Sleep(2000);
FZConnection := TZConnection.Create(Nil);
FZConnection.Protocol := 'postgresql-9';
FZConnection.HostName := FHostName;
FZConnection.Database := FDatabase;
FZConnection.User := FUser;
FZConnection.Password := FPassword;
FZConnection.Port := FPort;
FZConnection.LibraryLocation := FLibraryLocation;
FZQueryTable := TZQuery.Create(Nil);
FZQueryTable.Connection := FZConnection;
FZQueryExecute := TZQuery.Create(Nil);
FZQueryExecute.Connection := FZConnection;
if Terminated then Exit;
FZQueryExecute.SQL.Text := cSQLReplication_Index;
try
try
FZConnection.Connect;
if Terminated then Exit;
if Assigned(OnAddLog) then OnAddLog('Получаем перечень таблмц.');
if Assigned(OnMessage) then OnMessage('Получаем перечень таблмц.');
S := ''; nIndex := 0;
List := TStringList.Create;
try
List.Text := MainForm.LiadScripts(cTableListAll);
for I := 0 to List.Count - 1 do
begin
if Terminated then Exit;
if Assigned(OnProgress) then OnProgress(Format(cIndexProcessing, [
IntToStr(I)
, IntToStr(List.Count)
, List.Strings[I]])
, I, List.Count);
FZQueryExecute.Close;
FZQueryExecute.ParamByName('inTableName').AsString := List.Strings[I];
FZQueryExecute.Open;
if FZQueryExecute.FieldByName('ErrorText').AsString <> '' then
begin
FError := FZQueryExecute.FieldByName('ErrorText').AsString;
Exit;
end;
end;
finally
if Assigned(OnAddLog) then OnAddLog(Format(cIndexResult, [IntToStr(List.Count), IntToStr(nIndex)]));
List.Free;
end;
except
on E: Exception do
FError := Format(cExceptionMsg, [E.ClassName, E.Message]);
end;
finally
FZQueryExecute.Close;
FZQueryTable.Close;
FZConnection.Disconnect;
FreeAndNil(FZQueryExecute);
FreeAndNil(FZQueryTable);
FreeAndNil(FZConnection);
if Assigned(FOnFinish) then OnFinish;
end;
end;
end.
|
unit AqDrop.Core.Cache.Monitor;
interface
uses
System.SysUtils,
System.TypInfo,
System.Classes,
AqDrop.Core.Types,
AqDrop.Core.Cache.Intf,
AqDrop.Core.Collections.Intf;
type
TAqCaches<I: IAqMonitorableCache> = class
strict private
FCaches: IAqIDDictionary<I>;
FCachesByTypeName: IAqDictionary<string, IAqList<TAqID>>;
procedure ExecuteForEachCache(const pProcessingMethod: TProc<I>);
public
constructor Create;
function RegisterCache(pCache: I; const pTypeLinkerCallback: TProc<TProc<PTypeInfo>>): TAqID;
procedure UnregisterCache(const pID: TAqID);
procedure DiscardExpiredItems;
procedure DiscardCacheByTypeNames(const pTypeNames: TArray<string>; const pID: TAqEntityID); overload;
procedure DiscardCacheByTypeNames(const pSenderID: TAqID; const pTypeNames: TArray<string>;
const pID: TAqEntityID); overload;
end;
TAqCacheMonitor<I: IAqMonitorableCache> = class
strict private
FCaches: TAqCaches<I>;
FThread: TThread;
strict protected
property Caches: TAqCaches<I> read FCaches;
public
constructor Create;
destructor Destroy; override;
function RegisterCache(pCache: I; const pTypeLinkerCallback: TProc<TProc<PTypeInfo>>): TAqID;
procedure UnregisterCache(const pID: TAqID);
end;
implementation
uses
System.DateUtils,
System.Rtti,
AqDrop.Core.Helpers,
AqDrop.Core.Helpers.Rtti,
AqDrop.Core.Collections;
{ TAqCacheMonitor<I> }
constructor TAqCacheMonitor<I>.Create;
begin
FCaches := TAqCaches<I>.Create;
FThread := TThread.CreateAnonymousThread(
procedure
var
lNextCicle: TDateTime;
lCache: I;
begin
while not TThread.CheckTerminated do
begin
FCaches.DiscardExpiredItems;
lNextCicle := Now.IncSecond(10);
while not TThread.CheckTerminated and (Now < lNextCicle) do
begin
Sleep(100);
end;
end;
end);
FThread.FreeOnTerminate := False;
FThread.Start;
end;
destructor TAqCacheMonitor<I>.Destroy;
begin
FThread.Terminate;
FThread.WaitFor;
FThread.Free;
FCaches.Free;
inherited;
end;
function TAqCacheMonitor<I>.RegisterCache(pCache: I; const pTypeLinkerCallback: TProc<TProc<PTypeInfo>>): TAqID;
begin
Result := FCaches.RegisterCache(pCache, pTypeLinkerCallback);
end;
procedure TAqCacheMonitor<I>.UnregisterCache(const pID: TAqID);
begin
FCaches.UnregisterCache(pID);
end;
{ TAqCaches<I> }
constructor TAqCaches<I>.Create;
begin
FCaches := TAqIDDictionary<I>.Create(TAqLockerType.lktMultiReaderExclusiveWriter);
FCachesByTypeName := TAqDictionary<string, IAqList<TAqID>>.Create;
end;
procedure TAqCaches<I>.DiscardCacheByTypeNames(const pTypeNames: TArray<string>; const pID: TAqEntityID);
begin
DiscardCacheByTypeNames(TAqIDGenerator.GetEmpty, pTypeNames, pID);
end;
procedure TAqCaches<I>.DiscardCacheByTypeNames(const pSenderID: TAqID; const pTypeNames: TArray<string>;
const pID: TAqEntityID);
var
lCachesToDiscard: IAqList<TAqID>;
lTypeName: string;
lCachesIDs: IAqList<TAqID>;
lCacheID: TAqID;
lCache: I;
begin
FCaches.BeginRead;
try
lCachesToDiscard := TAqList<TAqID>.Create;
for lTypeName in pTypeNames do
begin
if FCachesByTypeName.TryGetValue(lTypeName, lCachesIDs) then
begin
for lCacheID in lCachesIDs do
begin
if (lCacheID <> pSenderID) and not lCachesToDiscard.Contains(lCacheID) then
begin
lCachesToDiscard.Add(lCacheID);
end;
end;
end;
end;
for lCacheID in lCachesToDiscard do
begin
if FCaches.TryGetValue(lCacheID, lCache) then
begin
lCache.DiscardCache(pID);
end;
end;
finally
FCaches.EndRead;
end;
end;
procedure TAqCaches<I>.DiscardExpiredItems;
begin
ExecuteForEachCache(
procedure(pCache: I)
begin
pCache.DiscardExpiredItems;
end);
end;
procedure TAqCaches<I>.ExecuteForEachCache(const pProcessingMethod: TProc<I>);
var
lCache: I;
begin
FCaches.BeginRead;
try
for lCache in FCaches.Values.ToArray do
begin
pProcessingMethod(lCache);
end;
finally
FCaches.EndRead;
end;
end;
function TAqCaches<I>.RegisterCache(pCache: I; const pTypeLinkerCallback: TProc<TProc<PTypeInfo>>): TAqID;
var
lID: TAqID;
begin
FCaches.BeginWrite;
try
lID := FCaches.Add(pCache);
pTypeLinkerCallback(
procedure(pType: PTypeInfo)
var
lType: TRttiType;
begin
pCache.LinkToType(pType);
lType := TAqRtti.&Implementation.GetType(pType);
FCachesByTypeName.GetOrCreate(lType.QualifiedName,
function: IAqList<TAqID>
begin
Result := TAqList<TAqID>.Create;
end).Add(lID);
end);
finally
FCaches.EndWrite;
end;
Result := lID;
end;
procedure TAqCaches<I>.UnregisterCache(const pID: TAqID);
var
lCache: I;
lLinkedTypeName: string;
lCachesIDs: IAqList<TAqID>;
begin
FCaches.BeginWrite;
try
if FCaches.TryGetValue(pID, lCache) then
begin
for lLinkedTypeName in lCache.GetLinkedTypesNames do
begin
if FCachesByTypeName.TryGetValue(lLinkedTypeName, lCachesIDs) then
begin
lCachesIDs.DeleteItem(pID);
end;
end;
FCaches.Remove(pID);
end;
finally
FCaches.EndWrite;
end;
end;
end.
|
unit CreateOrderFromMCSLayout;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AncestorEnum, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxCheckBox, cxButtonEdit, dsdAction, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, Vcl.Menus, dsdAddOn, dxBarExtItems, dxBar,
cxClasses, dsdDB, Datasnap.DBClient, Vcl.ActnList, cxPropertiesStore,
cxGridLevel, cxGridCustomView, cxGrid, cxPC, dxSkinsCore,
dxSkinsDefaultPainters, dxSkinscxPCPainter, cxPCdxBarPopupMenu,
dxSkinsdxBarPainter;
type
TCreateOrderFromMCSLayoutForm = class(TAncestorEnumForm)
NeedReorder: TcxGridDBColumn;
UnitCode: TcxGridDBColumn;
UnitName: TcxGridDBColumn;
ExistsOrderInternal: TcxGridDBColumn;
MovementId: TcxGridDBColumn;
actOpenOrderInternalForm: TdsdOpenForm;
spInsertUpdate_MovementItem_OrderInternalMCSLayout: TdsdStoredProc;
actExecInsertUpdate_MovementItem_OrderInternalMCS: TdsdExecStoredProc;
actStartInsertUpdate_MovementItem_OrderInternalMCS: TMultiAction;
dxBarButton1: TdxBarButton;
actStartExec: TMultiAction;
spGet_MovementId_OrderInternal_Auto: TdsdStoredProc;
FormParams: TdsdFormParams;
mactOpenForm: TMultiAction;
actGet_MovementId_OrderInternal_Auto: TdsdExecStoredProc;
dxBarButton2: TdxBarButton;
actSelectAll: TBooleanStoredProcAction;
JuridicalName: TcxGridDBColumn;
private
{ Private declarations }
public
{ Public declarations }
end;
var
CreateOrderFromMCSLayoutForm: TCreateOrderFromMCSLayoutForm;
implementation
{$R *.dfm}
initialization
RegisterClass(TCreateOrderFromMCSLayoutForm)
end.
|
unit fHVEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Spin, Gauges, THnaciVozidlo, ComCtrls,
Generics.Collections, Buttons;
type
TF_HVEdit = class(TForm)
E_Nazev: TEdit;
E_Oznaceni: TEdit;
E_Majitel: TEdit;
L_HV1: TLabel;
L_HV2: TLabel;
L_HV3: TLabel;
L_HV4: TLabel;
L_HV5: TLabel;
M_Poznamky: TMemo;
B_Save: TButton;
B_Storno: TButton;
B_NajetoDelete: TButton;
L_HV7: TLabel;
CB_Orientace: TComboBox;
CB_Trida: TComboBox;
L_HV10: TLabel;
E_Addr: TEdit;
CB_OR: TComboBox;
Label1: TLabel;
LV_Pom_Load: TListView;
Label2: TLabel;
Label3: TLabel;
LV_Pom_Release: TListView;
SB_Rel_Remove: TSpeedButton;
SB_Rel_Add: TSpeedButton;
SB_Take_Add: TSpeedButton;
SB_Take_Remove: TSpeedButton;
procedure B_SaveClick(Sender: TObject);
procedure E_AdresaKeyPress(Sender: TObject; var Key: Char);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure B_StornoClick(Sender: TObject);
procedure B_NajetoDeleteClick(Sender: TObject);
procedure LV_Pom_LoadDblClick(Sender: TObject);
procedure SB_Take_AddClick(Sender: TObject);
procedure SB_Take_RemoveClick(Sender: TObject);
procedure LV_Pom_LoadChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure SB_Rel_AddClick(Sender: TObject);
procedure SB_Rel_RemoveClick(Sender: TObject);
procedure LV_Pom_ReleaseChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure LV_Pom_ReleaseDblClick(Sender: TObject);
private
OpenHV: THV;
procedure NormalOpenForm;
procedure NewHVOpenForm;
procedure HlavniOpenForm;
public
procedure OpenForm(HV:THV);
procedure NewHV();
end;
var
F_HVEdit: TF_HVEdit;
implementation
uses fMain, FileSystem, fSettings, THVDatabase, DataHV, TOblsRizeni, TOblRizeni,
fHVPomEdit, TBloky;
{$R *.dfm}
procedure TF_HVEdit.OpenForm(HV:THV);
begin
OpenHV := HV;
F_HVEdit.ActiveControl := Self.E_Nazev;
HlavniOpenForm();
if (HV = nil) then
begin
// nove HV
NewHVOpenForm();
end else begin
//editace HV
NormalOpenForm();
end;//else NewHV
F_HVEdit.ShowModal;
end;
procedure TF_HVEdit.SB_Rel_AddClick(Sender: TObject);
var LI:TListItem;
i:Integer;
begin
F_HV_Pom.OpenForm(-1, 0);
if (F_HV_Pom.saved) then
begin
i := 0;
while ((i < Self.LV_Pom_Release.Items.Count) and (StrToInt(Self.LV_Pom_Release.Items.Item[i].Caption) < F_HV_Pom.SE_CV.Value)) do Inc(i);
if ((Assigned(Self.LV_Pom_Release.Items.Item[i])) and (StrToInt(Self.LV_Pom_Release.Items.Item[i].Caption) = F_HV_Pom.SE_CV.Value)) then
begin
Self.LV_Pom_Release.Items.Item[i].SubItems.Strings[0] := IntToStr(F_HV_Pom.SE_Value.Value);
end else begin
LI := Self.LV_Pom_Release.Items.Insert(i);
LI.Caption := IntToStr(F_HV_Pom.SE_CV.Value);
LI.SubItems.Add(IntToStr(F_HV_Pom.SE_Value.Value));
end;
end;
end;
procedure TF_HVEdit.SB_Rel_RemoveClick(Sender: TObject);
begin
if (Self.LV_Pom_Release.Selected <> nil) then
Self.LV_Pom_Release.Items.Delete(Self.LV_Pom_Release.ItemIndex);
end;
procedure TF_HVEdit.SB_Take_AddClick(Sender: TObject);
var LI:TListItem;
i:Integer;
begin
F_HV_Pom.OpenForm(-1, 0);
if (F_HV_Pom.saved) then
begin
i := 0;
while ((i < Self.LV_Pom_Load.Items.Count) and (StrToInt(Self.LV_Pom_Load.Items.Item[i].Caption) < F_HV_Pom.SE_CV.Value)) do Inc(i);
if ((Assigned(Self.LV_Pom_Load.Items.Item[i])) and (StrToInt(Self.LV_Pom_Load.Items.Item[i].Caption) = F_HV_Pom.SE_CV.Value)) then
begin
Self.LV_Pom_Load.Items.Item[i].SubItems.Strings[0] := IntToStr(F_HV_Pom.SE_Value.Value);
end else begin
LI := Self.LV_Pom_Load.Items.Insert(i);
LI.Caption := IntToStr(F_HV_Pom.SE_CV.Value);
LI.SubItems.Add(IntToStr(F_HV_Pom.SE_Value.Value));
end;
end;
end;
procedure TF_HVEdit.SB_Take_RemoveClick(Sender: TObject);
begin
if (Self.LV_Pom_Load.Selected <> nil) then
Self.LV_Pom_Load.Items.Delete(Self.LV_Pom_Load.ItemIndex);
end;
procedure TF_HVEdit.B_SaveClick(Sender: TObject);
var data:THVData;
stav:THVStav;
return:Byte;
OblR:TOR;
i:Integer;
pomCV:THVPomCV;
begin
if (E_Nazev.Text = '') then
begin
Application.MessageBox('Vypiste nazev hnaciho vozidla','Nelze ulozit data',MB_OK OR MB_ICONWARNING);
Exit;
end;
if (CB_trida.ItemIndex = -1) then
begin
Application.MessageBox('Vyberte typ hnaciho vozidla','Nelze ulozit data',MB_OK OR MB_ICONWARNING);
Exit;
end;
if (CB_Orientace.ItemIndex = -1) and (CB_Orientace.Visible) then
begin
Application.MessageBox('Vyberte orientaci hnaciho vozidla !','Nelze ulozit data',MB_OK OR MB_ICONWARNING);
Exit;
end;
if (CB_OR.ItemIndex = -1) then
begin
Application.MessageBox('Vyberte stanici hnaciho vozidla !','Nelze ulozit data',MB_OK OR MB_ICONWARNING);
Exit;
end;
if ((not Self.E_Addr.ReadOnly) and (Self.E_Addr.text = '')) then
begin
Application.MessageBox('Vyplňte adresu !','Nelze ulozit data',MB_OK OR MB_ICONWARNING);
Exit;
end;
ORs.GetORByIndex(Self.CB_OR.ItemIndex, OblR);
if ((Self.OpenHV <> nil) and (Self.OpenHV.Stav.souprava > -1) and (Self.OpenHV.Stav.stanice <> OblR)) then
if (Application.MessageBox('Měníte stanici HV, které je na soupravě, opravdu pokračovat?', 'Opravdu?', MB_YESNO OR MB_ICONWARNING) = mrNo) then
Exit();
// samotne ukladani dat
data.Nazev := E_Nazev.Text;
data.Majitel := E_Majitel.Text;
data.Oznaceni := E_Oznaceni.Text;
data.Poznamka := M_Poznamky.Text;
data.Trida := THVClass(CB_trida.ItemIndex);
if (Self.OpenHV = nil) then
begin
data.POMtake := TList<THVPomCV>.Create();
data.POMrelease := TList<THVPomCV>.Create();
end else begin
data.POMtake := Self.OpenHV.Data.POMtake;
data.POMrelease := Self.OpenHV.Data.POMrelease;
end;
data.POMtake.Clear();
data.POMrelease.Clear();
// parse POM take
for i := 0 to Self.LV_Pom_Load.Items.Count-1 do
begin
try
pomCV.cv := StrToInt(Self.LV_Pom_Load.Items.Item[i].Caption);
pomCV.data := StrToInt(Self.LV_Pom_Load.Items.Item[i].SubItems.Strings[0]);
data.POMtake.Add(pomCV);
except
end;
end;
// parse POM release
for i := 0 to Self.LV_Pom_Release.Items.Count-1 do
begin
try
pomCV.cv := StrToInt(Self.LV_Pom_Release.Items.Item[i].Caption);
pomCV.data := StrToInt(Self.LV_Pom_Release.Items.Item[i].SubItems.Strings[0]);
data.POMrelease.Add(pomCV);
except
end;
end;
if (Self.OpenHV = nil) then
begin
// vytvoreni noveho HV
ORs.GetORByIndex(Self.CB_OR.ItemIndex, OblR);
return := HVDb.Add(data, StrToInt(Self.E_Addr.Text), THVStanoviste(CB_Orientace.ItemIndex), OblR);
if (return = 1) then
begin
Application.MessageBox(PChar('Chyba '+IntToStr(return)+#13#10+'Neplatná adresa !'), 'Nelze přidat', MB_OK OR MB_ICONWARNING);
Exit;
end;
if (return = 2) then
begin
Application.MessageBox(PChar('Chyba '+IntToStr(return)+#13#10+'HV s touto adresou již existuje !'), 'Nelze přidat', MB_OK OR MB_ICONWARNING);
Exit;
end;
end else begin
// vyznamy funkci jednoduse zkopirujeme
data.funcVyznam := Self.OpenHV.Data.funcVyznam;
// update HV
Self.OpenHV.data := data;
ORs.GetORByIndex(Self.CB_OR.ItemIndex, OblR);
stav := Self.OpenHV.stav;
stav.StanovisteA := THVStanoviste(CB_Orientace.ItemIndex);
Self.OpenHV.Stav := stav;
Self.OpenHV.PredejStanici(OblR);
Self.OpenHV.UpdateAllRegulators();
HVTableData.UpdateLine(OpenHV);
if (stav.souprava > -1) then
Blky.ChangeSprToTrat(stav.souprava);
end;
Self.Close;
end;//procedure
procedure TF_HVEdit.E_AdresaKeyPress(Sender: TObject; var Key: Char);
begin
Key := Key;
case Key of
'0'..'9',#9,#8:begin
end else begin
Key := #0;
end;
end;//case
end;
procedure TF_HVEdit.NewHV();
begin
Self.OpenForm(nil);
end;//procedure
procedure TF_HVEdit.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
Self.OpenHV := nil;
end;//procedure
procedure TF_HVEdit.B_StornoClick(Sender: TObject);
begin
Self.Close;
end;//procedure
procedure TF_HVEdit.B_NajetoDeleteClick(Sender: TObject);
begin
if (Self.OpenHV = nil) then Exit;
OpenHV.RemoveStats();
HVTableData.UpdateLine(Self.OpenHV);
Application.MessageBox('Operace proběhla úspěšne', 'OK', MB_OK OR MB_ICONINFORMATION);
end;//procedure
procedure TF_HVEdit.HlavniOpenForm;
begin
Self.SB_Rel_Remove.Enabled := false;
Self.SB_Take_Remove.Enabled := false;
end;
procedure TF_HVEdit.LV_Pom_LoadChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
Self.SB_Take_Remove.Enabled := (Self.LV_Pom_Load.Selected <> nil);
end;
procedure TF_HVEdit.LV_Pom_LoadDblClick(Sender: TObject);
begin
if (Self.LV_Pom_Load.Selected <> nil) then
begin
F_HV_Pom.OpenForm(StrToInt(Self.LV_Pom_Load.Selected.Caption), StrToInt(Self.LV_Pom_Load.Selected.SubItems.Strings[0]));
if (F_HV_Pom.saved) then
Self.LV_Pom_Load.Selected.SubItems.Strings[0] := IntToStr(F_HV_Pom.SE_Value.Value);
end else begin
Self.SB_Take_AddClick(Self);
end;
end;
procedure TF_HVEdit.LV_Pom_ReleaseChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
Self.SB_Rel_Remove.Enabled := (Self.LV_Pom_Release.Selected <> nil);
end;
procedure TF_HVEdit.LV_Pom_ReleaseDblClick(Sender: TObject);
begin
if (Self.LV_Pom_Release.Selected <> nil) then
begin
F_HV_Pom.OpenForm(StrToInt(Self.LV_Pom_Release.Selected.Caption), StrToInt(Self.LV_Pom_Release.Selected.SubItems.Strings[0]));
if (F_HV_Pom.saved) then
Self.LV_Pom_Release.Selected.SubItems.Strings[0] := IntToStr(F_HV_Pom.SE_Value.Value);
end else begin
Self.SB_Rel_AddClick(Self);
end;
end;
procedure TF_HVEdit.NormalOpenForm;
var data:THVData;
stav:THVStav;
i:Integer;
LI:TListItem;
begin
B_NajetoDelete.Visible := true;
E_Addr.ReadOnly := true;
data := Self.OpenHV.data;
stav := Self.OpenHV.stav;
E_Nazev.Text := data.Nazev;
E_Oznaceni.Text := data.Oznaceni;
E_Majitel.Text := data.Majitel;
E_Addr.Text := IntToStr(Self.OpenHV.adresa);
M_Poznamky.Text := data.Poznamka;
CB_trida.ItemIndex := Integer(data.Trida);
CB_Orientace.ItemIndex := Integer(stav.StanovisteA);
Self.LV_Pom_Load.Clear();
for i := 0 to data.POMtake.Count-1 do
begin
LI := Self.LV_Pom_Load.Items.Add;
LI.Caption := IntToStr(data.POMtake[i].cv);
LI.SubItems.Add(IntToStr(data.POMtake[i].data));
end;
Self.LV_Pom_Release.Clear();
for i := 0 to data.POMrelease.Count-1 do
begin
LI := Self.LV_Pom_Release.Items.Add;
LI.Caption := IntToStr(data.POMrelease[i].cv);
LI.SubItems.Add(IntToStr(data.POMrelease[i].data));
end;
ORs.FillCB(Self.CB_OR, stav.stanice);
F_HVEdit.Caption := 'HV : '+IntToStr(Self.OpenHV.adresa);
end;//procedure
procedure TF_HVEdit.NewHVOpenForm;
begin
B_NajetoDelete.Visible := false;
E_Addr.ReadOnly := false;
E_Nazev.Text := '';
E_Oznaceni.Text := '';
E_Majitel.Text := '';
E_Addr.Text := '';
M_Poznamky.Text := '';
CB_trida.ItemIndex := -1;
CB_Orientace.ItemIndex := -1;
Self.LV_Pom_Load.Clear();
Self.LV_Pom_Release.Clear();
ORs.FillCB(Self.CB_OR, nil);
F_HVEdit.Caption := 'Nové HV';
end;//procedure
end.//unit
|
PROGRAM EX11;
USES CRT;
VAR hora_i, min_i, hora_f, min_f, hora_d, min_d: INTEGER;
BEGIN
{Limpa a tela}
CLRSCR;
{Mostra mensagem solicitando o horário inicial}
WRITELN('Digite o horário inicial ');
{Mostra mensagem solicitando a hora inicial}
WRITELN('hora: ');
{Recebe a hora inicial}
READLN(hora_i);
{Mostra mensagem solicitando os minutos iniciais}
WRITELN('minuto: ');
{Recebe os minutos iniciais}
READLN(min_i);
{Mostra mensagem solicitando o horário final}
WRITELN('Digite o horário final ');
{Mostra mensagem solicitando a hora final}
WRITELN('hora: ');
{Recebe a hora final}
READLN(hora_f);
{Mostra mensagem solicitando os minutos finais}
WRITELN('minuto: ');
{Recebe os minutos finais}
READLN(min_f);
{Calcula a duraçao do jogo}
IF min_i > min_f
THEN BEGIN
min_f := min_f + 60;
hora_f := hora_f - 1;
END;
IF hora_i > hora_f
THEN hora_f := hora_f + 24;
min_d := min_f - min_i;
hora_d := hora_f - hora_i;
{Mostra a duraçao do jogo}
WRITELN('O jogo durou ',hora_d,' hora(s) e ',min_d,' minuto(s)');
{Pára o programa a espera de um ENTER}
READLN;
END.
|
unit mvctrls;
interface
uses StdCtrls, Messages, Windows, SysUtils, Classes, Controls, Forms, Graphics,
ExtCtrls;
type
TmvRadioButton = class(TButtonControl)
private
FAlignment: TLeftRight;
FChecked: Boolean;
FWordWrap: boolean;
procedure SetAlignment(Value: TLeftRight);
procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED;
procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
procedure CNCommand(var Message: TWMCommand); message CN_COMMAND;
protected
procedure SetChecked(Value: Boolean);
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWindowHandle(const Params: TCreateParams); override;
procedure CreateWnd; override;
public
constructor Create(AOwner: TComponent); override;
published
property Alignment: TLeftRight read FAlignment write SetAlignment default taRightJustify;
property Caption;
property Checked: Boolean read FChecked write SetChecked default False;
property Color;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
property WordWrap: boolean read FWordWrap write FWordWrap default false; // mv
end;
TmvCustomRadioGroup = class(TCustomGroupBox)
private
FButtons: TList;
FItems: TStrings;
FItemIndex: Integer;
FColumns: Integer;
FReading: Boolean;
FUpdating: Boolean;
FWordWrap: Boolean;
procedure ArrangeButtons;
procedure ButtonClick(Sender: TObject);
procedure ItemsChange(Sender: TObject);
procedure SetButtonCount(Value: Integer);
procedure SetColumns(Value: Integer);
procedure SetItemIndex(Value: Integer);
procedure SetItems(Value: TStrings);
procedure UpdateButtons;
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
protected
procedure ReadState(Reader: TReader); override;
function CanModify: Boolean; virtual;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
property Columns: Integer read FColumns write SetColumns default 1;
property ItemIndex: Integer read FItemIndex write SetItemIndex default -1;
property Items: TStrings read FItems write SetItems;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property WordWrap: boolean read FWordWrap write FWordWrap default false; // mv
end;
TmvRadioGroup = class(TmvCustomRadioGroup)
published
property Align;
property Caption;
property Color;
property Columns;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property ItemIndex;
property Items;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnStartDrag;
end;
implementation
{ TmvRadioButton }
constructor TmvRadioButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := 113;
Height := 17;
ControlStyle := [csSetCaption, csDoubleClicks];
FAlignment := taRightJustify;
end;
procedure TmvRadioButton.SetAlignment(Value: TLeftRight);
begin
if FAlignment <> Value then
begin
FAlignment := Value;
RecreateWnd;
end;
end;
procedure TmvRadioButton.SetChecked(Value: Boolean);
procedure TurnSiblingsOff;
var
I: Integer;
Sibling: TControl;
begin
if Parent <> nil then
with Parent do
for I := 0 to ControlCount - 1 do
begin
Sibling := Controls[I];
if (Sibling <> Self) and (Sibling is TmvRadioButton) then
TmvRadioButton(Sibling).SetChecked(False);
end;
end;
begin
if FChecked <> Value then
begin
FChecked := Value;
TabStop := Value;
if HandleAllocated then
SendMessage(Handle, BM_SETCHECK, Integer(Checked), 0);
if Value then
begin
TurnSiblingsOff;
inherited Changed;
Click;
end;
end;
end;
procedure TmvRadioButton.CreateParams(var Params: TCreateParams);
const
Alignments: array[TLeftRight] of LongInt = (BS_LEFTTEXT, 0);
WordWraps: array[Boolean] of LongInt = (0, BS_MULTILINE);
begin
inherited CreateParams(Params);
CreateSubClass(Params, 'BUTTON');
with Params do // V - it's my (mv) patch
Style := Style or BS_RADIOBUTTON or WordWraps[FWordWrap] or BS_TOP or Alignments[FAlignment];
end;
procedure TmvRadioButton.CreateWnd;
begin
inherited CreateWnd;
SendMessage(Handle, BM_SETCHECK, Integer(FChecked), 0);
end;
procedure TmvRadioButton.CreateWindowHandle(const Params: TCreateParams);
begin
if Ctl3D and not NewStyleControls then
begin // special subclassing required by unicode Ctl3D on NT
with Params do
WindowHandle := CreateWindowEx(ExStyle, 'BUTTON', Caption, Style,
X, Y, Width, Height, WndParent, 0, HInstance, Param);
Subclass3DWnd(WindowHandle);
DefWndProc := Pointer(GetWindowLong(WindowHandle, GWL_WNDPROC));
CreationControl := Self;
SetWindowLong(WindowHandle, GWL_WNDPROC, Longint(@InitWndProc));
SendMessage(WindowHandle, WM_NULL, 0, 0);
end
else
inherited CreateWindowHandle(Params);
end;
procedure TmvRadioButton.CMCtl3DChanged(var Message: TMessage);
begin
RecreateWnd;
end;
procedure TmvRadioButton.CMDialogChar(var Message: TCMDialogChar);
begin
with Message do
if IsAccel(Message.CharCode, Caption) and CanFocus then
begin
SetFocus;
Result := 1;
end else
inherited;
end;
procedure TmvRadioButton.CNCommand(var Message: TWMCommand);
begin
case Message.NotifyCode of
BN_CLICKED: SetChecked(True);
BN_DOUBLECLICKED: DblClick;
end;
end;
procedure TmvRadioButton.WMSetFocus(var Message: TWMSetFocus);
begin // fix double focus rect drawing bug in Ctl3D when switching notebook pages
if Ctl3D and not NewStyleControls then UpdateWindow(Handle);
inherited;
end;
{ TmvGroupButton }
type
TmvGroupButton = class(TmvRadioButton)
private
FInClick: Boolean;
procedure CNCommand(var Message: TWMCommand); message CN_COMMAND;
protected
procedure ChangeScale(M, D: Integer); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
public
constructor InternalCreate(RadioGroup: TmvCustomRadioGroup);
destructor Destroy; override;
end;
constructor TmvGroupButton.InternalCreate(RadioGroup: TmvCustomRadioGroup);
begin
inherited Create(RadioGroup);
RadioGroup.FButtons.Add(Self);
Visible := False;
Enabled := RadioGroup.Enabled;
ParentShowHint := False;
OnClick := RadioGroup.ButtonClick;
Parent := RadioGroup;
WordWrap := RadioGroup.WordWrap;
end;
destructor TmvGroupButton.Destroy;
begin
TmvCustomRadioGroup(Owner).FButtons.Remove(Self);
inherited Destroy;
end;
procedure TmvGroupButton.CNCommand(var Message: TWMCommand);
begin
if not FInClick then
begin
FInClick := True;
try
if ((Message.NotifyCode = BN_CLICKED) or
(Message.NotifyCode = BN_DOUBLECLICKED)) and
TmvCustomRadioGroup(Parent).CanModify then
inherited;
except
Application.HandleException(Self);
end;
FInClick := False;
end;
end;
procedure TmvGroupButton.ChangeScale(M, D: Integer);
begin
end;
procedure TmvGroupButton.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
TmvCustomRadioGroup(Parent).KeyPress(Key);
if (Key = #8) or (Key = ' ') then
begin
if not TmvCustomRadioGroup(Parent).CanModify then Key := #0;
end;
end;
procedure TmvGroupButton.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
TmvCustomRadioGroup(Parent).KeyDown(Key, Shift);
end;
{ TmvCustomRadioGroup }
constructor TmvCustomRadioGroup.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csSetCaption, csDoubleClicks];
FButtons := TList.Create;
FItems := TStringList.Create;
TStringList(FItems).OnChange := ItemsChange;
FItemIndex := -1;
FColumns := 1;
end;
destructor TmvCustomRadioGroup.Destroy;
begin
SetButtonCount(0);
TStringList(FItems).OnChange := nil;
FItems.Free;
FButtons.Free;
inherited Destroy;
end;
procedure TmvCustomRadioGroup.ArrangeButtons;
var
ButtonsPerCol, ButtonWidth, ButtonHeight, TopMargin, I: Integer;
DC: HDC;
SaveFont: HFont;
Metrics: TTextMetric;
DeferHandle: THandle;
begin
if (FButtons.Count <> 0) and not FReading then
begin
DC := GetDC(0);
SaveFont := SelectObject(DC, Font.Handle);
GetTextMetrics(DC, Metrics);
SelectObject(DC, SaveFont);
ReleaseDC(0, DC);
ButtonsPerCol := (FButtons.Count + FColumns - 1) div FColumns;
ButtonWidth := (Width - 10) div FColumns;
I := Height - Metrics.tmHeight - 5;
ButtonHeight := I div ButtonsPerCol;
TopMargin := Metrics.tmHeight + 1 + (I mod ButtonsPerCol) div 2;
DeferHandle := BeginDeferWindowPos(FButtons.Count);
for I := 0 to FButtons.Count - 1 do
with TmvGroupButton(FButtons[I]) do
begin
DeferHandle := DeferWindowPos(DeferHandle, Handle, 0,
(I div ButtonsPerCol) * ButtonWidth + 8,
(I mod ButtonsPerCol) * ButtonHeight + TopMargin,
ButtonWidth, ButtonHeight,
SWP_NOZORDER or SWP_NOACTIVATE);
Visible := True;
end;
EndDeferWindowPos(DeferHandle);
end;
end;
procedure TmvCustomRadioGroup.ButtonClick(Sender: TObject);
begin
if not FUpdating then
begin
FItemIndex := FButtons.IndexOf(Sender);
Changed;
Click;
end;
end;
procedure TmvCustomRadioGroup.ItemsChange(Sender: TObject);
begin
if not FReading then
begin
if FItemIndex >= FItems.Count then FItemIndex := FItems.Count - 1;
UpdateButtons;
end;
end;
procedure TmvCustomRadioGroup.ReadState(Reader: TReader);
begin
FReading := True;
inherited ReadState(Reader);
FReading := False;
UpdateButtons;
end;
procedure TmvCustomRadioGroup.SetButtonCount(Value: Integer);
begin
while FButtons.Count < Value do TmvGroupButton.InternalCreate(Self);
while FButtons.Count > Value do TmvGroupButton(FButtons.Last).Free;
end;
procedure TmvCustomRadioGroup.SetColumns(Value: Integer);
begin
if Value < 1 then Value := 1;
if Value > 16 then Value := 16;
if FColumns <> Value then
begin
FColumns := Value;
ArrangeButtons;
Invalidate;
end;
end;
procedure TmvCustomRadioGroup.SetItemIndex(Value: Integer);
begin
if FReading then FItemIndex := Value else
begin
if Value < -1 then Value := -1;
if Value >= FButtons.Count then Value := FButtons.Count - 1;
if FItemIndex <> Value then
begin
if FItemIndex >= 0 then
TmvGroupButton(FButtons[FItemIndex]).Checked := False;
FItemIndex := Value;
if FItemIndex >= 0 then
TmvGroupButton(FButtons[FItemIndex]).Checked := True;
end;
end;
end;
procedure TmvCustomRadioGroup.SetItems(Value: TStrings);
begin
FItems.Assign(Value);
end;
procedure TmvCustomRadioGroup.UpdateButtons;
var
I: Integer;
begin
SetButtonCount(FItems.Count);
for I := 0 to FButtons.Count - 1 do
TmvGroupButton(FButtons[I]).Caption := FItems[I];
if FItemIndex >= 0 then
begin
FUpdating := True;
TmvGroupButton(FButtons[FItemIndex]).Checked := True;
FUpdating := False;
end;
ArrangeButtons;
Invalidate;
end;
procedure TmvCustomRadioGroup.CMEnabledChanged(var Message: TMessage);
var
I: Integer;
begin
inherited;
for I := 0 to FButtons.Count - 1 do
TmvGroupButton(FButtons[I]).Enabled := Enabled;
end;
procedure TmvCustomRadioGroup.CMFontChanged(var Message: TMessage);
begin
inherited;
ArrangeButtons;
end;
procedure TmvCustomRadioGroup.WMSize(var Message: TWMSize);
begin
inherited;
ArrangeButtons;
end;
function TmvCustomRadioGroup.CanModify: Boolean;
begin
Result := True;
end;
procedure TmvCustomRadioGroup.GetChildren(Proc: TGetChildProc; Root: TComponent);
begin
end;
end.
|
{******************************************************************************}
{ }
{ Indy (Internet Direct) - Internet Protocols Simplified }
{ }
{ https://www.indyproject.org/ }
{ https://gitter.im/IndySockets/Indy }
{ }
{******************************************************************************}
{ }
{ This file is part of the Indy (Internet Direct) project, and is offered }
{ under the dual-licensing agreement described on the Indy website. }
{ (https://www.indyproject.org/license/) }
{ }
{ Copyright: }
{ (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. }
{ }
{******************************************************************************}
{ }
{ Originally written by: Fabian S. Biehn }
{ fbiehn@aagon.com (German & English) }
{ }
{ Contributers: }
{ Here could be your name }
{ }
{******************************************************************************}
unit IdOpenSSLIOHandlerClientBase;
interface
{$i IdCompilerDefines.inc}
uses
IdGlobal,
IdOpenSSLContext,
IdOpenSSLSocket,
IdSSL;
type
TIdOpenSSLIOHandlerClientBase = class(TIdSSLIOHandlerSocketBase)
private
protected
FTLSSocket: TIdOpenSSLSocket;
FContext: TIdOpenSSLContext;
function RecvEnc(var ABuffer: TIdBytes): Integer; override;
function SendEnc(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; override;
procedure EnsureContext; virtual; abstract;
procedure SetPassThrough(const Value: Boolean); override;
public
destructor Destroy; override;
procedure AfterAccept; override;
procedure StartSSL; override;
procedure ConnectClient; override;
procedure Close; override;
function CheckForError(ALastResult: Integer): Integer; override;
procedure RaiseError(AError: Integer); override;
function Readable(AMSec: Integer = IdTimeoutDefault): Boolean; override;
function Clone: TIdSSLIOHandlerSocketBase; override;
end;
implementation
uses
IdOpenSSLExceptions,
IdOpenSSLHeaders_ssl,
IdStackConsts,
SysUtils;
type
TIdOpenSSLSocketAccessor = class(TIdOpenSSLSocket);
{ TIdOpenSSLIOHandlerClientBase }
procedure TIdOpenSSLIOHandlerClientBase.AfterAccept;
begin
inherited;
EnsureContext();
StartSSL();
end;
procedure TIdOpenSSLIOHandlerClientBase.Close;
begin
if Assigned(FTLSSocket) then
begin
FTLSSocket.Close();
FreeAndNil(FTLSSocket);
end;
inherited;
end;
procedure TIdOpenSSLIOHandlerClientBase.ConnectClient;
begin
inherited;
EnsureContext();
StartSSL();
end;
destructor TIdOpenSSLIOHandlerClientBase.Destroy;
begin
FreeAndNil(FTLSSocket);
// no FContext.Free() here, if a derived class creates an own instance that
// class should free that object
inherited;
end;
function TIdOpenSSLIOHandlerClientBase.CheckForError(ALastResult: Integer): Integer;
begin
if PassThrough then
begin
Result := inherited CheckForError(ALastResult);
Exit;
end;
Result := FTLSSocket.GetErrorCode(ALastResult);
case Result of
SSL_ERROR_SYSCALL:
Result := inherited CheckForError(ALastResult);
// inherited CheckForError(Integer(Id_SOCKET_ERROR));
SSL_ERROR_NONE:
begin
Result := 0;
Exit;
end;
else
raise EIdOpenSSLUnspecificStackError.Create('', Result);
end;
end;
function TIdOpenSSLIOHandlerClientBase.Clone: TIdSSLIOHandlerSocketBase;
begin
Result := TIdClientSSLClass(Self.ClassType).Create(Owner);
end;
function TIdOpenSSLIOHandlerClientBase.RecvEnc(var ABuffer: TIdBytes): Integer;
begin
Result := FTLSSocket.Receive(ABuffer);
end;
function TIdOpenSSLIOHandlerClientBase.SendEnc(const ABuffer: TIdBytes;
const AOffset, ALength: Integer): Integer;
begin
Result := FTLSSocket.Send(ABuffer, AOffset, ALength);
end;
procedure TIdOpenSSLIOHandlerClientBase.SetPassThrough(const Value: Boolean);
begin
if fPassThrough = Value then
Exit;
inherited;
if not Value then
begin
if BindingAllocated then
StartSSL();
end
else
begin
if Assigned(FTLSSocket) then
begin
FTLSSocket.Close();
FreeAndNil(FTLSSocket);
end;
end;
end;
procedure TIdOpenSSLIOHandlerClientBase.RaiseError(AError: Integer);
function IsSocketError(const AError: Integer): Boolean; {$IFDEF USE_INLINE}inline;{$ENDIF}
begin
Result := (AError = Id_WSAESHUTDOWN)
or (AError = Id_WSAECONNABORTED)
or (AError = Id_WSAECONNRESET)
end;
begin
if PassThrough or IsSocketError(AError) or not Assigned(FTLSSocket) then
inherited RaiseError(AError)
else
raise EIdOpenSSLUnspecificError.Create(TIdOpenSSLSocketAccessor(FTLSSocket).FSSL, AError, '');
end;
function TIdOpenSSLIOHandlerClientBase.Readable(AMSec: Integer): Boolean;
begin
Result := True;
if PassThrough or not FTLSSocket.HasReadableData() then
Result := inherited Readable(AMSec);
end;
procedure TIdOpenSSLIOHandlerClientBase.StartSSL;
var
LTimeout: Integer;
begin
inherited;
if PassThrough then
Exit;
FTLSSocket := FContext.CreateSocket();
{$IFDEF WIN32_OR_WIN64}
if IndyCheckWindowsVersion(6) then
begin
// Note: Fix needed to allow SSL_Read and SSL_Write to timeout under
// Vista+ when connection is dropped
LTimeout := FReadTimeOut;
if LTimeout <= 0 then begin
LTimeout := 30000; // 30 seconds
end;
Binding.SetSockOpt(Id_SOL_SOCKET, Id_SO_RCVTIMEO, LTimeout);
Binding.SetSockOpt(Id_SOL_SOCKET, Id_SO_SNDTIMEO, LTimeout);
end;
{$ENDIF}
end;
end.
|
unit fZesilovacEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Spin, fMain, Booster;
type
TF_ZesilovacEdit = class(TForm)
L_Nazev: TLabel;
E_Nazev: TEdit;
RG_Typ: TRadioGroup;
B_Save: TButton;
GB_Zkrat: TGroupBox;
L_Zkrat_Port: TLabel;
L_Zkrat_MTB: TLabel;
SE_Zkrat_Port: TSpinEdit;
GB_Napajeni: TGroupBox;
L_Napajeni_Port: TLabel;
L_Napajeni_MTB: TLabel;
SE_Napajeni_Port: TSpinEdit;
B_Storno: TButton;
SE_Zkrat_MTB: TSpinEdit;
SE_Napajeni_MTB: TSpinEdit;
GB_DCC: TGroupBox;
Label1: TLabel;
Label2: TLabel;
SE_DCC_port: TSpinEdit;
SE_DCC_MTB: TSpinEdit;
CHB_DCC: TCheckBox;
E_ID: TEdit;
Label3: TLabel;
procedure B_SaveClick(Sender: TObject);
procedure B_StornoClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure CHB_DCCClick(Sender: TObject);
private
open_booster:TBooster;
procedure HlavniOpenForm;
procedure NormalOpenForm;
procedure NewOpenForm;
public
procedure NewZes;
procedure OpenForm(Zesilovac:TBooster);
end;
var
F_ZesilovacEdit: TF_ZesilovacEdit;
implementation
uses GetSystems, fSettings, TechnologieRCS, BoosterDb, FileSystem, DataZesilovac,
TBloky;
{$R *.dfm}
procedure TF_ZesilovacEdit.OpenForm(Zesilovac:TBooster);
begin
Self.open_booster := Zesilovac;
Self.HlavniOpenForm;
if (zesilovac = nil) then
begin
Self.NewOpenForm;
end else begin
Self.NormalOpenForm;
end;
Self.ShowModal;
end;
procedure TF_ZesilovacEdit.B_SaveClick(Sender: TObject);
var settings:TBoosterSettings;
begin
if (E_Nazev.Text = '') then
begin
Application.MessageBox('Vyplnte nazev zesilovace','Nelze ulozit data',MB_OK OR MB_ICONSTOP);
Exit;
end;
if (E_ID.Text = '') then
begin
Application.MessageBox('Vyplnte id zesilovace','Nelze ulozit data',MB_OK OR MB_ICONSTOP);
Exit;
end;
if (Self.RG_Typ.ItemIndex < 0) then
begin
Application.MessageBox('Vyberte typ zesilovace','Nelze ulozit data',MB_OK OR MB_ICONSTOP);
Exit;
end;
if (Boosters.ContainsKey(E_ID.Text, Self.open_booster)) then
begin
Application.MessageBox('Zesilovač s tímto ID již existuje!','Nelze ulozit data',MB_OK OR MB_ICONSTOP);
Exit;
end;
if (Self.open_booster = nil) then
begin
Self.open_booster := TBooster.Create;
try
Boosters.Add(Self.open_booster);
except
on E:Exception do
begin
Application.MessageBox(PChar(e.Message), 'Chyba při vytváření zesilovače', MB_OK OR MB_ICONERROR);
Exit();
end;
end;
end;
settings.Name := E_Nazev.Text;
settings.bclass := TBoosterClass(RG_Typ.ItemIndex+1);
settings.id := E_ID.Text;
settings.MTB.Zkrat.board := Self.SE_Zkrat_MTB.Value;
settings.MTB.Napajeni.board := Self.SE_Napajeni_MTB.Value;
settings.MTB.Zkrat.port := SE_Zkrat_Port.Value;
settings.MTB.Napajeni.port := SE_Napajeni_Port.Value;
if (Self.CHB_DCC.Checked) then
begin
Settings.MTB.DCC.board := Self.SE_DCC_MTB.Value;
Settings.MTB.DCC.port := Self.SE_DCC_port.Value;
end else begin
Settings.MTB.DCC.board := 0;
Settings.MTB.DCC.port := 0;
end;
Self.open_booster.bSettings := settings;
Boosters.SyncStructures();
ZesTableData.LoadToTable();
Self.Close;
end;//procedure
procedure TF_ZesilovacEdit.B_StornoClick(Sender: TObject);
begin
F_ZesilovacEdit.Close;
end;
procedure TF_ZesilovacEdit.CHB_DCCClick(Sender: TObject);
begin
Self.SE_DCC_MTB.Enabled := Self.CHB_DCC.Checked;
Self.SE_DCC_port.Enabled := Self.CHB_DCC.Checked;
end;
procedure TF_ZesilovacEdit.NewZes;
begin
OpenForm(nil);
end;//procedure
procedure TF_ZesilovacEdit.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
Self.open_booster := nil;
CanClose := true;
end;//procedure
procedure TF_ZesilovacEdit.HlavniOpenForm;
begin
F_ZesilovacEdit.ActiveControl := B_Save;
end;//procedure
procedure TF_ZesilovacEdit.NormalOpenForm;
var bSettings:TBoosterSettings;
IgnoraceMTB:TArI;
begin
bSettings := open_booster.bSettings;
E_ID.Text := bSettings.id;
E_Nazev.Text := bSettings.Name;
RG_Typ.ItemIndex := Integer(bSettings.bclass)-1;
SE_Zkrat_Port.Value := bSettings.MTB.Zkrat.port;
SE_Napajeni_Port.Value := bSettings.MTB.Napajeni.port;
SetLength(IgnoraceMTB,2);
IgnoraceMTB[0] := 3;
IgnoraceMTB[1] := 4;
Self.SE_Napajeni_MTB.Value := bSettings.MTB.Napajeni.board;
Self.SE_Zkrat_MTB.Value := bSettings.MTB.Zkrat.board;
Self.SE_DCC_MTB.Value := bSettings.MTB.DCC.board;
Self.SE_DCC_port.Value := bSettings.MTB.DCC.port;
Self.CHB_DCC.Checked := open_booster.isDCCdetection;
Self.CHB_DCCClick(Self.CHB_DCC);
F_ZesilovacEdit.Caption := 'Zesilovač : '+bSettings.Name;
end;//procedure
procedure TF_ZesilovacEdit.NewOpenForm;
var IgnoraceMTB:TArI;
begin
E_ID.Text := '';
E_Nazev.Text := '';
RG_Typ.ItemIndex := -1;
SE_Zkrat_Port.Value := 0;
SE_Napajeni_Port.Value := 0;
SetLength(IgnoraceMTB,2);
IgnoraceMTB[0] := 3;
IgnoraceMTB[1] := 4;
Self.SE_Napajeni_MTB.Value := 1;
Self.SE_Zkrat_MTB.Value := 1;
Self.SE_DCC_MTB.Value := 1;
Self.SE_DCC_port.Value := 0;
Self.CHB_DCC.Checked := false;
Self.CHB_DCCClick(Self.CHB_DCC);
F_ZesilovacEdit.Caption := 'Nový zesilovač';
end;//procedure
end.//unit
|
{$ifdef license}
(*
Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com )
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be
used to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
{$endif}
unit cwThreading.ScheduledTaskWrapper.Standard;
{$ifdef fpc}{$mode delphiunicode}{$endif}
interface
uses
cwThreading
, cwThreading.Internal
;
type
TScheduledThreadState = ( tsRunning, tsTerminating, tsTerminated );
TScheduledTaskWrapper = class( TInterfacedObject, IScheduledTaskWrapper )
private
fThread: IThread;
fThreadCS: ISignaledCriticalSection;
fScheduledTask: IScheduledTask;
fLastExecuted: nativeuint;
fDeltaSeconds: nativeuint;
fThreadState: TScheduledThreadState;
private
procedure ExecuteThread( const Thread: IThread );
strict private //- IScheduledTaskWrapper -//
function getScheduledTask: IScheduledTask;
function getLastExecuted: nativeuint;
procedure setLastExecuted( const value: nativeuint );
procedure RunTask( const DeltaSeconds: nativeuint );
public
constructor Create( const ScheduledTask: IScheduledTask; const DeltaSeconds: nativeuint );
destructor Destroy; override;
end;
implementation
uses
{$ifdef MSWINDOWS}
cwThreading.SignaledCriticalSection.Windows
, cwThreading.Internal.Thread.Windows
{$else}
cwThreading.SignaledCriticalSection.Posix
, cwThreading.Internal.Thread.Posix
{$endif}
;
procedure TScheduledTaskWrapper.ExecuteThread(const Thread: IThread);
begin
try
repeat
Thread.Acquire;
try
Thread.Sleep;
try
if fThreadState<>tsRunning then exit;
fLastExecuted := fDeltaSeconds;
fScheduledTask.Execute(fDeltaSeconds);
finally
end;
finally
Thread.Release;
end;
until fThreadState<>tsRunning;
finally
fThreadState := tsTerminated;
end;
end;
function TScheduledTaskWrapper.getScheduledTask: IScheduledTask;
begin
Result := fScheduledTask;
end;
function TScheduledTaskWrapper.getLastExecuted: nativeuint;
begin
Result := fLastExecuted;
end;
procedure TScheduledTaskWrapper.setLastExecuted( const value: nativeuint );
begin
fLastExecuted := Value;
end;
procedure TScheduledTaskWrapper.RunTask(const DeltaSeconds: nativeuint);
begin
fDeltaSeconds := DeltaSeconds;
if (fScheduledTask.IntervalSeconds=0) then exit;
if (fDeltaSeconds>=fLastExecuted+fScheduledTask.IntervalSeconds) then begin
fThread.Wake;
end;
end;
constructor TScheduledTaskWrapper.Create(const ScheduledTask: IScheduledTask; const DeltaSeconds: nativeuint );
begin
inherited Create;
fThreadState := tsRunning;
fLastExecuted := DeltaSeconds;
fDeltaSeconds := 0;
fScheduledTask := ScheduledTask;
fThreadCS := TSignaledCriticalSection.Create;
fThread := TThread.Create(ExecuteThread,fThreadCS);
end;
destructor TScheduledTaskWrapper.Destroy;
begin
fThreadState := tsTerminating;
while fThreadState<>tsTerminated do fThread.Wake;
fThreadCS := nil;
fThread := nil;
fScheduledTask := nil;
inherited Destroy;
end;
end.
|
unit UConstantes;
interface
const
TAM_BLOCO = 32;
LINHAS = 10;
COLUNAS = 100;
var
Numero_Blocos: integer = 0;
Fase: array[0..LINHAS-1,0..COLUNAS-1] of integer;
implementation
end.
|
unit newItemUnit;
interface
uses
Windows,
Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, Buttons, Menus, TypesUnit, FrameNewItems,
HelperUnit, iniFiles, TypInfo;
type
TnewItems = class(TForm)
PopupMenu: TPopupMenu;
menuNewItem: TMenuItem;
menuRemoveTab: TMenuItem;
N1: TMenuItem;
menuDeleteItem: TMenuItem;
PageControl: TPageControl;
btAdd: TBitBtn;
menuNewTab: TMenuItem;
btClose: TBitBtn;
procedure menuNewItemClick(Sender: TObject);
procedure btAddClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure menuNewTabClick(Sender: TObject);
procedure menuDeleteItemClick(Sender: TObject);
procedure menuRemoveTabClick(Sender: TObject);
procedure btCloseClick(Sender: TObject);
procedure PopupMenuPopup(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function AddPage(v:string):TNewItemSheet;
function AddItem(p:TNewItemSheet;v:string):TNewItem;
procedure Read;
procedure Write;
end;
var
newItems: TnewItems;
implementation
{$R *.dfm}
uses MainUnit, ContainerUnit, LauncherUnit;
function TnewItems.AddPage(v:string):TNewItemSheet;
begin
result:=TNewItemSheet.Create(PageControl);
result.Caption:=v;
result.PageControl:=PageControl;
end;
function TNewItems.AddItem(p:TNewItemSheet; v:string):TNewItem;
var
Lw:TListView;
Li:TListItem;
begin
result:=nil;
if p<>nil then begin
result:=TNewItem.Create;
result.Name:=v;
Lw:=TListView(TFrameNewI(p.Controls[0]).Controls[0]);
if Lw<>nil then begin
Li:=Lw.Items.Add;
Li.Data:=result;
Li.Caption:=v;
end
end
end;
procedure TnewItems.Read;
var
L,B,IT:TStrings;
s,p,v:string;
i,j,k:integer;
Pg:TNewItemSheet;
item:TNewItem;
begin
L:=TStringList.Create;
B:=TStringList.Create;
IT:=TStringList.Create;
with TIniFile.Create(ideDir+'newItems\newitems.ini') do begin
ReadSection('Pages',L);
if L.Count=0 then begin Free ;exit; end;
for i:=0 to L.Count-1 do begin
Pg:=AddPage(L[i]);
ReadSection(L[i],B);
for j:=0 to B.Count-1 do begin
item:=AddItem(Pg,B[j]);
ReadSectionValues(B[j],IT);
for k:=0 to IT.Count-1 do begin
p:=copy(IT[k],1,pos('=',IT[k])-1);
v:=copy(IT[k],pos('=',IT[k])+1,length(IT[k]));
if GetPropInfo(item,p)<>nil then
SetPropValue(item,p,v);
end
end
end;
Free;
end;
L.Free;
B.Free;
IT.Free;
end;
procedure TnewItems.Write;
var
i,j:integer;
Lw:TListView;
begin
with TIniFile.Create(ideDir+'newItems\newitems.ini') do begin
for i:=0 to PageControl.PageCount-1 do begin
WriteString('Pages',PageControl.Pages[i].Caption,inttostr(i));
Lw:=TListView(TFrameNewI(PageControl.Pages[i].Controls[0]).Controls[0]);
for j:=0 to Lw.Items.Count-1 do begin
WriteString(PageControl.Pages[i].Caption,Lw.Items[j].Caption,inttostr(j));
WriteString(Lw.Items[j].Caption,'CodeFile',TNewItem(Lw.Items[j].Data).CodeFile);
end;
end;
Free
end
end;
procedure TnewItems.menuNewItemClick(Sender: TObject);
var
s :string;
T :TNewItemSheet;
Ni :TNewItem;
Li :TListItem;
function FindItem(v:string):TListItem;
var
i,j:integer;
Lw:TListView;
begin
result:=nil;
for i:=0 to PageControl.PageCount-1 do begin
Lw:=TListView(TFrameNewI(PageControl.Pages[i].Controls[0]).Controls[0]);
if Lw<>nil then
for j:=0 to Lw.Items.Count-1 do
if compareText(Lw.Items[i].Caption,v)=0 then begin
result:=Lw.Items[i];
break
end
end
end;
begin
T := TNewItemSheet(PageControl.ActivePage);
if T= nil then begin
s:=NamesList.AddName('myItems');// GetIdx('myItems');
if InputQuery('Add New Item','Name Tab:',s)then begin
T :=TNewItemSheet.Create(PageControl);
T.Caption:= s;
T.PageControl:=PageControl;
Ni := TNewItem.Create;
s:=NamesList.AddName('myItem');//GetIdx('myItem');
if InputQuery('Add New Item','Name Item:',s) then begin
if FindItem(s)<>nil then begin
messageDlg('Exists.',mtInformation,[mbok],0)
end else begin
Ni.Name :=s;
Li := TNewItemSheet(T).Frame.ListView.Items.Add;
Ni.Owner:=Li;
Li.Caption := Ni.Name;
Li.Data := Ni;
end
end;
end;
end else begin
Ni := TNewItem.Create;
s:=NamesList.AddName('myItem');//GetIdx('myItem');
if InputQuery('Add New Item','Name Item:',s) then begin
if FindItem(s)<>nil then begin
messageDlg('Exists.',mtInformation,[mbok],0)
end else begin
Ni.Name :=s;
Li := TNewItemSheet(T).Frame.ListView.Items.Add;
Ni.Owner:=Li;
Li.Caption := Ni.Name;
Li.Data := Ni;
end
end;
end;
end;
procedure TnewItems.btAddClick(Sender: TObject);
begin
menuNewItem.Click
end;
procedure TnewItems.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Write;
end;
procedure TnewItems.FormShow(Sender: TObject);
begin
Read
end;
procedure TnewItems.menuNewTabClick(Sender: TObject);
var
T :TNewItemSheet;
s :string;
function Find(v :string):TNewItemSheet;
var
i :integer;
begin
result:=nil;
for i :=0 to PageControl.PageCount-1 do
if CompareText(PageControl.Pages[i].Caption,v)=0 then begin
result :=TNewItemSheet(PageControl.Pages[i]);
end;
end;
begin
s:=NamesList.AddName('myTabItems');{GetIdx('myItems'); T := Find(s)};
if InputQuery('Add New Items Tab','Name Tab:',s)then begin
if Find(s)<>nil then begin
PageControl.ActivePage:=Find(s)
end else begin
T :=TNewItemSheet.Create(PageControl);
T.Caption:= s;
T.PageControl:=PageControl;
PageControl.ActivePage:=T;
end
end;
end;
procedure TnewItems.menuDeleteItemClick(Sender: TObject);
var
Ti :TNewItemSheet;
ini :TIniFile;
s :string;
begin
Ti := TNewItemSheet(PageControl.ActivePage);
s:=ExtractFilePath(ParamStr(0))+'newitems\'+Ti.Name+'.ini';
ini:=TiniFile.Create(s);
if Ti.Frame.ListView.Selected<>nil then begin
TNewItem(Ti.Frame.ListView.Selected.Data).Free;
ini.EraseSection(Ti.Frame.ListView.Selected.Caption);
Ti.Frame.ListView.Selected.Free;
end;
ini.Free;
end;
procedure TnewItems.menuRemoveTabClick(Sender: TObject);
var
Ti :TNewItemSheet;
i :integer;
ini :TIniFile;
s :string;
begin
Ti := TNewItemSheet(PageControl.ActivePage);
if Ti<>nil then begin
s := ExtractFilePath(ParamStr(0))+'newitems\'+Ti.Name+'.ini';
ini:=TiniFile.Create(s);
for i:=Ti.Frame.ListView.Items.Count-1 downto 0 do begin
ini.EraseSection(Ti.Frame.ListView.Items[i].Caption);
TNewItems(Ti.Frame.ListView.Items[i].Data).Free;
end;
Ti.Free;
DeleteFile(s);
end;
end;
procedure TnewItems.btCloseClick(Sender: TObject);
begin
Close
end;
procedure TnewItems.PopupMenuPopup(Sender: TObject);
begin
menuRemoveTab.Enabled:= (PageControl.PageCount>0) and (PageControl.ActivePageIndex>-1);
menuDeleteItem.Enabled := (PageControl.ActivePageIndex>-1) and (TNewItemSheet(PageControl.ActivePage).Frame.ListView.Selected<>nil);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.