text stringlengths 14 6.51M |
|---|
unit FPReadJPEGTurbo;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FPImage, ctypes, turbojpeg, GraphType;
type
{ TFPReaderJPEGTurbo }
{ This is a FPImage reader for jpeg images. }
TJPEGScale = (jsFullSize, jsHalf, jsQuarter, jsEighth);
TJPEGReadPerformance = (jpBestQuality, jpBestSpeed);
TFPReaderJPEGTurbo = class(TFPCustomImageReader)
private
FSmoothing: boolean;
FWidth: Integer;
FHeight: Integer;
FGrayscale: boolean;
FScale: TJPEGScale;
FPerformance: TJPEGReadPerformance;
procedure SetPerformance(const AValue: TJPEGReadPerformance);
procedure SetSmoothing(const AValue: boolean);
protected
procedure InternalRead(Str: TStream; Img: TFPCustomImage); override;
function InternalCheck(Str: TStream): boolean; override;
class function InternalSize(Str: TStream): TPoint; override;
public
constructor Create; override;
destructor Destroy; override;
property GrayScale: boolean read FGrayscale;
property Scale: TJPEGScale read FScale write FScale;
end;
implementation
uses
IntfGraphics;
{ TFPReaderJPEGTurbo }
procedure TFPReaderJPEGTurbo.SetSmoothing(const AValue: boolean);
begin
if FSmoothing=AValue then exit;
FSmoothing:=AValue;
end;
procedure TFPReaderJPEGTurbo.SetPerformance(const AValue: TJPEGReadPerformance);
begin
if FPerformance=AValue then exit;
FPerformance:=AValue;
end;
procedure TFPReaderJPEGTurbo.InternalRead(Str: TStream; Img: TFPCustomImage);
type
TRGBAQuad = record
Blue: Byte;
Green: Byte;
Red: Byte;
Alpha: Byte;
end;
PRGBAQuad = ^TRGBAQuad;
const
ScaleFactors: array[TJPEGScale] of tjscalingfactor = (
(num:1; denom:1),
(num:1; denom:2),
(num:1; denom:4),
(num:1; denom:8)
);
var
MemStream: TMemoryStream;
jpegDecompressor: tjhandle;
Continue: Boolean;
scFact: tjscalingfactor;
procedure ReadHeader;
var
jpegWidth: cint;
jpegHeight: cint;
jpegSubsamp, jpegColorspace: cint;
begin
tjDecompressHeader3(jpegDecompressor, MemStream.Memory,MemStream.Size, @jpegWidth, @jpegHeight, @jpegSubsamp, @jpegColorspace);
FWidth := jpegWidth;
FHeight := jpegHeight;
FGrayscale := jpegColorspace = cint(TJCS_GRAY);
end;
procedure ReadPixelsGeneric;
var
outData: TMemoryStream;
y, x: Integer;
lColor: TFPColor;
mp: PRGBAQuad;
begin
outData:= TMemoryStream.Create;
try
outData.SetSize(FWidth*FHeight*sizeof(TRGBAQuad));
tjDecompress2(jpegDecompressor, MemStream.Memory, MemStream.Size, outData.Memory, FWidth, 0, FHeight, cint(TJPF_BGRX), TJFLAG_FASTDCT);
mp:= outData.Memory;
for y := 0 to FHeight - 1 do begin
for x := 0 to FWidth - 1 do begin
lColor.alpha:= alphaOpaque;
lColor.blue:= mp^.Blue or mp^.Blue shl 8;
lColor.green:= mp^.Green or mp^.Green shl 8;
lColor.red:= mp^.Red or mp^.Red shl 8;
Img.Colors[x, y] := lColor;
inc(mp);
end;
end;
finally
FreeAndNil(outData);
end;
end;
procedure ReadPixelsLazIntfImage;
var
li: TLazIntfImage;
fmt: TJPF;
rd: TRawImageDescription;
lo: cint;
begin
fmt:= TJPF(-1);
li:= TLazIntfImage(Img);
rd:= li.DataDescription;
if (rd.Format = ricfRGBA) then begin
if rd.Depth = 24 then begin
if rd.RedShift=0 then
fmt:= TJPF_RGB
else
fmt:= TJPF_BGR;
end else
if rd.Depth = 32 then begin
if rd.RedShift=0 then
fmt:= TJPF_RGBA
else
fmt:= TJPF_BGRA;
end;
if rd.LineOrder = riloTopToBottom then
lo:= 0
else
lo:= TJFLAG_BOTTOMUP;
end;
if cint(fmt) >= 0 then begin
//FillChar(li.PixelData^, rd.BytesPerLine*FHeight, 0);
tjDecompress2(jpegDecompressor, MemStream.Memory, MemStream.Size, li.PixelData, FWidth, rd.BytesPerLine, FHeight, cint(fmt), TJFLAG_FASTDCT or lo)
end
else
ReadPixelsGeneric;
end;
begin
FWidth:=0;
FHeight:=0;
MemStream:=nil;
try
if Str is TMemoryStream then
MemStream:=TMemoryStream(Str)
else begin
MemStream:=TMemoryStream.Create;
MemStream.CopyFrom(Str, 0);
MemStream.Position:=0;
end;
if MemStream.Size > 0 then begin
jpegDecompressor := tjInitDecompress();
try
ReadHeader;
Continue:= true;
Progress(psStarting, 0, False, Rect(0,0,0,0), '', Continue);
if not Continue then
exit;
scFact:= ScaleFactors[FScale];
FWidth:= TJSCALED(FWidth, scFact);
FHeight:= TJSCALED(FHeight, scFact);
Img.SetSize(FWidth, FHeight);
if Img is TLazIntfImage then
ReadPixelsLazIntfImage
else
ReadPixelsGeneric;
Progress(psEnding, 100, false, Rect(0,0,0,0), '', Continue);
finally
tjDestroy(jpegDecompressor);
end;
end;
finally
if (MemStream<>nil) and (MemStream<>Str) then
MemStream.Free;
end;
end;
class function TFPReaderJPEGTurbo.InternalSize(Str: TStream): TPoint;
var
jpegDecompressor: tjhandle;
jpegWidth: cint;
jpegHeight: cint;
jpegSubsamp, jpegColorspace: cint;
pHeader: Pointer;
hSize: LongInt;
begin
jpegDecompressor := tjInitDecompress();
try
GetMem(pHeader, 16*1024);
try
hSize:= Str.Read(pHeader^, 16*1024);
tjDecompressHeader3(jpegDecompressor, pHeader, hSize, @jpegWidth, @jpegHeight, @jpegSubsamp, @jpegColorspace);
Result.X:= jpegWidth;
Result.Y:= jpegHeight
finally
Freemem(pHeader);
end;
finally
tjDestroy(jpegDecompressor);
end;
end;
function TFPReaderJPEGTurbo.InternalCheck(Str: TStream): boolean;
var
Buf: array[0..1] of Byte = (0, 0);
p: Int64;
begin
if Str=nil then exit(false);
p:=Str.Position;
Result := (Str.Read(Buf, 2)=2) and (Buf[0]=$FF) and (Buf[1]=$D8); // byte sequence FFD8 = start of image
Str.Position:=p;
end;
constructor TFPReaderJPEGTurbo.Create;
begin
inherited Create;
FScale:= jsFullSize;
end;
destructor TFPReaderJPEGTurbo.Destroy;
begin
inherited Destroy;
end;
initialization
ImageHandlers.UnregisterImageHandlers('JPEG Graphics', true, false);
ImageHandlers.RegisterImageReader('JPEG Graphics (Turbo)', 'jpg;jpeg', TFPReaderJPEGTurbo);
end.
|
unit uStaticFunction;
interface
uses
SysUtils, Grids, Controls, Classes, uMyTools;
function GetOperaterResult(dTotalValue, dOneValue: Double): Double; overload;
function GetOperaterResult(dTotalValue, dOneValue: Integer): Integer; overload;
function GetPercentFormat(AValue: Double; ABitInt: Integer = 2): string;
function GetFloatFormat(AValue: Double; ABitInt: Integer = 4): string;
function FormatDBDate(Value: TDateTime): string;
function FormatDBDateTime(Value: TDateTime): string;
//------------------------------------------------------------------------------
//StringGrid排序函数
procedure GridQuickSort(Grid: TStringGrid; ACol: Integer; Order: Boolean ; NumOrStr: Boolean);
procedure StringGridTitleDown(Sender: TObject;
Button: TMouseButton; X, Y: Integer);
//------------------------------------------------------------------------------
implementation
function GetOperaterResult(dTotalValue, dOneValue: Double): Double; overload;
begin
Result := dTotalValue + dOneValue;
end;
function GetOperaterResult(dTotalValue, dOneValue: Integer): Integer; overload;
begin
Result := dTotalValue + dOneValue;
end;
function GetPercentFormat(AValue: Double; ABitInt: Integer = 2): string;
var
sFormat: string;
begin
sFormat := Format('%%.%df', [ABitInt]);
Result := Format(sFormat, [(AValue * 100)]) + '%';
end;
function GetFloatFormat(AValue: Double; ABitInt: Integer = 4): string;
begin
Result := Format('%%.%df', [ABitInt]);
Result := Format(Result, [AValue]);
end;
function FormatDBDate(Value: TDateTime): string;
begin
Result := FormatDateTime('YYYY-MM-DD', Value);
end;
function FormatDBDateTime(Value: TDateTime): string;
begin
Result := FormatDateTime('YYYY-MM-DD HH:NN:SS.ZZZ', Value);
end;
//------------------------------------------------------------------------------
//StringGrid排序函数
// Added by zhbgt 2015-04-06 16:26:58
procedure GridQuickSort(Grid: TStringGrid; ACol: Integer; Order: Boolean ; NumOrStr: Boolean);
(******************************************************************************)
(* 函数名称:GridQuickSort *)
(* 函数功能:给 StringGrid 的 ACol 列快速法排序 _/_/ _/_/ _/_/_/_/_/ *)
(* 参数说明: _/ _/ _/ *)
(* Order: True 从小到大 _/ _/ *)
(* : False 从大到小 _/ _/ *)
(* NumOrStr : true 值的类型是Integer _/_/ _/_/ *)
(* : False 值的类型是String *)
(* 函数说明:对于日期,时间等类型数据均可按字符方式排序, *)
(* *)
(* *)
(* Author: YuJie 2001-05-27 *)
(* Email : yujie_bj@china.com *)
(******************************************************************************)
procedure MoveStringGridData(Grid: TStringGrid; Sou,Des :Integer );
var
TmpStrList: TStringList ;
K : Integer ;
begin
try
TmpStrList :=TStringList.Create() ;
TmpStrList.Clear ;
for K := Grid.FixedCols to Grid.ColCount -1 do
TmpStrList.Add(Grid.Cells[K,Sou]) ;
Grid.Rows [Sou] := Grid.Rows [Des] ;
for K := Grid.FixedCols to Grid.ColCount -1 do
Grid.Cells [K,Des]:= TmpStrList.Strings[K] ;
finally
TmpStrList.Free ;
end;
end;
procedure QuickSort(Grid: TStringGrid; iLo, iHi: Integer);
var
Lo, Hi : Integer;
Mid: String ;
begin
Lo := iLo ;
Hi := iHi ;
Mid := Grid.Cells[ACol,(Lo + Hi) div 2];
repeat
if Order and not NumOrStr then //按正序、字符排
begin
while Grid.Cells[ACol,Lo] < Mid do Inc(Lo);
while Grid.Cells[ACol,Hi] > Mid do Dec(Hi);
end ;
if not Order and not NumOrStr then //按反序、字符排
begin
while Grid.Cells[ACol,Lo] > Mid do Inc(Lo);
while Grid.Cells[ACol,Hi] < Mid do Dec(Hi);
end;
if NumOrStr then
begin
if Grid.Cells[ACol,Lo] = '' then Grid.Cells[ACol,Lo] := '0' ;
if Grid.Cells[ACol,Hi] = '' then Grid.Cells[ACol,Hi] := '0' ;
if Mid = '' then Mid := '0' ;
if Order then
begin //按正序、数字排
while StrToFloat(Grid.Cells[ACol,Lo]) < StrToFloat(Mid) do Inc(Lo);
while StrToFloat(Grid.Cells[ACol,Hi]) > StrToFloat(Mid) do Dec(Hi);
end else
begin //按反序、数字排
while StrToFloat(Grid.Cells[ACol,Lo]) > StrToFloat(Mid) do Inc(Lo);
while StrToFloat(Grid.Cells[ACol,Hi]) < StrToFloat(Mid) do Dec(Hi);
end;
end ;
if Lo <= Hi then
begin
MoveStringGridData(Grid, Lo, Hi) ;
Inc(Lo);
Dec(Hi);
end;
until Lo > Hi;
if Hi > iLo then QuickSort(Grid, iLo, Hi);
if Lo < iHi then QuickSort(Grid, Lo, iHi);
end;
begin
try
QuickSort(Grid, Grid.FixedRows, Grid.RowCount - 1 ) ;
except
on E: Exception do
DlgError('系统在排序数据的时候遇到异常:'#13+E.message);
//Application.MessageBox(Pchar('系统在排序数据的时候遇到异常:'#13+E.message+#13'请重试,如果该问题依然存在请与程序供应商联系!'),'系统错误',MB_OK+MB_ICONERROR) ;
end;
end;
procedure StringGridTitleDown(Sender: TObject;
Button: TMouseButton; X, Y: Integer);
(******************************************************************************)
(* 函数名称:StringGridTitleDown *)
(* 函数功能:取鼠标点StringGrid 的列 _/_/ _/_/ _/_/_/_/_/ *)
(* 参数说明: _/ _/ _/ *)
(* Sender _/ _/ *)
(* _/ _/ *)
(* _/_/ _/_/ *)
(* *)
(* *)
(* Author: YuJie 2001-05-27 *)
(* Email : yujie_bj@china.com *)
(******************************************************************************)
var
I: Integer ;
begin
if (Y > 0 ) and (y < TStringGrid(Sender).DefaultRowHeight * TStringGrid(Sender).FixedRows ) then
begin
if Button = mbLeft then
begin
I := X div TStringGrid(Sender).DefaultColWidth ;
//这个i 就是要排序得行了
// 下面调用上面的排序函数就可以了,
GridQuickSort(TStringGrid(Sender), I, False, True) ;
end;
end;
end;
end.
|
{*======================================================================*
| PropertyPageForm |
| |
| Base class for property forms that live on a PropertyBaseForm |
| |
| When deriving a property page: |
| |
| 1. Create a data class, derived from TPropertyPageData. This |
| holds the data for the form, until it is applied. |
| |
| 2. Override the data classes Initialize method to initialize the |
| data. Initialize it from your options directly, or from the |
| data in 'Param' - a general purpose pointer optionally passed |
| in TPropertyBaseForm.AddPropertyPageDetails. |
| |
| 3. Override the data classes Apply method to apply the data to |
| your options. Return false if the data can't be applied. |
| |
| 4. Override the pages GetDataClass method to return your data |
| class type. |
| |
| 5. Override the pages PopulateControls method. You *must* first |
| call inherited PopulateControls. Then save the data ('as' the |
| required type) in a local variable, then populate the page's |
| controls. |
| |
| 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. |
| |
| Copyright © Colin Wilson 2005,2006 All Rights Reserved |
| |
| Version Date By Description |
| ------- ---------- ---- ------------------------------------------|
| 1.0 19/01/2005 CPWW Original |
| 1.1 01/02/2006 CPWW Generic version |
*======================================================================*}
unit PropertyPageForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TPropertyPageData = class
private
fCaption: string;
fHelpText: string;
fHelpKeyword : string;
fParam: Integer;
fMinX : Integer;
fMinY : Integer;
fInitialized : boolean;
protected
property Param : Integer read fParam;
procedure Initialize; virtual;
function GetCaption: string; virtual;
function GetHelpText: string; virtual;
public
constructor Create (const ACaption, AHelpText, AHelpKeyword : string; AMinCX, AMinCY : Integer; AParam : Integer = 0);
function Apply : boolean; virtual;
procedure Cancel; virtual;
procedure Error; virtual;
property Caption : string read GetCaption;
property Initialized : boolean read fInitialized write fInitialized;
property HelpText : string read GetHelpText;
property HelpKeyword : string read fHelpKeyword;
property MinX : Integer read fMinX;
property MinY : Integer read fMinY;
end;
TPropertyPageDataClass = class of TPropertyPageData;
TfmPropertyPage = class(TForm)
Panel1: TPanel;
Bevel1: TBevel;
stSectionDetails: TLabel;
private
fAltKeyword : string;
protected
fPopulating : boolean;
public
class function GetDataClass : TPropertyPageDataClass; virtual; abstract;
procedure PopulateControls (AData : TPropertyPageData); virtual;
property Populating : boolean read fPopulating write fPopulating;
property AltKeyword : string read fAltKeyword;
end;
TPropertyPageClass = class of TfmPropertyPage;
var
fmPropertyPage: TfmPropertyPage;
implementation
{$R *.dfm}
{ TfmPropertyPage }
procedure TfmPropertyPage.PopulateControls (AData : TPropertyPageData);
begin
if not AData.fInitialized then
begin
AData.Initialize;
AData.fInitialized := True
end;
stSectionDetails.Caption := AData.HelpText;
fAltKeyword := AData.HelpKeyword;
end;
{ TPropertyPageData }
function TPropertyPageData.Apply : boolean;
begin
result := True; // Stub - return true to indicate success
end;
procedure TPropertyPageData.Cancel;
begin
// Stub
end;
constructor TPropertyPageData.Create(const ACaption, AHelpText, AHelpKeyword: string; AMinCX, AMinCY : Integer;
AParam: Integer);
begin
fCaption := ACaption;
fHelpText := AHelpText;
fHelpKeyword := AHelpKeyword;
fParam := AParam;
fMiNX := AMinCX;
fMinY := AMinCY;
end;
procedure TPropertyPageData.Error;
begin
// Stub
end;
function TPropertyPageData.GetCaption: string;
begin
result := fCaption
end;
function TPropertyPageData.GetHelpText: string;
begin
result := fHelpText
end;
procedure TPropertyPageData.Initialize;
begin
// Stub
end;
end.
|
{ complete compress -- compress dictionary by taking advantage of common roots }
program compressprog (input, output);
const
ENDFILE = -1;
NEWLINE = 10; { ASCII value }
TILDE = 126;
type
character = -1..127; { ASCII, plus ENDFILE }
{ getc -- get one character from standard input }
function getc (var c : character) : character;
var
ch : char;
begin
if (eof) then
c := ENDFILE
else if (eoln) then begin
readln;
c := NEWLINE
end
else begin
read(ch);
c := ord(ch)
end;
getc := c
end;
{ putc -- put one character on standard output }
procedure putc (c : character);
begin
if (c = NEWLINE) then
writeln
else
write(chr(c))
end;
{ getl -- get one line from standard input }
function getl (var s : string) : string;
begin
readln(s);
getl := s
end;
{ min -- compute minimum of two integers }
function min(x, y : integer) : integer;
begin
if (x < y) then
min := x
else
min := y
end;
{ compress -- compress standard input }
procedure compress;
const
WARNING = TILDE; { ~ }
var
l, lastl : string;
n : integer;
{ countcommon -- count number of characters in common from te start between two strings }
function countcommon (str1 : string; str2 : string) : integer;
var
i, ctr : integer;
begin
ctr := 0;
for i := 1 to length(str2) do
if (copy(str1, i, 1) = copy(str2, i, 1)) then
ctr := ctr + 1;
countcommon := ctr
end;
{ putline -- print counter for common prefix and rest of line }
procedure putline (N : integer; s : string);
const
MAXREP = 94;
var
offset : integer;
begin
offset := 1;
putc(min(N, MAXREP) + ord(' '));
offset := offset + min(N, MAXREP);
writeln(copy(s, offset, length(s) - offset + 1))
end;
begin
n := 1;
getl(lastl);
writeln(lastl);
while (getl(l) <> '') do begin
n := countcommon(lastl, l);
putline(n, l);
lastl := l
end
end;
begin { main program }
compress
end.
|
unit BigAltGrCrashWorkaround;
interface
implementation
uses
BigProcHook, Menus;
var
FHook: TBigProcHook;
// The replacement function
function SafeIsAltGrPressed: Boolean;
begin
try
FHook.Hooked := False;
try
Result := IsAltGRPressed;
finally
FHook.Hooked := True;
end;
except
// Exception: Error when reading keyboard layout dll.
Result := False;
end;
end;
initialization
FHook := TBigProcHook.Create(@IsAltGRPressed, @SafeIsAltGrPressed);
finalization
FHook.Hooked := False;
FHook.Free;
end.
|
unit Btn360;
interface
uses
SysUtils, Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls,
Vcl.Buttons, ColorUtils, Messages, Windows, GDIPAPI, GDIPOBJ, GDIPUTIL, Vcl.StdCtrls;
type
TBtn360Style = class(TButton)
private
FBkgColor: TColor; // 鼠标悬停是的背景颜色
FEdgColor: TColor; // 边框颜色
FCanvas: TCanvas;
FMouseEnter: Boolean;
FPngFileName: string;
procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM;
procedure SetPngFileName(const Value: string);
procedure SetBkgColor(const Value: TColor);
procedure SetEdgColor(const Value: TColor);
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure SetButtonStyle(ADefault: Boolean); override; // 必须重新找个函数 否则会按默认样式绘制
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property PngFileName: string read FPngFileName write SetPngFileName;
property BkgColor: TColor read FBkgColor write SetBkgColor;
property EdgColor: TColor read FEdgColor write SetEdgColor;
end;
procedure Register;
implementation
constructor TBtn360Style.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
DoubleBuffered := True;
FCanvas := TCanvas.Create;
FBkgColor := clBlue;
FEdgColor := clSkyBlue;
end;
destructor TBtn360Style.Destroy;
begin
FCanvas.Free;
inherited Destroy;
end;
procedure TBtn360Style.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
with Params do
Style := Style or BS_OWNERDRAW;
end;
procedure TBtn360Style.SetEdgColor(const Value: TColor);
begin
if FEdgColor <> Value then
begin
FEdgColor := Value;
Invalidate;
end;
end;
procedure TBtn360Style.SetBkgColor(const Value: TColor);
begin
if FBkgColor <> Value then
begin
FBkgColor := Value;
Invalidate;
end;
end;
procedure TBtn360Style.SetButtonStyle(ADefault: Boolean);
begin
if csDesigning in ComponentState then
inherited;
end;
procedure TBtn360Style.SetPngFileName(const Value: string);
begin
if FPngFileName <> Value then
begin
FPngFileName := Value;
Invalidate;
end;
end;
procedure TBtn360Style.CMMouseEnter(var Message: TMessage);
begin
inherited;
FMouseEnter := True;
Invalidate;
end;
procedure TBtn360Style.CMMouseLeave(var Message: TMessage);
begin
inherited;
FMouseEnter := False;
Invalidate;
end;
procedure TBtn360Style.CNDrawItem(var Message: TWMDrawItem);
var
IsDown: Boolean;
ARect: TRect;
DrawItemStruct: TDrawItemStruct;
wh: TSize;
g: TGPGraphics;
pen: TGPPen;
img: TGPImage;
img2: TGPBitmap;
imgAtt: TGPImageAttributes;
i, j: Integer;
const
ColorMatrix: TColorMatrix = ((1.0, 0.0, 0.0, 0.0, 0.0), (0.0, 1.0, 0.0, 0.0, 0.0), (0.0, 0.0, 1.0, 0.0, 0.0), (0.0, 0.0, 0.0, 1.0, 0.0), (1.0, 0.0, 0.0, 0.0, 1.0));
begin
DrawItemStruct := Message.DrawItemStruct^;
FCanvas.Handle := DrawItemStruct.hDC;
g := TGPGraphics.Create(FCanvas.Handle);
pen := TGPPen.Create(GDIPAPI.MakeColor(128, FEdgColor and $FF, (FEdgColor shr 8) and $FF, (FEdgColor shr 16) and $FF));
img := TGPImage.Create(FPngFileName);
img2 := TGPBitmap.Create(Width, Height);
for i := 0 to img2.GetWidth do
for j := 0 to img2.GetHeight do
begin
color := GDIPAPI.MakeColor(128, FBkgColor and $FF, (FBkgColor shr 8) and $FF, (FBkgColor shr 16) and $FF);
img2.SetPixel(i, j, color);
end;
ARect := ClientRect;
with DrawItemStruct do
IsDown := itemState and ODS_SELECTED <> 0;
if FMouseEnter then // 鼠标在按钮上 则绘制一个背景及边框
begin
Perform($000B, 0, 0);
g.DrawImage(img2, 0, 0, Width, Height);
g.DrawRectangle(pen, 0, 0, Width - 1, Height - 1);
Perform($000B, 1, 0);
end;
// 按钮被按下时的状态绘制
if IsDown then
begin
imgAtt := TGPImageAttributes.Create;
imgAtt.SetColorMatrix(ColorMatrix, ColorMatrixFlagsDefault, ColorAdjustTypeDefault);
g.DrawImage(img, MakeRect(0, 0, img.GetWidth, img.GetHeight), -10, -10, img.GetWidth + 10, img.GetHeight + 10, UnitPixel, imgAtt);
FreeAndNil(imgAtt);
end
else // 绘制一个未按下的按钮
g.DrawImage(img, (Width - img.GetWidth) div 2, 10);
FreeAndNil(img);
FreeAndNil(img2);
FreeAndNil(g);
FreeAndNil(pen);
// 绘制 Caption 文本内容
FCanvas.Font := Self.Font;
ARect := ClientRect;
wh := FCanvas.TextExtent(Caption);
FCanvas.Pen.Width := 1;
FCanvas.Brush.Style := bsClear;
if not Enabled then
begin // 按钮失效时应多绘一次 Caption 文本
FCanvas.Font.Color := clBtnHighlight;
FCanvas.TextOut((Width div 2) - (wh.cx div 2), height - wh.cy - 10, Caption);
FCanvas.Font.Color := clBtnShadow;
end
else
FCanvas.TextOut((Width div 2) - (wh.cx div 2), height - wh.cy - 10, Caption);
FCanvas.Handle := 0;
end;
procedure Register;
begin
RegisterComponents('cactus', [TBtn360Style]);
end;
end.
|
unit TextEditor.CodeFolding.Ranges;
interface
uses
Winapi.Windows, System.Classes, System.SysUtils, TextEditor.CodeFolding.Regions;
type
TTextEditorCodeFoldingRange = class;
TTextEditorAllCodeFoldingRanges = class;
TTextEditorCodeFoldingRanges = class(TPersistent)
strict private
FList: TList;
function GetCount: Integer;
function GetItem(const AIndex: Integer): TTextEditorCodeFoldingRange;
public
constructor Create;
destructor Destroy; override;
function Add(const AAllCodeFoldingRanges: TTextEditorAllCodeFoldingRanges; const AFromLine, AIndentLevel, AFoldRangeLevel: Integer;
const ARegionItem: TTextEditorCodeFoldingRegionItem; const AToLine: Integer = 0): TTextEditorCodeFoldingRange;
procedure Clear;
property Count: Integer read GetCount;
property Items[const AIndex: Integer]: TTextEditorCodeFoldingRange read GetItem; default;
end;
TTextEditorAllCodeFoldingRanges = class(TTextEditorCodeFoldingRanges)
strict private
FList: TList;
function GetAllCount: Integer;
function GetItem(const AIndex: Integer): TTextEditorCodeFoldingRange;
procedure SetItem(const AIndex: Integer; const Value: TTextEditorCodeFoldingRange);
public
constructor Create;
destructor Destroy; override;
procedure ClearAll;
procedure Delete(const AFoldRange: TTextEditorCodeFoldingRange); overload;
procedure Delete(const AIndex: Integer); overload;
procedure SetParentCollapsedOfSubCodeFoldingRanges(const AFoldRange: TTextEditorCodeFoldingRange);
procedure UpdateFoldRanges;
property AllCount: Integer read GetAllCount;
property Items[const AIndex: Integer]: TTextEditorCodeFoldingRange read GetItem write SetItem; default;
property List: TList read FList;
end;
TTextEditorCodeFoldingRange = class
strict private
FAllCodeFoldingRanges: TTextEditorAllCodeFoldingRanges;
FCollapsed: Boolean;
FCollapsedBy: Integer;
FCollapseMarkRect: TRect;
FFoldRangeLevel: Integer;
FFromLine: Integer;
FIndentLevel: Integer;
FIsExtraTokenFound: Boolean;
FParentCollapsed: Boolean;
FRegionItem: TTextEditorCodeFoldingRegionItem;
FSubCodeFoldingRanges: TTextEditorCodeFoldingRanges;
FToLine: Integer;
FUndoListed: Boolean;
public
constructor Create;
destructor Destroy; override;
function Collapsable: Boolean;
procedure MoveBy(const ALineCount: Integer);
procedure MoveChildren(const ABy: Integer);
procedure SetParentCollapsedOfSubCodeFoldingRanges(const AParentCollapsed: Boolean; const ACollapsedBy: Integer);
procedure Widen(const ALineCount: Integer);
property AllCodeFoldingRanges: TTextEditorAllCodeFoldingRanges read FAllCodeFoldingRanges write FAllCodeFoldingRanges;
property Collapsed: Boolean read FCollapsed write FCollapsed default False;
property CollapsedBy: Integer read FCollapsedBy write FCollapsedBy;
property CollapseMarkRect: TRect read FCollapseMarkRect write FCollapseMarkRect;
property FoldRangeLevel: Integer read FFoldRangeLevel write FFoldRangeLevel;
property FromLine: Integer read FFromLine write FFromLine;
property IndentLevel: Integer read FIndentLevel write FIndentLevel;
property IsExtraTokenFound: Boolean read FIsExtraTokenFound write FIsExtraTokenFound default False;
property ParentCollapsed: Boolean read FParentCollapsed write FParentCollapsed;
property RegionItem: TTextEditorCodeFoldingRegionItem read FRegionItem write FRegionItem;
property SubCodeFoldingRanges: TTextEditorCodeFoldingRanges read FSubCodeFoldingRanges;
property ToLine: Integer read FToLine write FToLine;
property UndoListed: Boolean read FUndoListed write FUndoListed default False;
end;
implementation
uses
TextEditor.Utils;
{ TTextEditorAllCodeFoldingRanges }
constructor TTextEditorAllCodeFoldingRanges.Create;
begin
inherited;
FList := TList.Create;
end;
destructor TTextEditorAllCodeFoldingRanges.Destroy;
begin
FreeList(FList);
inherited;
end;
procedure TTextEditorAllCodeFoldingRanges.ClearAll;
begin
Clear;
ClearList(FList);
end;
procedure TTextEditorAllCodeFoldingRanges.Delete(const AFoldRange: TTextEditorCodeFoldingRange);
var
LIndex: Integer;
begin
for LIndex := FList.Count - 1 downto 0 do
if FList[LIndex] = AFoldRange then
begin
TTextEditorCodeFoldingRange(FList[LIndex]).Free;
FList[LIndex] := nil;
FList.Delete(LIndex);
Break;
end;
end;
procedure TTextEditorAllCodeFoldingRanges.Delete(const AIndex: Integer);
begin
FList.Delete(AIndex);
end;
function TTextEditorAllCodeFoldingRanges.GetAllCount: Integer;
begin
Result := FList.Count;
end;
function TTextEditorAllCodeFoldingRanges.GetItem(const AIndex: Integer): TTextEditorCodeFoldingRange;
begin
if Cardinal(AIndex) < Cardinal(FList.Count) then
Result := FList.List[AIndex]
else
Result := nil;
end;
procedure TTextEditorAllCodeFoldingRanges.SetItem(const AIndex: Integer; const Value: TTextEditorCodeFoldingRange);
begin
FList[AIndex] := Value;
end;
procedure TTextEditorAllCodeFoldingRanges.SetParentCollapsedOfSubCodeFoldingRanges(const AFoldRange: TTextEditorCodeFoldingRange);
var
LIndex: Integer;
LFoldRange: TTextEditorCodeFoldingRange;
begin
for LIndex := 0 to AllCount - 1 do
begin
LFoldRange := GetItem(LIndex);
if LFoldRange = AFoldRange then
Continue;
if LFoldRange.FromLine > AFoldRange.ToLine then
Break;
if (LFoldRange.FromLine > AFoldRange.FromLine) and (LFoldRange.FromLine <> AFoldRange.ToLine) then
LFoldRange.ParentCollapsed := True;
end;
end;
procedure TTextEditorAllCodeFoldingRanges.UpdateFoldRanges;
var
LIndex: Integer;
LFoldRange: TTextEditorCodeFoldingRange;
begin
for LIndex := 0 to AllCount - 1 do
begin
LFoldRange := GetItem(LIndex);
if Assigned(LFoldRange) then
LFoldRange.ParentCollapsed := False;
end;
for LIndex := 0 to AllCount - 1 do
begin
LFoldRange := GetItem(LIndex);
if Assigned(LFoldRange) and not LFoldRange.ParentCollapsed then
SetParentCollapsedOfSubCodeFoldingRanges(LFoldRange);
end;
end;
{ TTextEditorCodeFoldingRanges }
constructor TTextEditorCodeFoldingRanges.Create;
begin
inherited;
FList := TList.Create;
end;
destructor TTextEditorCodeFoldingRanges.Destroy;
begin
FList.Clear;
FList.Free;
FList := nil;
inherited;
end;
function TTextEditorCodeFoldingRanges.Add(const AAllCodeFoldingRanges: TTextEditorAllCodeFoldingRanges;
const AFromLine, AIndentLevel, AFoldRangeLevel: Integer;
const ARegionItem: TTextEditorCodeFoldingRegionItem; const AToLine: Integer): TTextEditorCodeFoldingRange;
begin
Result := TTextEditorCodeFoldingRange.Create;
with Result do
begin
FromLine := AFromLine;
ToLine := AToLine;
IndentLevel := AIndentLevel;
FoldRangeLevel := AFoldRangeLevel;
AllCodeFoldingRanges := AAllCodeFoldingRanges;
RegionItem := ARegionItem;
end;
FList.Add(Result);
AAllCodeFoldingRanges.List.Add(Result);
end;
procedure TTextEditorCodeFoldingRanges.Clear;
begin
FList.Clear;
end;
function TTextEditorCodeFoldingRanges.GetCount: Integer;
begin
Result := FList.Count;
end;
function TTextEditorCodeFoldingRanges.GetItem(const AIndex: Integer): TTextEditorCodeFoldingRange;
begin
Result := FList[AIndex];
end;
{ TTextEditorCodeFoldingRange }
function TTextEditorCodeFoldingRange.Collapsable: Boolean;
begin
Result := (FFromLine < FToLine) or RegionItem.TokenEndIsPreviousLine and (FFromLine = FToLine);
end;
constructor TTextEditorCodeFoldingRange.Create;
begin
inherited;
FSubCodeFoldingRanges := TTextEditorCodeFoldingRanges.Create;
FCollapsed := False;
FCollapsedBy := -1;
FIsExtraTokenFound := False;
FUndoListed := False;
end;
destructor TTextEditorCodeFoldingRange.Destroy;
begin;
FSubCodeFoldingRanges.Clear;
FSubCodeFoldingRanges.Free;
FSubCodeFoldingRanges := nil;
inherited;
end;
procedure TTextEditorCodeFoldingRange.MoveBy(const ALineCount: Integer);
begin
Inc(FFromLine, ALineCount);
Inc(FToLine, ALineCount);
end;
procedure TTextEditorCodeFoldingRange.MoveChildren(const ABy: Integer);
var
LIndex: Integer;
LCodeFoldingRange: TTextEditorCodeFoldingRange;
begin
for LIndex := 0 to FSubCodeFoldingRanges.Count - 1 do
begin
LCodeFoldingRange := FSubCodeFoldingRanges[LIndex];
if Assigned(LCodeFoldingRange) then
begin
LCodeFoldingRange.MoveChildren(ABy);
with FAllCodeFoldingRanges.List do
if LCodeFoldingRange.FParentCollapsed then
Move(IndexOf(LCodeFoldingRange), IndexOf(LCodeFoldingRange) + ABy);
end;
end;
end;
procedure TTextEditorCodeFoldingRange.SetParentCollapsedOfSubCodeFoldingRanges(const AParentCollapsed: Boolean; const ACollapsedBy: Integer);
var
LIndex: Integer;
LCodeFoldingRange: TTextEditorCodeFoldingRange;
begin
if Assigned(FSubCodeFoldingRanges) then
for LIndex := 0 to FSubCodeFoldingRanges.Count - 1 do
begin
LCodeFoldingRange := FSubCodeFoldingRanges[LIndex];
LCodeFoldingRange.SetParentCollapsedOfSubCodeFoldingRanges(AParentCollapsed, ACollapsedBy);
if (LCodeFoldingRange.FCollapsedBy = -1) or (LCodeFoldingRange.FCollapsedBy = ACollapsedBy) then
begin
LCodeFoldingRange.FParentCollapsed := AParentCollapsed;
with LCodeFoldingRange do
if not AParentCollapsed then
FCollapsedBy := -1
else
FCollapsedBy := ACollapsedBy;
end;
end;
end;
procedure TTextEditorCodeFoldingRange.Widen(const ALineCount: Integer);
begin
Inc(FToLine, ALineCount);
end;
end.
|
unit DrawUtils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, Math, LCLType, GraphUtil;
type
TPercent = 0..100;
TRGB = packed record
case byte of
0: (R, G, B: byte);
1: (Color: TColor);
end;
THLS = packed record
H,S: Byte;
case boolean of
True: (V: byte);
False: (L: byte);
end;
THSV=THLS;
function LightenColor(c: TColor; Val: TPercent): TColor;
function DarkenColor(c: TColor; Val: TPercent): TColor;
function BlackNWhite(c: TColor): TColor;
procedure DrawTextCenter(c: TCanvas; Width, Height: integer; Caption: string);
function RGBtoHSV(Col: TColor): THSV;
function HSVtoRGB(HSV: THSV): TColor;
procedure DrawGradientCircle(Canvas: TCanvas; ARect: TRect;
Color1, Color2: TColor; Vert: boolean = True); overload;
procedure DrawGradientCircle(Canvas: TCanvas; Left, Top, Radius: Integer;
Color1, Color2: TColor; Vert: boolean = True); overload;
procedure DrawRadient(Canvas: TCanvas; Left, Top, Radius: Integer; Color1, Color2: TColor);
procedure FillRadient(Canvas: TCanvas; ARect: TRect; Color1, Color2: TColor);
procedure DrawCircle(Canvas: TCanvas; Left, Top, Radius: Integer); inline;
procedure DrawOpacity(PosX, PosY: Integer; c: TCanvas; g: TGraphic; Opac: double);
implementation
procedure DrawOpacity(PosX, PosY: integer; c: TCanvas; g: TGraphic; Opac: double);
var
x, y: integer;
bmp: TBitmap;
r, r2: TRGB;
begin
bmp := TBitmap.Create;
try
bmp.Assign(g);
for y := 0 to bmp.Height do
for x := 0 to bmp.Width do
begin
r.Color := c.Pixels[PosX + X, PosY + y];
r2.Color := bmp.Canvas.Pixels[X, Y];
r.R:=round(r.R*(1-Opac)+r2.R*Opac);
r.G:=round(r.G*(1-Opac)+r2.G*Opac);
r.B:=round(r.B*(1-Opac)+r2.B*Opac);
c.Pixels[PosX + X, PosY + y]:=r.Color;
end;
finally
bmp.Free;
end;
end;
procedure DrawCircle(Canvas: TCanvas; Left, Top, Radius: Integer); inline;
begin
Canvas.Ellipse(Left-Radius, Top-Radius, Left+Radius, Top+Radius);
end;
procedure DrawRadient(Canvas: TCanvas; Left, Top, Radius: Integer; Color1, Color2: TColor);
function GetColVal(C1, C2, F1, F2: Integer): TColor;
var r1, r2, res: TRGB;
begin
r1.Color:=C1;
r2.Color:=C2;
res.r := Round(r1.r + (r2.r - r1.r) * F1 / (F2));
res.g := Round(r1.g + (r2.g - r1.g) * F1 / (F2));
res.b := Round(r1.b + (r2.b - r1.b) * F1 / (F2));
Result:=res.Color;
end;
var i: Integer;
begin
for i := Radius downto 0 do
begin
Canvas.Brush.Color:=GetColVal(Color2, Color1, i, Radius);
Canvas.Brush.Style:=bsSolid;
Canvas.Pen.Style:=psClear;
DrawCircle(Canvas, Left, Top, i);
end;
end;
procedure FillRadient(Canvas: TCanvas; ARect: TRect; Color1, Color2: TColor);
var bmp: TBitmap;
begin
bmp:=TBitmap.Create;
try
bmp.Width:=ARect.Right-ARect.Left;
bmp.Height:=ARect.Bottom-ARect.Top;
DrawRadient(bmp.Canvas, bmp.Width div 2, bmp.Height div 2,
round(sqrt(bmp.Height**2 + bmp.Width**2) / 2), Color1, Color2);
Canvas.Draw(ARect.Left, ARect.Top, bmp);
finally
bmp.Free;
end;
end;
procedure DrawGradientCircle(Canvas: TCanvas; Left, Top, Radius: Integer;
Color1, Color2: TColor; Vert: boolean = True);
begin
DrawGradientCircle(Canvas, Rect(Left-Radius, Top-Radius,
Left+Radius, Top+Radius), Color1, Color2, Vert);
end;
procedure DrawGradientCircle(Canvas: TCanvas; ARect: TRect;
Color1, Color2: TColor; Vert: boolean = True);
function GetRectV(Circle: TRect; Position: integer): TRect;
var
Mid, Wid, r: integer;
begin
Mid := (Circle.Right + Circle.Left) div 2;
r := abs(Circle.Right - Circle.Left) div 2;
Wid := trunc(sqrt(sqr(r) - sqr(Position - r)));
if Position - r = 0 then
wid -= 1;
if Wid = 1 then
Wid := 0;
Result.Top := Position + Circle.Top;
Result.Bottom := Result.Top + 1;
Result.Left := Mid - Wid;
Result.Right := Mid + Wid;
end;
function GetRectH(Circle: TRect; Position: integer): TRect;
var
Mid, Wid, r: integer;
begin
Mid := (Circle.Bottom + Circle.Top) div 2;
r := abs(Circle.Bottom - Circle.Top) div 2;
Wid := trunc(sqrt(sqr(r) - sqr(Position - r)));
if Position - r = 0 then
wid -= 1;
if Wid = 1 then
Wid := 0;
Result.Left := Position + Circle.Left;
Result.Right := Result.Left + 1;
Result.Top := Mid - Wid;
Result.Bottom := Mid + Wid;
end;
var
c1, c2, c: TRGB; //for easy access to RGB values as well as TColor value
x, y: integer; //current pixel position to be set
OldPenWidth: integer; //Save old settings to restore them properly
OldPenStyle: TPenStyle;//see above
begin
c1.Color := ColorToRGB(Color1); //convert system colors to RGB values
c2.Color := ColorToRGB(Color2); //if neccessary
OldPenWidth := Canvas.Pen.Width; //get old settings
OldPenStyle := Canvas.Pen.Style;
Canvas.Pen.Width := 1; //ensure correct pen settings
Canvas.Pen.Style := psInsideFrame;
case Vert of
True:
begin
for y := 0 to ARect.Bottom - ARect.Top do
begin
c.r := Round(c1.r + (c2.r - c1.r) * y / (ARect.Bottom - ARect.Top));
c.g := Round(c1.g + (c2.g - c1.g) * y / (ARect.Bottom - ARect.Top));
c.b := Round(c1.b + (c2.b - c1.b) * y / (ARect.Bottom - ARect.Top));
Canvas.Brush.Color := c.Color;
Canvas.FillRect(GetRectV(ARect, y));
end;
end;
False:
begin
for x := 0 to ARect.Right - ARect.Left do
begin
c.r := Round(c1.r + (c2.r - c1.r) * x / (ARect.Right - ARect.Left));
c.g := Round(c1.g + (c2.g - c1.g) * x / (ARect.Right - ARect.Left));
c.b := Round(c1.b + (c2.b - c1.b) * x / (ARect.Right - ARect.Left));
Canvas.Brush.Color := c.Color;
Canvas.FillRect(GetRectH(ARect, x));
end;
end;
end;
Canvas.Pen.Width := OldPenWidth; //restore old settings
Canvas.Pen.Style := OldPenStyle;
end;
function RGBtoHSV(Col: TColor): THSV;
begin
ColorToHLS(Col, Result.h, Result.L, Result.S);
end;
function HSVtoRGB(HSV: THSV): TColor;
begin
Result:=HLStoColor(HSV.H, HSV.L, HSV.S);
end;
function BlackNWhite(c: TColor): TColor;
var
H: THSV;
begin
H := RGBtoHSV(c);
H.S := 0;
Result := HSVtoRGB(H);
end;
procedure DrawTextCenter(c: TCanvas; Width, Height: integer; Caption: string);
begin
c.TextOut((Width div 2) - (c.TextWidth(Caption) div 2),
(Height div 2) - (c.TextHeight(Caption) div 2), Caption);
end;
function LightenColor(c: TColor; Val: TPercent): TColor;
var
h: THSV;
o: Byte;
begin
h := RGBtoHSV(ColorToRGB(c));
o:=h.V;
h.v := h.v + h.v div 100 * Val;
if h.v<o then
h.v:=255;
Result := HSVtoRGB(h);
end;
function DarkenColor(c: TColor; Val: TPercent): TColor;
var
h: THSV;
o: Byte;
begin
h := RGBtoHSV(ColorToRGB(c));
o:=h.V;
h.v := h.v - h.v div 100 * Val;
if h.v>o then
h.v:=0;
Result := HSVtoRGB(h);
end;
end.
|
{*******************************************************}
{ }
{ 无边框窗体大小控制单元 }
{ }
{ 版权所有 (C) 2017 by YangYxd }
{ }
{*******************************************************}
{
使用方法: 将需要控制大小的无边框窗口的基类设置为 TSizeForm 即可
}
unit UI.SizeForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, UI.Base,
FMX.StdCtrls;
type
TResizeMode = (Normal, LTop, RTop, LBottom, RBottom, Top, Bottom, Left, Right);
TSizeForm = class(TForm)
private
{ Private declarations }
FCaptureDragForm: Boolean;
FMouseDraging: Boolean;
protected
FSizeWH: Single; // 可调节区域大小
FMousePos, FDownPos, FResizeSize, FDownSize: TPointF;
FResizeMode: TResizeMode;
function PointInDragBorder(const X, Y: Single): Boolean;
function CalcResizeMode(const X, Y: Single): TResizeMode;
procedure UpdateCurror(const AResizeMode: TResizeMode);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
function ObjectAtPoint(AScreenPoint: TPointF): IControl; override;
procedure MouseMove(Shift: TShiftState; X, Y: Single); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single; DoClick: Boolean = True); override;
published
property CaptureDragForm: Boolean read FCaptureDragForm write FCaptureDragForm;
property SizeWH: Single read FSizeWH write FSizeWH;
end;
implementation
function TSizeForm.CalcResizeMode(const X, Y: Single): TResizeMode;
begin
Result := TResizeMode.Normal;
if (X < 0) and (Y < 0) then
Exit;
if (X > FSizeWH) and (X <= Width - FSizeWH) then begin
if (Y < FSizeWH) then
Result := TResizeMode.Top
else if (Y >= Height - FSizeWH) then
Result := TResizeMode.Bottom
end else if (Y > FSizeWH) and (Y < Height - FSizeWH) then begin
if X <= FSizeWH then
Result := TResizeMode.Left
else if X >= Width - FSizeWH then
Result := TResizeMode.Right
end else if (X <= FSizeWH) and (Y <= FSizeWH) then
Result := TResizeMode.LTop
else if (X >= Width - FSizeWH) and (Y <= FSizeWH) then
Result := TResizeMode.RTop
else if (X <= FSizeWH) and (Y >= Height - FSizeWH) then
Result := TResizeMode.LBottom
else if (X >= Width - FSizeWH) and (Y >= Height - FSizeWH) then
Result := TResizeMode.RBottom;
end;
constructor TSizeForm.Create(AOwner: TComponent);
begin
inherited;
FSizeWH := 10;
end;
procedure TSizeForm.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
begin
inherited;
if (BorderStyle = TFmxFormBorderStyle.None) and (WindowState = TWindowState.wsNormal) then begin
if (csDesigning in ComponentState) then Exit;
if (Button = TMouseButton.mbLeft) and (Shift = [ssLeft]) then begin
if FullScreen then
Exit;
if not PointInDragBorder(X, Y) then begin
if FCaptureDragForm then begin
FMouseDraging := True;
StartWindowDrag;
end;
Exit;
end;
FResizeMode := CalcResizeMode(X, Y);
UpdateCurror(FResizeMode);
if FResizeMode = TResizeMode.Normal then
Exit;
FMousePos := PointF(X, Y);
FDownPos := FMousePos;
FResizeSize := PointF(Width, Height);
FDownSize := FResizeSize;
FWinService.SetCapture(Self);
end;
end;
end;
procedure TSizeForm.MouseMove(Shift: TShiftState; X, Y: Single);
var
P: TPointF;
begin
if (FResizeMode <> TResizeMode.Normal) and (ssLeft in Shift) then begin
Engage;
try
P.X := Left;
P.Y := Top;
case FResizeMode of
TResizeMode.LTop:
begin
P.X := P.X + (X - FDownPos.X);
P.Y := P.Y + (Y - FDownPos.Y);
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X - (X - FDownPos.X)));
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y - (Y - FDownPos.Y)));
end;
TResizeMode.RTop:
begin
P.Y := P.Y + (Y - FDownPos.Y);
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X));
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y - (Y - FDownPos.Y)));
end;
TResizeMode.LBottom:
begin
P.X := P.X + (X - FDownPos.X);
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X - (X - FDownPos.X)));
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y));
end;
TResizeMode.RBottom:
begin
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X));
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y));
end;
TResizeMode.Top:
begin
P.Y := P.Y + (Y - FDownPos.Y);
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y) - (Y - FDownPos.Y));
end;
TResizeMode.Bottom:
begin
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y));
end;
TResizeMode.Left:
begin
P.X := P.X + (X - FDownPos.X);
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X - (X - FDownPos.X)));
end;
TResizeMode.Right:
begin
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X));
end;
end;
SetBounds(Round(P.X), Round(P.Y), Round(FResizeSize.X), Round(FResizeSize.Y));
FMousePos := PointF(X, Y);
finally
Disengage;
end;
end else begin
inherited;
if (BorderStyle = TFmxFormBorderStyle.None) then begin
if Shift = [] then
UpdateCurror(CalcResizeMode(X, Y))
else
Cursor := crArrow;
end else if Cursor <> crDefault then
Cursor := crDefault;
end;
end;
procedure TSizeForm.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single;
DoClick: Boolean);
begin
if FMouseDraging then begin
FMouseDraging := False;
ReleaseCapture;
end;
if FResizeMode <> TResizeMode.Normal then begin
FResizeMode := TResizeMode.Normal;
ReleaseCapture;
end;
inherited;
end;
function TSizeForm.ObjectAtPoint(AScreenPoint: TPointF): IControl;
function Innder(const P: TPointF): IControl;
begin
if (P.X < 0) or (P.Y < 0) or PointInDragBorder(P.X, P.Y) then
Result := nil
else
Result := inherited;
end;
begin
if (BorderStyle = TFmxFormBorderStyle.None) and (WindowState = TWindowState.wsNormal) and (FSizeWH > 1) then
Result := Innder(ScreenToClient(AScreenPoint))
else
Result := inherited;
end;
function TSizeForm.PointInDragBorder(const X, Y: Single): Boolean;
begin
Result := (FSizeWH > 1) and ((X < FSizeWH) or (X >= Width - FSizeWH) or (Y < FSizeWH) or (Y >= Height - FSizeWH));
end;
procedure TSizeForm.UpdateCurror(const AResizeMode: TResizeMode);
const
CCursor: array [TResizeMode] of Integer = (
crArrow, crSizeNWSE, crSizeNESW, crSizeNESW, crSizeNWSE, crSizeNS, crSizeNS, crSizeWE, crSizeWE
);
begin
Cursor := CCursor[AResizeMode]
end;
end.
|
unit TestCases;
interface
uses
TestFrameWork,
Db2XML,
XMLDoc, XMLIntf, DB, AdoDb,
TestExtensions;
type
TTestDBSetup = class(TTestSetup)
public
Connection: TADOConnection;
Query: TADOQuery;
procedure SetUp; override;
procedure TearDown; override;
end;
TRootTestCase = class(TTestCase)
public
procedure SetUp; override;
procedure TearDown; override;
private
Convertor: TDb2XmlRoot;
published
procedure CreationTest;
procedure RootNodeTest;
procedure SaveTest;
end;
TLayerTestCase = class(TTestCase)
private
Convertor: TDb2XmlRoot;
Dataset: TADOQuery;
RootNode: IXmlNode;
XmlDoc: TXMLDocument;
procedure SaveTest(TestFileName: string);
procedure ProcessTable(Layer: TDb2XmlDataLayer; table, OutFile: string);
procedure LayerTest(TableIndex, RuleIndex: integer);
public
procedure SetUp; override;
procedure TearDown; override;
published
// Проверяет только перебор записей и сохранение для каждой записи ноды <Record/>
procedure NoLinesTest;
procedure OneLinesTest;
procedure TwoLinesTest;
// Проверяет работу с полями:
// Поля записываются как тексты вложенных нод
procedure NoAttrTest;
// Поля записываются как параметры нод
procedure OnlyAttrTest;
// Поля записываются и как тексты вложенных нод и как параметры нод
procedure AttrAndDeepTest;
end;
implementation
uses SysUtils, Classes;
var TestDB: TTestDBSetup;
{ TRootTestCase }
procedure TRootTestCase.SetUp;
begin
inherited;
Convertor := TDb2XmlRoot.Create('out\Simple.xml','ROOT_NAME', 'ID=12345');
end;
procedure TRootTestCase.TearDown;
begin
inherited;
Convertor.Free;
end;
procedure TRootTestCase.CreationTest;
begin
Check(true);
end;
procedure TRootTestCase.RootNodeTest;
var x: TDb2XmlRoot;
begin
x:= convertor;
CheckEqualsString(x.RootNode.NodeName, 'ROOT_NAME');
CheckEquals(x.RootNode.Attributes['ID'], 12345);
end;
procedure TRootTestCase.SaveTest;
var
etalon, test: string;
sl: TStringList;
begin
Convertor.Save;
sl := TStringList.Create;
try
sl.LoadFromFile('testData\Simple.xml');
etalon := sl.Text;
sl.LoadFromFile('Out\Simple.xml');
test := sl.Text;
finally
sl.Free;
end;
CheckEqualsString(etalon, Test);
end;
{ TTestDBSetup }
procedure TTestDBSetup.SetUp;
begin
inherited;
Connection := TADOConnection.Create(nil);
Connection.ConnectionString := 'FILE NAME=.\TestData\csv.udl';
Query :=TADOQuery.Create(nil);
Query.Connection := Connection;
end;
procedure TTestDBSetup.TearDown;
begin
Query.Free;
Connection.Free;
inherited;
end;
{ TLayerTestCase }
const
Rules: array[0..3] of string = (
'RECORD'
, 'RECORD'#13#10' No_data'#13#10' No_Data2='#13#10' NODE_B=b'#13#10' Node_C=c'#13#10' Node_e=e'#13#10' NODE_B=b'
, 'RECORD='#13#10' #a=a'#13#10' #aaa=a'#13#10' #f=f'#13#10' #e=e'#13#10' #d=d'#13#10' #b=b'
, 'RECORD'#13#10' No_data'#13#10' No_Data2='#13#10' #param_a=a'#13#10' NODE_B=b'#13#10' Node_C=c'#13#10' Node_e=e'#13#10' #param_a=a'#13#10' #param_b=b'#13#10' NODE_B=b'
);
RuleNames: array[0..3] of string = (
'simple'
, 'NoAttr'
, 'OnlyAttr'
, 'Attr&Deep'
);
TableNames: array[0..2] of string = (
'noRec'
, 'OneRec'
, 'TwoRec'
);
procedure TLayerTestCase.LayerTest(TableIndex, RuleIndex: integer);
Var
Layer: TDb2XmlDataLayer;
begin
Layer := TDb2XmlDataLayer.Create(
Rules[RuleIndex],
TestDb.Query);
try
ProcessTable(
Layer,
'TestData\' + TableNames[TableIndex] + '.csv',
RuleNames[RuleIndex] + IntToStr(TableIndex) +'.xml'
);
SaveTest(RuleNames[RuleIndex] + IntToStr(TableIndex) + '.xml');
finally
Layer.Free;
end;
end;
procedure TLayerTestCase.ProcessTable(Layer: TDb2XmlDataLayer; table, OutFile: string);
begin
with TestDb.Query do
begin
Active := false;
sql.Text := 'select * from ' + table;
Active := true;
end;
Layer.Execute(Convertor.RootNode);
Convertor.FileName := 'out\'+ OutFile;
Convertor.Save;
end;
procedure TLayerTestCase.SetUp;
begin
inherited;
Convertor := TDb2XmlRoot.Create('out\Simple.xml','ROOT_NAME', 'ID=12345');
end;
procedure TLayerTestCase.TearDown;
begin
inherited;
end;
procedure TLayerTestCase.SaveTest(TestFileName: string);
var
sl: TStringList;
Etalon, test: string;
begin
sl := TStringList.Create;
try
sl.LoadFromFile('testData\' + TestFileName);
etalon := sl.Text;
sl.LoadFromFile('Out\'+ TestFileName);
test := sl.Text;
finally
sl.Free;
end;
CheckEqualsString(etalon, Test);
end;
procedure TLayerTestCase.NoLinesTest;
begin
LayerTest(0, 0);
end;
procedure TLayerTestCase.OneLinesTest;
begin
LayerTest(1, 0);
end;
procedure TLayerTestCase.TwoLinesTest;
begin
LayerTest(2, 0);
end;
procedure TLayerTestCase.NoAttrTest;
begin
LayerTest(2, 1);
end;
procedure TLayerTestCase.OnlyAttrTest;
begin
LayerTest(2, 2);
end;
procedure TLayerTestCase.AttrAndDeepTest;
begin
LayerTest(2, 3);
end;
initialization
TestFramework.RegisterTest(TRootTestCase.Suite);
TestDb := TTestDBSetup.Create(TLayerTestCase.Suite);
RegisterTest(TestDb);
end.
|
unit DelphiAST.Writer;
interface
uses
{$IFDEF FPC}
StringBuilderUnit,
{$ENDIF}
Classes,
DelphiAST.Classes, SysUtils;
type
TSyntaxTreeWriter = class
private
class procedure NodeToXML(const Builder: TStringBuilder;
const Node: TSyntaxNode; Formatted: Boolean); static;
public
class function ToXML(const Root: TSyntaxNode;
Formatted: Boolean = False): string; static;
{$IFNDEF FPC}
class function ToBinary(const Root: TSyntaxNode; Stream: TStream): Boolean; static;
{$ENDIF}
end;
implementation
uses
Generics.Collections,
{$IFNDEF FPC}
DelphiAST.Serialize.Binary,
{$ENDIF}
DelphiAST.Consts;
{$I SimpleParser/SimpleParser.inc}
{$IFDEF D18_NEWER}
{$ZEROBASEDSTRINGS OFF}
{$ENDIF}
{ TSyntaxTreeWriter }
class procedure TSyntaxTreeWriter.NodeToXML(const Builder: TStringBuilder;
const Node: TSyntaxNode; Formatted: Boolean);
function XMLEncode(const Data: string): string;
var
i, n: Integer;
procedure Encode(const s: string);
begin
Move(s[1], Result[n], Length(s) * SizeOf(Char));
Inc(n, Length(s));
end;
begin
SetLength(Result, Length(Data) * 6);
n := 1;
for i := 1 to Length(Data) do
case Data[i] of
'<': Encode('<');
'>': Encode('>');
'&': Encode('&');
'"': Encode('"');
'''': Encode(''');
else
Result[n] := Data[i];
Inc(n);
end;
SetLength(Result, n - 1);
end;
procedure NodeToXMLInternal(const Node: TSyntaxNode; const Indent: string);
var
HasChildren: Boolean;
NewIndent: string;
Attr: TPair<TAttributeName, string>;
ChildNode: TSyntaxNode;
begin
HasChildren := Node.HasChildren;
if Formatted then
begin
NewIndent := Indent + ' ';
Builder.Append(Indent);
end;
Builder.Append('<' + UpperCase(SyntaxNodeNames[Node.Typ]));
if Node is TCompoundSyntaxNode then
begin
Builder.Append(' begin_line="' + IntToStr(TCompoundSyntaxNode(Node).Line) + '"');
Builder.Append(' begin_col="' + IntToStr(TCompoundSyntaxNode(Node).Col) + '"');
Builder.Append(' end_line="' + IntToStr(TCompoundSyntaxNode(Node).EndLine) + '"');
Builder.Append(' end_col="' + IntToStr(TCompoundSyntaxNode(Node).EndCol) + '"');
end else
begin
Builder.Append(' line="' + IntToStr(Node.Line) + '"');
Builder.Append(' col="' + IntToStr(Node.Col) + '"');
end;
if Node.FileName <> '' then
Builder.Append(' file="' + XMLEncode(Node.FileName) + '"');
if Node is TValuedSyntaxNode then
Builder.Append(' value="' + XMLEncode(TValuedSyntaxNode(Node).Value) + '"');
for Attr in Node.Attributes do
Builder.Append(' ' + AttributeNameStrings[Attr.Key] + '="' + XMLEncode(Attr.Value) + '"');
if HasChildren then
Builder.Append('>')
else
Builder.Append('/>');
if Formatted then
Builder.AppendLine;
for ChildNode in Node.ChildNodes do
NodeToXMLInternal(ChildNode, NewIndent);
if HasChildren then
begin
if Formatted then
Builder.Append(Indent);
Builder.Append('</' + UpperCase(SyntaxNodeNames[Node.Typ]) + '>');
if Formatted then
Builder.AppendLine;
end;
end;
begin
NodeToXMLInternal(Node, '');
end;
{$IFNDEF FPC}
class function TSyntaxTreeWriter.ToBinary(const Root: TSyntaxNode; Stream: TStream):
Boolean;
var
Writer: TBinarySerializer;
begin
Writer := TBinarySerializer.Create;
try
Result := Writer.Write(Stream, Root);
finally FreeAndNil(Writer); end;
end;
{$ENDIF}
class function TSyntaxTreeWriter.ToXML(const Root: TSyntaxNode;
Formatted: Boolean): string;
var
Builder: TStringBuilder;
begin
Builder := TStringBuilder.Create;
try
NodeToXml(Builder, Root, Formatted);
Result := '<?xml version="1.0"?>' + sLineBreak + Builder.ToString;
finally
Builder.Free;
end;
end;
end.
|
(*******************************************************)
(* *)
(* Engine Paulovich DirectX *)
(* Win32-DirectX API Unit *)
(* *)
(* Copyright (c) 2003-2004, Ivan Paulovich *)
(* *)
(* iskatrek@hotmail.com uin#89160524 *)
(* *)
(* Unit: brInput *)
(* *)
(*******************************************************)
unit brInput;
interface
uses
Windows, DirectInput8, SysUtils;
type
TTimedInput = record
Time: dWord;
Used: boolean;
end;
TInput = class
private
FHandle: HWnd;
DI8: IDirectInput8;
DIK8: IDirectInputDevice8;
DIM8: IDirectInputDevice8;
DIJ8: IDirectInputDevice8;
DIMEvent: THandle;
DIMou0Clicked: Boolean;
DIMou1Clicked: Boolean;
DIJ8Caps: TDIDevCaps;
function EnumJoysticksCallback(Device: PDIDeviceInstance; Ref: Pointer): Integer;
function EnumAxesCallback(var Device: TDIDeviceObjectInstance; Ref: Pointer): Integer;
public
constructor Create(Handle: HWnd; Keyboard, Mouse, Joystick: Boolean);
function Run: Integer;
procedure Clear;
function InitializeMouse: Boolean;
function InitializeJoystick: Boolean;
function InitializeKeyboard: Boolean;
function MouseAcquire(Acquire: Boolean): Boolean;
function MouseState(var X, Y: LongInt; var Up0, Down0, DblClk0,
Up1, Down1, DblClk1: Longint): Boolean;
function JoystickState(var Data: TDIJoyState2): Boolean;
function KeyboardAcquire(Acquire: Boolean): Boolean;
function KeyboardState: Boolean;
function KeyDown(Key: Byte): Boolean;
property Handle: HWnd read FHandle;
end;
var
Input: TInput = nil;
procedure TimedInputReset(var Ti: TTimedInput);
function TimedInputRefresh(var Ti: TTimedInput; _Time, TimeOut: DWord;
Condition: Boolean): Longint;
implementation
uses
brForms;
const
DIMBufSize = 16;
DIMTimeOut = 250;
DIJoyRange = 32768;
var
DIMButSwapped: Boolean = False;
DIM0Released: DWord = 0;
DIM1Released: DWord = 0;
DIKeyBuffer: array[0..255] of Byte;
procedure TimedInputReset(var Ti: TTimedInput);
begin
Ti.Time := 0;
Ti.Used := False;
end;
function TimedInputRefresh(var Ti: TTimedInput; _Time, TimeOut: DWord;
Condition: Boolean): LongInt;
begin
Result := 0;
if (Ti.Time = 0) and (Condition) then
begin
Ti.Time := _Time;
Exit;
end;
if Ti.Time <> 0 then
if Condition then
begin
if _Time - Ti.Time >= Timeout then
begin
Ti.Used := true;
while _Time - Ti.Time >= Timeout do
begin
Inc(Result);
Inc(Ti.Time, Timeout)
end;
end;
end
else
begin
if not Ti.Used then
Inc(Result);
Ti.Used := false;
Ti.Time := 0;
end;
end;
function GlobalEnumJoysticksCallback(Device: PDIDeviceInstance; Ref: Pointer): Integer; stdcall;
begin
Input.EnumJoysticksCallback(Device, Ref);
end;
function GlobalEnumAxesCallback(var Device: TDIDeviceObjectInstance; Ref: pointer): Integer; stdcall;
begin
Input.EnumAxesCallback(Device, Ref);
end;
constructor TInput.Create;
begin
if Assigned(Input) then
raise ELogError.Create(Format(ERROR_EXISTS, ['TInput']))
else
SaveLog(Format(EVENT_CREATE, ['TInput']));
DI8 := nil;
DIK8 := nil;
DIM8 := nil;
DIJ8 := nil;
FHandle := Handle;
end;
function TInput.Run: Integer;
begin
Clear;
SaveLog(Format(EVENT_TALK, ['TInput.Run']));
if Failed(DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8,
DI8, nil)) then
Result := E_FAIL
else
Result := S_OK;
end;
procedure TInput.Clear;
begin
if Assigned(DI8) then
begin
if Assigned(DIK8) then
begin
DIK8.Unacquire;
DIK8 := nil;
end;
if Assigned(DIM8) then
begin
DIM8.Unacquire;
DIM8 := nil;
end;
if Assigned(DIJ8) then
begin
DIJ8.Unacquire;
DIJ8 := nil;
end;
DI8 := nil;
end;
end;
function TInput.InitializeMouse: Boolean;
var
Prop: TDIPropDWord;
begin
Result := false;
DIMButSwapped := GetSystemMetrics(SM_SWAPBUTTON) <> 0;
if Failed(DI8.CreateDevice(GUID_SysMouse, DIM8, nil)) then
Exit;
if Failed(DIM8.SetDataFormat(@c_dfDIMouse)) then
Exit;
if Failed(DIM8.SetCooperativeLevel(Handle, DISCL_FOREGROUND or DISCL_EXCLUSIVE)) then
Exit;
DIMEvent := CreateEvent(nil, False, False, nil);
if DIMEvent = 0 then
Exit;
if Failed(DIM8.SetEventNotification(DIMEvent)) then
Exit;
with Prop do begin
diph.dwSize := SizeOf(TDIPropDWord);
diph.dwHeaderSize := SizeOf(TDIPropHeader);
diph.dwObj := 0;
diph.dwHow := DIPH_DEVICE;
dwData := DIMBufSize;
end;
if Failed(DIM8.SetProperty(DIPROP_BUFFERSIZE, Prop.diph)) then
Exit;
Result := True;
end;
function TInput.MouseAcquire(Acquire: Boolean): Boolean;
begin
if not Acquire then
Result := not Failed(DIM8.Unacquire)
else
Result := not Failed(DIM8.Acquire);
end;
function TInput.MouseState(var X, Y: LongInt; var Up0, Down0, DblClk0,
Up1, Down1, DblClk1: Longint): Boolean;
var
Hr: HRESULT;
Objdata: TDIDeviceObjectData;
Zero, One: Boolean;
_Time: DWord;
Elements: DWord;
begin
Result := false;
X := 0;
Y := 0;
Up0 := 0;
Down0 := 0;
DblClk0 := 0;
Up1 := 0;
Down1 := 0;
DblClk1 := 0;
repeat
Elements := 1;
Hr := DIM8.GetDeviceData(SizeOf(TDIDeviceObjectData), @Objdata, Elements, 0);
if Hr = DIERR_INPUTLOST then
begin
Hr := DIM8.Acquire;
if not Failed(hr) then
Hr := DIM8.GetDeviceData(SizeOf(TDIDeviceObjectData), @ObjData, Elements, 0);
end;
if (Failed(Hr)) then
Exit;
Result := True;
if (Elements = 0) then
Exit;
Zero := False;
One := False;
case ObjData.dwOfs of
DIMOFS_X: X := X + LongInt(ObjData.dwData);
DIMOFS_Y: Y := Y + LongInt(ObjData.dwData);
DIMOFS_BUTTON0: if DIMButSwapped then
One := True
else
Zero := True;
DIMOFS_BUTTON1: if DIMButSwapped then
Zero := True
else
One := True;
end;
if Zero then
begin
DIMou0Clicked := (ObjData.dwData and $80 = $80);
if not DIMou0Clicked then
begin
Inc(Up0);
_Time := GetTickCount;
if (_Time - DIM0Released < DIMTimeOut) then
begin
DIM0Released := 0;
Inc(DblClk0);
end
else
DIM0Released := _time;
end
else
Inc(Down0);
end;
if One then
begin
DIMou1Clicked := (ObjData.dwData and $80 = $80);
if not DIMou1Clicked then
begin
Inc(Up1);
_Time := GetTickCount;
if (_Time - DIM1Released < DIMTimeOut) then
begin
DIM1Released := 0;
Inc(DblClk1);
end
else
DIM1Released := _Time;
end
else
Inc(Down1);
end;
until Elements = 0;
end;
function TInput.EnumJoysticksCallback(Device: PDIDeviceInstance; Ref: Pointer): Integer;
begin
Result := DIENUM_CONTINUE;
if Failed(DI8.CreateDevice(Device.guidInstance, DIJ8, nil)) then
Exit;
Result := DIENUM_STOP;
end;
function TInput.EnumAxesCallback(var Device: TDIDeviceObjectInstance; Ref: Pointer): Integer;
var
PropRange: TDIPropRange;
begin
Result := DIENUM_CONTINUE;
PropRange.diph.dwSize := Sizeof(TDIPropRange);
PropRange.diph.dwHeaderSize := Sizeof(TDIPropHeader);
PropRange.diph.dwHow := DIPH_BYID;
PropRange.diph.dwObj := Device.dwType;
PropRange.lMin := -DIJoyRange;
PropRange.lMax := DIJoyRange;
if Failed(DIJ8.SetProperty(DIPROP_RANGE, PropRange.diph)) then
Result := DIENUM_STOP;
end;
function TInput.InitializeJoystick: Boolean;
begin
Result := False;
DI8.EnumDevices(DI8DEVCLASS_GAMECTRL, @GlobalEnumJoysticksCallback, nil, DIEDFL_ATTACHEDONLY);
if DIJ8 = nil then
Exit;
if Failed(DIJ8.SetDataFormat(@c_dfDIJoystick2)) then
begin
DIJ8 := nil;
Exit;
end;
if Failed(DIJ8.SetCooperativeLevel(Handle, DISCL_EXCLUSIVE or DISCL_FOREGROUND)) then
begin
DIJ8 := nil;
Exit;
end;
DIJ8CAPS.dwSize := Sizeof(TDIDevCaps);
if Failed(DIJ8.GetCapabilities(DIJ8CAPS)) then
begin
DIJ8 := nil;
Exit;
end;
if Failed(DIJ8.EnumObjects(GlobalEnumAxesCallback, nil, DIDFT_AXIS)) then
begin
DIJ8 := nil;
Exit;
end;
Result := True;
end;
function TInput.JoystickState(var Data: TDIJoyState2): Boolean;
begin
Result := False;
if Failed(DIJ8.Poll) then
if DIJ8.Acquire = DIERR_INPUTLOST then
if Failed(DIJ8.Acquire) then
Exit;
Result := not Failed(DIJ8.GetDeviceState(Sizeof(TDIJoyState2), @Data));
end;
function TInput.InitializeKeyboard: Boolean;
begin
Result := False;
if Failed(DI8.CreateDevice(GUID_SysKeyboard, DIK8, nil)) then
Exit;
if Failed(DIK8.SetDataFormat(@c_dfDIKeyboard)) then
Exit;
if Failed(DIK8.SetCooperativeLevel(Handle, DISCL_FOREGROUND or DISCL_NONEXCLUSIVE)) then
Exit;
Result := True;
end;
function TInput.KeyboardAcquire(Acquire: Boolean): Boolean;
var
Hr: hResult;
begin
if not Acquire then
Result := not Failed(DIK8.Unacquire)
else
Result := not Failed(DIK8.Acquire);
end;
function TInput.KeyboardState: Boolean;
var
Hr: HRESULT;
begin
Hr := DIK8.GetDeviceState(SizeOf(DIKeyBuffer), @DIKeyBuffer);
if Hr = DIERR_INPUTLOST then
begin
Hr := DIK8.Acquire;
if not Failed(Hr) then
Hr := DIK8.GetDeviceState(SizeOf(DIKeyBuffer), @DIKeyBuffer);
end;
Result := not Failed(Hr);
end;
function TInput.KeyDown(Key: Byte): Boolean;
begin
Result := (DIKeyBuffer[Key] and $80 = $80);
end;
begin
ZeroMemory(@DIKeyBuffer, SizeOf(DIKeyBuffer));
end.
|
(* А) Напишите процедуру, переводящую все символы строки
(латинские буквы) к верхнему регистру. *)
var
str : string;
procedure UpAllChars(var aStr : string);
var
i, len : word;
begin
len := Length((aStr));
for i := 1 to len do
aStr[i] := UpCase(aStr[i]);
end;
begin
str := 'pascal is awesome';
Writeln(str);
UpAllChars(str);
Writeln(str);
end. |
{
DocuGes - Gestion Documental
Autor: Fco. Javier Perez Vidal <developer at f-javier dot es>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
unit aboutbox;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs,
ExtCtrls, StdCtrls, Buttons, ComCtrls;
type
{ TfAboutBox }
TfAboutBox = class(TForm)
btnSalir: TBitBtn;
Imagen: TImage;
Label1: TLabel;
LVersion: TLabel;
LNombre: TLabel;
Label3: TLabel;
Licencia: TMemo;
pc: TPageControl;
tsAbout: TTabSheet;
tsLicencia: TTabSheet;
procedure btnSalirClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
fAboutBox: TfAboutBox;
implementation
{ TfAboutBox }
uses recursostexto;
procedure TfAboutBox.FormCreate(Sender: TObject);
begin
LVersion.Caption := 'DocuGes - Ver. 1.0 (Rev. 20)';
pc.ActivePage:=tsAbout;
Imagen.Picture.LoadFromFile(DirectorioAplicacion+'about.png');
Licencia.Lines.LoadFromFile(UTF8ToAnsi(DirectorioAplicacion+'license.txt'));
end;
procedure TfAboutBox.btnSalirClick(Sender: TObject);
begin
Self.Close;
end;
procedure TfAboutBox.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
CloseAction:=caFree;
end;
initialization
{$I aboutbox.lrs}
end.
|
program testmath02(output);
begin
writeln('six times seven equals: ');
writeln(6 * 7);
writeln('Four times two equals: ');
writeln(4 * 2)
end.
|
{>>Dans cette unité, on va traiter tout ce qui concerne le son midi}
unit UMidiSound;
interface
Uses Windows, SysUtils, PatternMidi, BassMidi, Bass, PianoGrid, Dialogs;
Procedure Initialize_MidiStream(Var MidiStream:HStream;Flag:DWord);
Procedure Finalize_MidiStream(Var MidiStream:HStream);
Procedure Load_SoundFont(MidiStream:HStream; Var MidiFont:BASS_MIDI_FONT; SndFontFileName:String);
Procedure Free_SoundFont(MidiStream:HStream; MidiFont:BASS_MIDI_FONT);
Procedure DefaultParams_Pattern(Instrument: TInstrPattern);
Procedure Pattern_Define_MidiEvents(MidiStream:HStream; Instrument: TInstrPattern);
Procedure NoteGrid_Define_MidiEvents(MidiStream:HStream; Note:TNote);
Procedure Press_Note(MidiStream:HStream;Channel,Note,Velocity:Byte);
implementation
Uses UPianoMd, UPatternMd, UParams;
Procedure Initialize_MidiStream(Var MidiStream:HStream;Flag:DWord);
Var
Freq:Cardinal;
Begin
If MidiStream=0 Then
Begin
With Params_Form.Sample_Freq_LsBx Do
Begin
If ItemIndex<0 Then Exit;
Freq:=StrToInt(Items[ItemIndex]);
End;
MidiStream:=BASS_MIDI_StreamCreate(128,Flag,Freq);
End;
End;
Procedure Finalize_MidiStream(Var MidiStream:HStream);
Begin
If MidiStream<>0 Then
Begin
BASS_StreamFree(MidiStream);
MidiStream:=0;
End;
End;
Procedure Load_SoundFont(MidiStream:HStream; Var MidiFont:BASS_MIDI_FONT; SndFontFileName:String);
Begin
If MidiStream<>0 Then
With MidiFont Do
Begin
Font:=BASS_MIDI_FontInit(Pchar(SndFontFileName),0);
Preset := -1;
Bank := 0;
BASS_MIDI_StreamSetFonts(MidiStream,MidiFont,1);
End;
End;
Procedure Free_SoundFont(MidiStream:HStream; MidiFont:BASS_MIDI_FONT);
Begin
If (MidiStream<>0) And (MidiFont.Font<>0) Then
BASS_MIDI_FontFree(MidiFont.Font);
End;
Procedure DefaultParams_Pattern(Instrument: TInstrPattern);
Begin
With Instrument Do
Begin
//On met le volume par défaut à 127
Volume:=127;
//On met la vélocité par défaut à 127
Velocity:=127;
//On met l'expression par défaut à 127
Expression:=127;
//On met la resonance par défaut à 127
Resonance:=127;
//Le Sustain est mis à 127
Sustain:=127;
//On met le panomarique par défaut à 64
Pan:=64;
End;
End;
Procedure Pattern_Define_MidiEvents(MidiStream:HStream; Instrument: TInstrPattern);
Begin
If MidiStream<>0 Then
Begin
With Instrument Do
Begin
If (Channel=9) And (Instr=114) Then BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_DRUMS,1)
Else BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PROGRAM,Instr);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_VOLUME,Volume);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_CHANPRES,ChannelPressure);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_MODULATION,Modulation);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PITCH,PitchBend);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PORTATIME,PortamentoTime);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PORTAMENTO,PortamentoSwitch);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PORTANOTE,PortamentoNote);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PAN,Pan);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_RESONANCE,Resonance);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_REVERB,Vibrato);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_SUSTAIN,Sustain);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_EXPRESSION,Expression);
End;
End;
End;
Procedure NoteGrid_Define_MidiEvents(MidiStream:HStream; Note:TNote);
Begin
If MidiStream<>0 Then
Begin
With Note Do
Begin
If (Channel=9) And (Instr=114) Then BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_DRUMS,1)
Else BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PROGRAM,Instr);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_VOLUME,Volume);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_CHANPRES,ChannelPressure);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_MODULATION,Modulation);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PITCH,PitchBend);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PORTATIME,PortamentoTime);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PORTAMENTO,PortamentoSwitch);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PORTANOTE,PortamentoNote);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_PAN,Pan);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_RESONANCE,Resonance);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_REVERB,Vibrato);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_SUSTAIN,Sustain);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_EXPRESSION,Expression);
End;
End;
End;
Procedure Press_Note(MidiStream:HStream;Channel,Note,Velocity:Byte);
Var
Param:DWORD;
Begin
If MidiStream<>0 Then
Begin
If Velocity=0 Then Param:=Note
Else Param:=MAKEWORD(Note,Velocity);
BASS_MIDI_StreamEvent(MidiStream,Channel,MIDI_EVENT_NOTE,Param);
End;
End;
end.
|
{$include kode.inc}
unit kode_widget_keyboard;
{
mind-storm:
black or white, black = 1 rect, white = 2 rect
only 2 numbers per rectangle is unique
use rectangles for hit testing (mouse click)
precalc them in setup(scale,dist,y1,y2) ?
array with 12 elememnts, one for each note in octave
1 find octave
octave width = mScale*3*7
so, a key could be
- int black/white
- num1,num2
- num1,num2
}
//
// | |4| | | |
// | |_| |_| |
// |1 |2 |3 |
// |___|___|___|
//
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_canvas,
kode_color,
kode_flags,
kode_rect,
kode_widget;
type
KWidget_Keyboard = class(KWidget)
private
FActiveMap : array[0..11] of Boolean;
FNoteRects1 : array[0..(12*4)-1] of LongInt;
FNoteRects2 : array[0..(12*4)-1] of LongInt;
protected
FDist : longint;
FRatio : single;
FBlackColor : KColor;
FWhiteColor : KColor;
FBlackActiveColor : KColor;
FWhiteActiveColor : KColor;
//FFillColor : KColor;
//FDarkColor : KColor;
//FActiveColor : KColor;
//FValueColor : KColor;
private
procedure recalc;
public
constructor create(ARect:KRect; AAlignment:LongWord=kwa_none);
procedure setColors(AWhite,ABlack,AWhiteActive,ABlackActive:KColor);
procedure setDist(ADist:longint);
procedure setRatio(ARatio:single);
procedure activate(num:longint);
procedure deactivate(num:longint);
{ }
procedure on_setSize(AWidth,AHeight:LongInt); override;
procedure on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0); override;
procedure on_mouseDown(AXpos,AYpos,AButton,AState:LongInt); override;
//procedure on_enter(AWidget:KWidget); override;
//procedure on_leave(AWidget:KWidget); override;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
kode_math;
const
// ofs,type
internal_note_data : array[0..(12*2)-1] of longint =
( 0,0, 2,3, 1,1, 2,3, 1,2, 3,0, 2,3, 1,1, 2,3, 1,1, 2,3, 1,2 );
//----------
constructor KWidget_Keyboard.create(ARect:KRect; AAlignment:LongWord=kwa_none);
var
i : longint;
begin
inherited;
FName := 'KWidget_Keyboard';
FDist := 2;
FRatio := 0.7;
FWhiteColor := KLightGrey;
FWhiteActiveColor := KWhite;
FBlackColor := KDarkGrey;
FBlackActiveColor := KBlack;
for i := 0 to 11 do FActiveMap[i] := false;
recalc;
FCursor := kmc_Finger;
end;
procedure KWidget_Keyboard.setColors(AWhite,ABlack,AWhiteActive,ABlackActive:KColor);
begin
FWhiteColor := AWhite;
FWhiteActiveColor := AWhiteActive;
FBlackColor := ABlack;
FBlackActiveColor := ABlackActive;
end;
//----------
procedure KWidget_Keyboard.setDist(ADist:longint);
begin
FDist := ADist + 1;
end;
procedure KWidget_Keyboard.setRatio(ARatio:single);
begin
FRatio := ARatio;
end;
procedure KWidget_Keyboard.activate(num:longint);
begin
FActiveMap[num] := True;
end;
procedure KWidget_Keyboard.deactivate(num:longint);
begin
FActiveMap[num] := false;
end;
//----------
procedure KWidget_Keyboard.recalc;
var
width : longint;
step1,step2,step3 : single;
x1 : single;
y1,y2 : longint;
note,n2,n4,iofs : longint;
ofs,x1s1,x1s2,x1s3:single;
typ:longint;
begin
width := FRect.w;
step1 := Single(width) / 21.0;
step2 := step1*2;
step3 := step1*3;
x1 := 0;
y1 := KFloor(Single(FRect.h) * FRatio);
y2 := FRect.h - 1;
for note := 0 to 11 do
begin
n2 := note+note;
n4 := n2+n2;
iofs := internal_note_data[note*2];
ofs := Single(iofs) * step1;
x1 += ofs;
x1s1 := x1 + step1;
x1s2 := x1 + step2;
x1s3 := x1 + step3;
typ := internal_note_data[(note*2)+1];
case typ of
0: // C
begin
FNoteRects1[n4+0] := KFloor(x1); FNoteRects1[n4+1] := 0;
FNoteRects1[n4+2] := KFloor(x1s2) - FDist; FNoteRects1[n4+3] := y1-1;
FNoteRects2[n4+0] := KFloor(x1); FNoteRects2[n4+1] := y1;
FNoteRects2[n4+2] := KFloor(x1s3) - FDist; FNoteRects2[n4+3] := y2;
end;
1: // D
begin
FNoteRects1[n4+0] := KFloor(x1s1); FNoteRects1[n4+1] := 0;
FNoteRects1[n4+2] := KFloor(x1s2) - FDist; FNoteRects1[n4+3] := y1-1;
FNoteRects2[n4+0] := KFloor(x1); FNoteRects2[n4+1] := y1;
FNoteRects2[n4+2] := KFloor(x1s3) - FDist; FNoteRects2[n4+3] := y2;
end;
2: // E
begin
FNoteRects1[n4+0] := KFloor(x1s1); FNoteRects1[n4+1] := 0;
FNoteRects1[n4+2] := KFloor(x1s3) - FDist; FNoteRects1[n4+3] := y1-1;
FNoteRects2[n4+0] := KFloor(x1); FNoteRects2[n4+1] := y1;
FNoteRects2[n4+2] := KFloor(x1s3) - FDist; FNoteRects2[n4+3] := y2;
end;
3: // black
begin
FNoteRects1[n4+0] := KFloor(x1); FNoteRects1[n4+1] := 0;
FNoteRects1[n4+2] := KFloor(x1s2) - FDist; FNoteRects1[n4+3] := y1 - FDist;
end;
end; // case
end; //for noteend;
end;
//----------
procedure KWidget_Keyboard.on_setSize(AWidth,AHeight:LongInt);
begin
inherited;
recalc;
end;
//----------
procedure KWidget_Keyboard.on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0);
var
note,n2,n4,typ:longint;
active:boolean;
begin
//if Assigned(FSkin) then
//begin
for note := 0 to 11 do
begin
n2 := note*2;
n4 := note*4;
active := FActiveMap[note];
typ := internal_note_data[n2+1];
if typ = 3 then
begin
if active then ACanvas.setFillColor(FBlackActiveColor)
else ACanvas.setFillColor(FBlackColor);
ACanvas.fillRect( FRect.x + FNoteRects1[n4], FRect.y + FNoteRects1[n4+1],
FRect.x + FNoteRects1[n4+2],FRect.y + FNoteRects1[n4+3] );
end
else
begin
if active then ACanvas.setFillColor(FWhiteActiveColor)
else ACanvas.setFillColor(FWhiteColor);
ACanvas.fillRect( FRect.x + FNoteRects1[n4 ], FRect.y + FNoteRects1[n4+1],
FRect.x + FNoteRects1[n4+2], FRect.y + FNoteRects1[n4+3] );
ACanvas.fillRect( FRect.x + FNoteRects2[n4 ], FRect.y + FNoteRects2[n4+1],
FRect.x + FNoteRects2[n4+2], FRect.y + FNoteRects2[n4+3] );
end; //type=0,1,2
end; //for note;
//end;
end;
//----------
procedure KWidget_Keyboard.on_mouseDown(AXpos,AYpos,AButton,AState:LongInt);
var
hit,note,n2,n4,typ : longint;
rec : KRect;
begin
if AButton = kmb_left then
begin
hit := -1;
for note := 0 to 11 do
begin
n4 := note*4;
rec.x := FRect.x + FNoteRects1[n4 ];
rec.y := FRect.y + FNoteRects1[n4+1];
rec.w := (FRect.x + FNoteRects1[n4+2]) - rec.x;
rec.h := (FRect.y + FNoteRects1[n4+3]) - rec.y;
if rec.contain(AXpos,AYpos) then
begin
hit := note;
if FActiveMap[note] then deactivate(note)
else activate(note);
do_update(self);
do_redraw(self,FRect);
end; // contain
if hit < 0 then // check lower part?
begin
n2 := note*2;
typ := internal_note_data[n2+1];
if typ < 3 then //0,1,2 = white keys
begin
rec.x := FRect.x + FNoteRects2[n4 ];
rec.y := FRect.y + FNoteRects2[n4+1];
rec.w := (FRect.x + FNoteRects2[n4+2]) - rec.x;
rec.h := (FRect.y + FNoteRects2[n4+3]) - rec.y;
if rec.contain(AXpos,AYpos) then
begin
if FActiveMap[note] then deactivate(note)
else activate(note);
do_update(self);
do_redraw(self,FRect);
end; //contains
end; //type 0,1,2
end; //hit
end; // for note
end;
//axWidget::doMouseDown(aXpos,aYpos,aButton);
end;
//----------
//procedure KWidget_Keyboard.on_enter(AWidget:KWidget);
//begin
// do_cursor(self,kmc_Finger);
//end;
//----------
//procedure KWidget_Keyboard.on_leave(AWidget:KWidget);
//begin
// do_cursor(self,kmc_default);
//end;
//----------------------------------------------------------------------
end.
|
Unit pSender;
{*******************************************************************************
Process sender unit:
Client Process ->> Server Process
Send ->> Return answer with wait
********************************************************************************
Autor : BlackCash
********************************************************************************
Include this code to server aplication for geting input message:
...
protected
procedure SenderPs(var Msg: TMessage); message WM_COPYDATA;
...
procedure TFormX.SenderPs;
var
pcd: PCopyDataStruct;
begin
pcd := PCopyDataStruct(Msg.LParam);
// PChar(pcd.lpData) - Sender string
// This may be action procedure/function for process message
// and this answer metod:
// StrPCopy(lpBaseAddress,'ANSWER');
end;
********************************************************************************}
interface
Uses Windows, messages;
var
hFileMapObj : THandle;
lpBaseAddress : PChar;
cd : TCopyDataStruct;
function CreateSenderObject(SenderName: PAnsiChar): boolean;
function SendToObject(SenderSt: String): boolean;
function sendstring(ServerCapt: String; str: pchar): boolean;
function GetObjectResult(SenderName: PAnsiChar): string;
Procedure CloseSenderObject;
implementation
{ **************************************************************************** }
function StrLCopy(Dest: PChar; const Source: PChar; MaxLen: Cardinal): PChar; assembler;
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV ESI,EAX
MOV EDI,EDX
MOV EBX,ECX
XOR AL,AL
TEST ECX,ECX
JZ @@1
REPNE SCASB
JNE @@1
INC ECX
@@1: SUB EBX,ECX
MOV EDI,ESI
MOV ESI,EDX
MOV EDX,EDI
MOV ECX,EBX
SHR ECX,2
REP MOVSD
MOV ECX,EBX
AND ECX,3
REP MOVSB
STOSB
MOV EAX,EDX
POP EBX
POP ESI
POP EDI
end;
function StrPCopy(Dest: PChar; const Source: string): PChar;
begin
Result := StrLCopy(Dest, PChar(Source), Length(Source));
end;
{ **************************************************************************** }
// Warning!!! Do not use this metod in client App
function CreateSenderObject(SenderName: PAnsiChar): boolean;
begin
Result := true;
hFileMapObj:=CreateFileMapping(MAXDWORD,nil,PAGE_READWRITE,0,4,SenderName);
if (hFileMapObj=0) then
Result := false
else
lpBaseAddress:=MapViewOfFile(hFileMapObj,FILE_MAP_WRITE,0,0,0);
if lpBaseAddress = nil then
Result := false;
end;
function SendToObject(SenderSt: String): boolean;
begin
Result := true;
try
StrPCopy(lpBaseAddress,SenderSt);
except
Result := false;
end;
end;
Procedure CloseSenderObject;
begin
UnMapViewOfFile(lpBaseAddress);
CloseHandle(hFileMapObj);
end;
{ **************************************************************************** }
// Warning!!! Do not use this metod in server App
function GetObjectResult(SenderName: PAnsiChar): string;
begin
hFileMapObj:=CreateFileMapping(MAXDWORD,Nil,PAGE_READWRITE,0,4,SenderName);
if (hFileMapObj=0) then
Result := ''
else
lpBaseAddress:=MapViewOfFile(hFileMapObj,FILE_MAP_WRITE,0,0,0);
if lpBaseAddress = nil then
Result := '';
//
Result := PChar(lpBaseAddress);
UnMapViewOfFile(lpBaseAddress);
CloseHandle(hFileMapObj);
end;
function sendstring(ServerCapt: String; str: pchar): boolean;
begin
// Send to process handle
if FindWindow(nil, PChar(ServerCapt)) = 0 then
begin
result := false;
Exit;
end;
cd.cbData := Length(str) + 1;
cd.lpData := PChar(str);
SendMessage(FindWindow(nil, PChar(ServerCapt)), WM_COPYDATA, 0, LParam(@cd));
result := true;
end;
{ **************************************************************************** }
end. |
unit TextEditor.Search.Wildcard;
interface
uses
System.Classes, TextEditor.Search.RegularExpressions;
type
TTextEditorWildcardSearch = class(TTextEditorRegexSearch)
protected
function WildCardToRegExpr(const AWildCard: string): string;
procedure SetPattern(const AValue: string); override;
end;
implementation
procedure TTextEditorWildcardSearch.SetPattern(const AValue: string);
begin
FPattern := WildCardToRegExpr(AValue);
end;
function TTextEditorWildcardSearch.WildCardToRegExpr(const AWildCard: string): string;
var
LIndex: Integer;
begin
Result := '';
for LIndex := 1 to Length(AWildCard) do
case AWildCard[LIndex] of
'*':
Result := Result + '.*';
'?':
Result := Result + '.?';
else
Result := Result + AWildCard[LIndex];
end;
end;
end.
|
unit RtcSqlQuery;
interface
uses
SysUtils, Classes, rtcFunction, rtcDataCli, rtcCliModule, rtcInfo, rtcConn, rtcHttpCli, rtcLog,
rtcDB, DB, MemTableEh, variants, hpuclientinterface;
type
TResponseEvent = procedure (Sender:TObject; Result: TRtcValue);
{ TSQLStringList = class (TStringList)
private
FOnChange: TNotifyEvent;
public
function Add(const S:String):Integer;override;
procedure Delete(Index:Integer);override;
procedure Clear;override;
property OnChange:TNotifyEvent Read FOnChange write FOnChange;
end; }
TRemoteTransactionType = (ttReadCommited=0,ttStability=1, ttSnapshot=2 );
TRtcQuery = class (TObject)
private
FActive: Boolean;
FCurrentUser: PUserInfo;
FSql: TStringList;
FParams: TParams;
FClientModule: TRtcClientModule;
FQrResult: TRtcValue;
FOnSelectResponse: TResponseEvent;
FOnQueryResponse: TResponseEvent;
procedure DoSQlListOnChange(Sender:TObject);
function GetActive: Boolean;
procedure SetActive(const Value: Boolean);
public
constructor Create(AClientModule:TRtcClientModule;ACurrentUser:PUserInfo);
destructor Destroy;override;
procedure Close;
procedure ExecQuery;
function FieldByName(const AFieldName:String):TRtcValue;
function Bof: Boolean;
function Eof: Boolean;
function IsEmpty: Boolean;
procedure First;
procedure FullRefresh;
procedure Next;
procedure Open;
procedure Prior;
function ParamByName(const Aname: String):TParam;
procedure Select(ADataSet:TDataSet);
function QueryValue(const ASql:String; AParams: array of variant ):Variant;
property Active:Boolean read GetActive write SetActive;
property ClientModule: TRtcClientModule read FClientModule write FClientModule;
property Params:TParams read FParams;
property SQL:TStringList read FSQL;
property OnSelectResponse:TResponseEvent read FOnSelectResponse write FOnSelectResponse;
property OnQueryResponse:TResponseEvent read FOnQueryResponse write FOnQueryResponse;
property QrResult: TRtcValue read FQrResult;
property CurrentUser:PUserInfo Read FCurrentUser write FCurrentUser;
end;
TRtcSqlExecute = class (TObject)
private
FCurrentUser: PUserInfo;
FIdTransaction: Cardinal;
FSql: TStringList;
FParams: TParams;
FClientModule: TRtcClientModule;
FQrResult: TRtcValue;
procedure DoSQlListOnChange(Sender:TObject);
public
constructor Create(AClientModule:TRtcClientModule;ACurrentUser:PUserInfo);
procedure Close;
destructor Destroy;override;
procedure ExecQuery(ATransaction:TRemoteTransactionType = ttReadCommited);
function IsTransactionActive:Boolean;
function ParamByName(const Aname: String):TParam;
procedure StartTransaction(AType:TRemoteTransactionType = ttStability);
procedure Commit;
procedure RollBack;
class function GetRemoteTransactionTypeasInteger(AType:TRemoteTransactionType):Integer;
property ClientModule: TRtcClientModule read FClientModule write FClientModule;
property Params:TParams read FParams;
property SQL:TStringList read FSQL;
property QrResult: TRtcValue read FQrResult;
property CurrentUser:PUserInfo Read FCurrentUser write FCurrentUser;
end;
implementation
{ TRtcQuery }
function TRtcQuery.Bof: Boolean;
begin
FQrResult.asDataSet.BOF;
end;
procedure TRtcQuery.Close;
begin
// FSql.Clear;
if Assigned(FQrResult) then
FQrResult.Clear
end;
constructor TRtcQuery.Create;
begin
FSql:= TStringList.Create;
FParams:= TParams.Create;
FOnSelectResponse := nil;
FOnQueryResponse := nil;
FSQL.OnChange := DoSQlListOnChange;
FQrResult := TRtcValue.Create;
FCurrentUser := ACurrentUser;
FClientModule := AClientModule;
end;
destructor TRtcQuery.Destroy;
begin
FQrResult.Clear;
FreeAndNil(FQrResult);
FreeAndNil(FSql);
FreeAndNil(FParams);
FOnSelectResponse := nil;
FOnQueryResponse := nil;
inherited;
end;
procedure TRtcQuery.DoSQlListOnChange(Sender: TObject);
begin
FParams.Clear;
FParams.ParseSQL(FSQL.Text,True);
end;
function TRtcQuery.Eof: Boolean;
begin
Result := FQrResult.asDataSet.EOF;
end;
procedure TRtcQuery.ExecQuery;
begin
Select(nil);
end;
function TRtcQuery.FieldByName(const AFieldName: String): TRtcValue;
begin
Result := FQrResult.asDataSet.FieldByName(AFieldName)
end;
procedure TRtcQuery.First;
begin
FQrResult.asDataSet.First;
end;
procedure TRtcQuery.FullRefresh;
begin
end;
function TRtcQuery.GetActive: Boolean;
begin
Result := Assigned(QrResult.asDataSet);
end;
function TRtcQuery.IsEmpty: Boolean;
begin
FQrResult.asDataSet.Empty;
end;
procedure TRtcQuery.Next;
begin
FQrResult.asDataSet.Next;
end;
procedure TRtcQuery.Open;
begin
Select(nil);
end;
function TRtcQuery.ParamByName(const Aname: String): TParam;
begin
Result := FParams.ParamByName(AName)
end;
procedure TRtcQuery.Prior;
begin
FQrResult.asDataSet.Prior;
end;
function TRtcQuery.QueryValue(const ASql: String; AParams: array of variant): Variant;
var i: Integer;
begin
Result := null;
with FClientModule do
begin
with Prepare('RtcQueryValue') do
begin
Param.asWideString['username'] := FCurrentUser.user_name;
Param.asWideString['password'] := FCurrentUser.user_password;
Param.asWideString['SQL'] := ASql;
// Param.asInteger['Param_count'] := High(AParams);
for I := 0 to High(Aparams) do
Param.asValue['PARAM'+IntTostr(i)+'_VALUE'] := AParams[i];
try
FQrResult := Execute(False,0,False);
if FQrResult.isType=rtc_Exception then
begin
Raise Exception.Create(FQrResult.asException);
end
else
Result := FQrResult.asValue;
finally
//FreeAndNil(mResult);
end;
end;
end;
end;
procedure TRtcQuery.Select(ADataSet:TDataSet);
var i: Integer;
begin
with FClientModule do
begin
with Prepare('RtcSelectSql') do
begin
FQrResult.Clear;
Param.asWideString['username'] := FCurrentUser.user_name;
Param.asWideString['password'] := FCurrentUser.user_password;
Param.asString['SQL'] := FSql.Text;
// Param.asInteger['Param_count'] := FParams.Count;
for i := 0 to FParams.Count-1 do
begin
Param.asString['PARAM'+IntTostr(i)+'_NAME'] := FParams[i].Name;
if (FParams[i].DataType =ftDate) or (FParams[i].DataType =ftDateTime) then
Param.asDateTime['PARAM'+IntTostr(i)+'_VALUE'] := FParams[i].AsDateTime
else
Param.asValue['PARAM'+IntTostr(i)+'_VALUE'] := FParams[i].Value;
end;
try
FQrResult := Execute(False,0,False);
if FQrResult.isType=rtc_Exception then
Raise Exception.Create(FQrResult.asException)
else
begin
if Assigned(ADataSet) then
begin
ADataSet.DisableControls;
try
RtcDataSetFieldsToDelphi( FQrResult.asDataSet, ADataSet);
if ADataSet is TMemTableEh then
TMemTableEh(ADataSet).CreateDataSet;
RtcDataSetRowsToDelphi(FQrResult.asDataSet, ADataSet);
ADataSet.First;
finally
ADataSet.EnableControls;
end;
end;
if Assigned(FOnSelectResponse) then
FOnSelectResponse(Self,FQrResult);
end;
finally
if Assigned(ADataSet) then
FQrResult.Clear;
end;
end;
end;
end;
procedure TRtcQuery.SetActive(const Value: Boolean);
begin
if not Value then
Close
else
Open;
end;
{function TSQLStringList.Add(const S: String):Integer;
begin
inherited Add(s);
if Assigned(FOnChange) then
FOnChange(self)
end;
procedure TSQLStringList.Clear;
begin
inherited;
if Assigned(FOnChange) then
FOnChange(self)
end;
procedure TSQLStringList.Delete(Index: Integer);
begin
inherited;
if Assigned(FOnChange) then
FOnChange(self)
end;
}
{ TRtcUpdate }
procedure TRtcSqlExecute.Close;
begin
if Assigned(FQrResult) then
FQrResult.Clear
end;
procedure TRtcSqlExecute.Commit;
var mResult: TRtcValue;
begin
with FClientModule do
begin
with Prepare('RtcTransactionCommit') do
begin
Param.asWideString['username'] := FCurrentUser.user_name;
Param.asWideString['password'] := FCurrentUser.user_password;
Param.asCardinal['trid'] := FIdTransaction;
mResult := Execute(False,0,False);
FIdTransaction := 0;
if mResult.isType=rtc_Exception then
raise Exception.Create(mResult.asException);
end;
end;
end;
constructor TRtcSqlExecute.Create(AClientModule: TRtcClientModule; ACurrentUser: PUserInfo);
begin
FSql:= TStringList.Create;
FParams:= TParams.Create;
FSQL.OnChange := DoSQlListOnChange;
FQrResult := TRtcValue.Create;
FCurrentUser := ACurrentUser;
FClientModule := AClientModule;
FIdTransaction := 0;
end;
destructor TRtcSqlExecute.Destroy;
begin
FQrResult.Clear;
FreeAndNil(FQrResult);
FreeAndNil(FSql);
FreeAndNil(FParams);
inherited;
end;
procedure TRtcSqlExecute.DoSQlListOnChange(Sender: TObject);
begin
FParams.Clear;
FParams.ParseSQL(FSQL.Text,True);
end;
procedure TRtcSqlExecute.ExecQuery(ATransaction: TRemoteTransactionType);
var i: Integer;
begin
// if FIdTransaction=0 then
// Param.asInteger['TypeTransaction'] := TRtcSqlExecute.GetRemoteTransactionTypeAsInteger(ATransaction);
with FClientModule do
begin
with Prepare('RtcSqlExecute') do
begin
FQrResult.Clear;
Param.asWideString['username'] := FCurrentUser.user_name;
Param.asWideString['password'] := FCurrentUser.user_password;
Param.asString['SQL'] := FSql.Text;
// Param.asInteger['Param_count'] := FParams.Count;
for i := 0 to FParams.Count-1 do
begin
Param.asString['PARAM'+IntTostr(i)+'_NAME'] := FParams[i].Name;
if (FParams[i].DataType =ftDate) or (FParams[i].DataType =ftDateTime) then
Param.asDateTime['PARAM'+IntTostr(i)+'_VALUE'] := FParams[i].AsDateTime
else
Param.asValue['PARAM'+IntTostr(i)+'_VALUE'] := FParams[i].Value;
end;
if FIdTransaction>0 then
Param.asCardinal['trid'] := FIdTransaction
else
Param.asInteger['TypeTransaction'] := TRtcSqlExecute.GetRemoteTransactionTypeAsInteger(ATransaction);
//try
FQrResult := Execute(False,0,False);
if FQrResult.isType=rtc_Exception then
Raise Exception.Create(FQrResult.asException);
//end;
end;
end;
end;
class function TRtcSqlExecute.GetRemoteTransactionTypeasInteger(AType: TRemoteTransactionType): Integer;
begin
case AType of
ttReadCommited: Result := 0;
ttStability: Result := 1;
ttSnapshot: Result := 2;
end;
end;
function TRtcSqlExecute.IsTransactionActive: Boolean;
begin
Result := FIdTransaction > 0;
end;
function TRtcSqlExecute.ParamByName(const Aname: String): TParam;
begin
Result := FParams.ParamByName(AName);
end;
procedure TRtcSqlExecute.RollBack;
var mResult: TRtcValue;
begin
with FClientModule do
begin
with Prepare('RtcTransactionRollback') do
begin
Param.asWideString['username'] := FCurrentUser.user_name;
Param.asWideString['password'] := FCurrentUser.user_password;
Param.asCardinal['trid'] := FIdTransaction;
mResult := Execute(False);
FIdTransaction := 0;
if mResult.isType=rtc_Exception then
raise Exception.Create(mResult.asException);
end;
end;
end;
procedure TRtcSqlExecute.StartTransaction;
var mResult: TRtcValue;
begin
with FClientModule do
begin
with Prepare('RtcStartTransaction') do
begin
Param.asWideString['username'] := FCurrentUser.user_name;
Param.asWideString['password'] := FCurrentUser.user_password;
Param.AsInteger['TypeTransaction'] := TRtcSqlExecute.GetRemoteTransactionTypeAsInteger(AType);
mResult := Execute(False,0,False);
if mResult.isType=rtc_Exception then
raise Exception.Create(mResult.asException);
FIdTransaction := mResult.asCardinal
end;
end;
end;
end.
|
unit UdmPersistenceQueryClient;
interface
uses
System.SysUtils, System.Classes, 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, FireDAC.Stan.StorageBin, System.StrUtils;
type
TdmPersistenceQueryClient = class(TDataModule)
MemConsulta : TFDMemTable;
FDStanStorageBinLink1 : TFDStanStorageBinLink;
private
{ Private declarations }
FHostIntegrationService : String;
FPortIntegrationPersistence : Integer;
public
{ Public declarations }
FMensajeAlerta : String;
function query(AUUID, tx, fields, filter, order, responseFormat, index : String): Boolean;
constructor create_(AHostIntegrationService : String; APortIntegrationPersistence : Integer);
destructor destroy_;
end;
const
TX_PERSISTENCE_QUERY = 'TX_800_PERSISTENCE_QUERY_UDP';
STATUS_CODE_EXITOSO = '00';
TX_TRANSACTION = 'tx_code';
FIELDS_NAME = 'fields';
FILTER_DEFINITION = 'filter';
ORDER_DEFINITION = 'order';
RESPONSE_FORMAT = 'response_format';
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses UdmIntegrationServiceClient, LCallIntegration_Intf, fServerDataModule, UUtilidades, UdmConfiguracion;
{$R *.dfm}
{ TdmQuery }
constructor TdmPersistenceQueryClient.create_(AHostIntegrationService : String; APortIntegrationPersistence: Integer);
begin
self.create(nil);
FHostIntegrationService := AHostIntegrationService;
FPortIntegrationPersistence := APortIntegrationPersistence;
end;
destructor TdmPersistenceQueryClient.destroy_;
begin
MemConsulta.Close;
self.destroy;
end;
function TdmPersistenceQueryClient.query(AUUID, tx, fields, filter, order, responseFormat, index : String) : Boolean;
var
responseStr : AnsiString;
boolResult : Boolean;
responseIntServ : LCallIntegration_Intf.ResponseInfo_;
strParameters : String;
xCallIntegrationServiceClient : TdmIntegrationServiceClient;
lstParameters : TStringList;
datosConsulta : TStringStream;
strMensajeCorreo : String;
StrStatusCode : String;
StrStatusDesc : String;
begin
try
xCallIntegrationServiceClient := TdmIntegrationServiceClient.Create(nil);
responseIntServ := LCallIntegration_Intf.ResponseInfo_.Create;
datosConsulta := TStringStream.Create;
boolResult := False;
strParameters := '';
lstParameters := TStringList.Create;
lstParameters.Clear;
lstParameters.Values[TX_TRANSACTION] := String(tx);
lstParameters.Values[FIELDS_NAME] := String(fields);
lstParameters.Values[FILTER_DEFINITION] := String(filter);
lstParameters.Values[ORDER_DEFINITION] := String(order);
lstParameters.Values[RESPONSE_FORMAT] := String(responseFormat);
try
strParameters := lstParameters.Text;
responseIntServ := xCallIntegrationServiceClient.CallIntegrationService(TX_PERSISTENCE_QUERY, strParameters, FHostIntegrationService, FPortIntegrationPersistence);
FMensajeAlerta := responseIntServ.statusDesc;
if responseIntServ.statusCode = STATUS_CODE_EXITOSO then
begin
responseStr := AnsiString(ResponseIntServ.responseData);
datosConsulta.WriteString(String(responseStr));
datosConsulta.Position := 0;
MemConsulta.Close;
MemConsulta.IndexFieldNames := '';
MemConsulta.LoadFromStream(datosConsulta);
MemConsulta.IndexFieldNames := String(index);
MemConsulta.Open;
if tx = TX_JANUA_CONFIGURATION_QUERY then
ServerDataModule.FInicializacionJanua := true;
boolResult := True;
end
else
begin
FMensajeAlerta := responseIntServ.statusDesc;
//
ServerDataModule.EntrarModoStandBy;
strMensajeCorreo := 'nombre_aplicacion='+ strApplication + ',' +
'nombre_transaccion=' + tx + '- PERSISTENCE QUERY,' +
'mensaje_error=' + 'Error al consumir Persistence Query - ' + responseIntServ.statusDesc + ','+
'fecha_error=' + DateTimeToStr(Now);
strMensajeCorreo := AnsiReplaceStr(strMensajeCorreo,',',#13#10);
TUtilidades.sendEmailTemplate(AUUID, CORREO_ERROR, strMensajeCorreo, StrStatusCode, StrStatusDesc);
end;
except on e : exception do
begin
FMensajeAlerta := e.Message;
//
ServerDataModule.EntrarModoStandBy;
strMensajeCorreo := 'nombre_aplicacion='+ strApplication + ',' +
'nombre_transaccion=' + tx + '- PERSISTENCE QUERY,' +
'mensaje_error=' + 'Error al consumir Persistence Query - ' + responseIntServ.statusDesc + ','+
'fecha_error=' + DateTimeToStr(Now);
strMensajeCorreo := AnsiReplaceStr(strMensajeCorreo,',',#13#10);
TUtilidades.sendEmailTemplate(AUUID, CORREO_ERROR, strMensajeCorreo, StrStatusCode, StrStatusDesc);
end;
end;
finally
datosConsulta.Clear;
lstParameters.Clear;
FreeAndNil(datosConsulta);
FreeAndNil(lstParameters);
FreeAndNil(responseIntServ);
FreeAndNil(xCallIntegrationServiceClient);
end;
result := boolResult;
end;
end.
|
unit FreeOTFEfmeOptions_AutoRun;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FreeOTFESettings, StdCtrls, ComCtrls,
OTFEFreeOTFE_InstructionRichEdit, SDUDialogs, SDUStdCtrls,
CommonfmeOptions_Base,
FreeOTFEfmeOptions_Base;
type
TfmeOptions_Autorun = class(TfmeFreeOTFEOptions_Base)
gbAutorun: TGroupBox;
Label33: TLabel;
Label34: TLabel;
Label35: TLabel;
edPostMountExe: TEdit;
pbPostMountBrowse: TButton;
pbPreDismountBrowse: TButton;
edPreDismountExe: TEdit;
pbPostDismountBrowse: TButton;
edPostDismountExe: TEdit;
ckPrePostExeWarn: TSDUCheckBox;
OpenDialog: TSDUOpenDialog;
reInstructions: TOTFEFreeOTFE_InstructionRichEdit;
procedure pbPostMountBrowseClick(Sender: TObject);
procedure pbPreDismountBrowseClick(Sender: TObject);
procedure pbPostDismountBrowseClick(Sender: TObject);
protected
procedure _ReadSettings(config: TFreeOTFESettings); override;
procedure _WriteSettings(config: TFreeOTFESettings); override;
public
procedure Initialize(); override;
end;
implementation
{$R *.dfm}
uses
SDUi18n,
SDUGeneral;
{$IFDEF _NEVER_DEFINED}
// This is just a dummy const to fool dxGetText when extracting message
// information
// This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to
// picks up SDUGeneral.SDUCRLF
const
SDUCRLF = ''#13#10;
{$ENDIF}
resourcestring
FILTER_EXECUTABLE_FILES = 'Program files (*.exe, *.com, *.bat)|*.exe; *.bat; *.com|All files|*.*';
procedure TfmeOptions_Autorun.pbPostMountBrowseClick(Sender: TObject);
begin
inherited;
OpenDialog.title := _('Locate post mount executable');
OpenDialog.Filter := FILTER_EXECUTABLE_FILES;
OpenDialog.Options := OpenDialog.Options + [ofDontAddToRecent];
SDUOpenSaveDialogSetup(OpenDialog, edPostMountExe.text);
if (OpenDialog.execute) then
begin
// Strip drive letter
edPostMountExe.text := copy(OpenDialog.Filename, 3, length(OpenDialog.Filename)-2);
end;
end;
procedure TfmeOptions_Autorun.pbPreDismountBrowseClick(Sender: TObject);
begin
inherited;
OpenDialog.title := _('Locate pre dismount executable');
OpenDialog.Filter := FILTER_EXECUTABLE_FILES;
OpenDialog.Options := OpenDialog.Options + [ofDontAddToRecent];
SDUOpenSaveDialogSetup(OpenDialog, edPreDismountExe.text);
if (OpenDialog.execute) then
begin
// Strip drive letter
edPreDismountExe.text := copy(OpenDialog.Filename, 3, length(OpenDialog.Filename)-2);
end;
end;
procedure TfmeOptions_Autorun.pbPostDismountBrowseClick(Sender: TObject);
begin
inherited;
OpenDialog.title := _('Locate post dismount executable');
OpenDialog.Filter := FILTER_EXECUTABLE_FILES;
OpenDialog.Options := OpenDialog.Options + [ofDontAddToRecent];
SDUOpenSaveDialogSetup(OpenDialog, edPostDismountExe.text);
if (OpenDialog.execute) then
begin
edPostDismountExe.text := OpenDialog.Filename;
end;
end;
procedure TfmeOptions_Autorun._ReadSettings(config: TFreeOTFESettings);
begin
edPostMountExe.text := config.OptPostMountExe;
edPreDismountExe.text := config.OptPreDismountExe;
edPostDismountExe.text := config.OptPostDismountExe;
ckPrePostExeWarn.checked := config.OptPrePostExeWarn;
end;
procedure TfmeOptions_Autorun._WriteSettings(config: TFreeOTFESettings);
begin
config.OptPostMountExe := edPostMountExe.text;
config.OptPreDismountExe := edPreDismountExe.text;
config.OptPostDismountExe := edPostDismountExe.text;
config.OptPrePostExeWarn := ckPrePostExeWarn.checked;
end;
procedure TfmeOptions_Autorun.Initialize();
begin
inherited;
SDUCenterControl(gbAutorun, ccHorizontal);
SDUCenterControl(gbAutorun, ccVertical, 25);
// Setup instructions text
reInstructions.Text :=
_('FreeOTFE can be configured here to automatically run programs after mounting, before dismounting, and after dismounting.'+SDUCRLF+
SDUCRLF+
'Any post-mount and pre-dismount executables specified must use a relative path to the executable within the mounted volume (i.e. absolute and UNC paths are not allowed for security reasons)'+SDUCRLF+
SDUCRLF+
'Executables with spaces in their paths/names must be surrounded with double quotes.'+SDUCRLF+
SDUCRLF+
'"%DRIVE" will be substituted with the drive letter of the mounted drive letter');
end;
END.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Janela de critérios para compra sugerida
The MIT License
Copyright: Copyright (C) 2015 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (alberteije@gmail.com)
@version 2.0
******************************************************************************* }
unit UCriterioCompraSugerida;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DBClient, Grids, DBGrids, StdCtrls, ExtCtrls, ActnList,
RibbonSilverStyleActnCtrls, ActnMan, ToolWin, ActnCtrls, LabeledCtrls, ComCtrls,
System.Actions, Vcl.Imaging.pngimage, Controller;
type
TFCriterioCompraSugerida = class(TForm)
PanelCabecalho: TPanel;
Bevel1: TBevel;
Image1: TImage;
Label2: TLabel;
ActionToolBarPrincipal: TActionToolBar;
ActionManagerLocal: TActionManager;
ActionCancelar: TAction;
ActionGerarRequisicao: TAction;
PageControlItens: TPageControl;
tsDados: TTabSheet;
PanelDados: TPanel;
ActionSair: TAction;
ActionGerarPedido: TAction;
CDSProduto: TClientDataSet;
DSProduto: TDataSource;
CDSProdutoID: TIntegerField;
CDSProdutoNOME: TStringField;
CDSProdutoVALOR_VENDA: TFMTBCDField;
ComboboxSelecao: TLabeledComboBox;
procedure ActionCancelarExecute(Sender: TObject);
procedure ActionSairExecute(Sender: TObject);
procedure ActionGerarRequisicaoExecute(Sender: TObject);
procedure ActionGerarPedidoExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FCriterioCompraSugerida: TFCriterioCompraSugerida;
implementation
uses
UMenu, UDataModule, UCompraPedido, UCompraRequisicao, ProdutoController;
{$R *.dfm}
/// EXERCICIO: IMPLEMENTE OUTROS CRITERIOS DE GERAR UMA COMPRA SUGERIDA
procedure TFCriterioCompraSugerida.ActionCancelarExecute(Sender: TObject);
begin
Close;
end;
procedure TFCriterioCompraSugerida.ActionSairExecute(Sender: TObject);
begin
Close;
end;
procedure TFCriterioCompraSugerida.ActionGerarPedidoExecute(Sender: TObject);
begin
// Estoque Mínimo
if ComboboxSelecao.ItemIndex = 0 then
begin
TProdutoController.SetDataSet(CDSProduto);
TController.ExecutarMetodo('ProdutoController.TProdutoController', 'Consulta', ['QUANTIDADE_ESTOQUE<ESTOQUE_MINIMO', '0', False], 'GET', 'Lista');
end;
if CDSProduto.RecordCount > 0 then
begin
FMenu.ActionCompraPedido.Execute;
((FMenu.JvPageList.ActivePage.Components[0] as TForm) as TFCompraPedido).BotaoInserir.Click;
CDSProduto.First;
while not CDSProduto.Eof do
begin
((FMenu.JvPageList.ActivePage.Components[0] as TForm) as TFCompraPedido).CDSCompraPedidoDetalhe.Append;
((FMenu.JvPageList.ActivePage.Components[0] as TForm) as TFCompraPedido).CDSCompraPedidoDetalheID_PRODUTO.AsInteger := CDSProdutoID.AsInteger;
((FMenu.JvPageList.ActivePage.Components[0] as TForm) as TFCompraPedido).CDSCompraPedidoDetalheProdutoNome.AsString := CDSProdutoNOME.AsString;
((FMenu.JvPageList.ActivePage.Components[0] as TForm) as TFCompraPedido).CDSCompraPedidoDetalheVALOR_UNITARIO.AsExtended := CDSProdutoVALOR_VENDA.AsExtended;
((FMenu.JvPageList.ActivePage.Components[0] as TForm) as TFCompraPedido).CDSCompraPedidoDetalhe.Post;
CDSProduto.Next;
end;
Close;
end
else
Application.MessageBox('Não existem dados para os critérios informados.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
end;
procedure TFCriterioCompraSugerida.ActionGerarRequisicaoExecute(Sender: TObject);
begin
// Estoque Mínimo
if ComboboxSelecao.ItemIndex = 0 then
begin
TProdutoController.SetDataSet(CDSProduto);
TController.ExecutarMetodo('ProdutoController.TProdutoController', 'Consulta', ['QUANTIDADE_ESTOQUE<ESTOQUE_MINIMO', '0', False], 'GET', 'Lista');
end;
if CDSProduto.RecordCount > 0 then
begin
FMenu.ActionCompraRequisicao.Execute;
((FMenu.JvPageList.ActivePage.Components[0] as TForm) as TFCompraRequisicao).BotaoInserir.Click;
CDSProduto.First;
while not CDSProduto.Eof do
begin
((FMenu.JvPageList.ActivePage.Components[0] as TForm) as TFCompraRequisicao).CDSCompraRequisicaoDetalhe.Append;
((FMenu.JvPageList.ActivePage.Components[0] as TForm) as TFCompraRequisicao).CDSCompraRequisicaoDetalhe.FieldByName('ID_PRODUTO').AsInteger := CDSProdutoID.AsInteger;
((FMenu.JvPageList.ActivePage.Components[0] as TForm) as TFCompraRequisicao).CDSCompraRequisicaoDetalhe.FieldByName('PRODUTO.NOME').AsString := CDSProdutoNOME.AsString;
((FMenu.JvPageList.ActivePage.Components[0] as TForm) as TFCompraRequisicao).CDSCompraRequisicaoDetalhe.Post;
CDSProduto.Next;
end;
Close;
end
else
Application.MessageBox('Não existem dados para os critérios informados.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
end;
end.
|
unit uRotinasSIPAntigo;
interface
uses uInterfaceSIP, Windows, SysUtils, Inpulse.SIP.Models.Resgistrar;
type
tMetodoSIP = function(const pParam: TObject): PAnsiChar; //stdcall;
type
TRotinasSIPAntigo = class(TInterfacedObject, ISip)
private
DLLProg:Cardinal;
MetodoSIP: tMetodoSIP;
public
function Ligar(const pObj: TObject):String;
function Transferir(const pObj: TObject):String;
function EnviarDTMF(const pObj: TObject):String;
function Desligar:String;
function Registrar(const pObj:TObject):String;
function GetState:String;
constructor create;
destructor destroy;
class function New(pDLLProg:Cardinal): ISip;
End;
implementation
{ TRotinasSIPAntigo }
constructor TRotinasSIPAntigo.create;
begin
inherited;
end;
class function TRotinasSIPAntigo.New(pDLLProg:Cardinal): ISip;
begin
Result := Self.create;
TRotinasSIPAntigo(Result).DLLProg := pDLLProg;
end;
function TRotinasSIPAntigo.Registrar(const pObj:TObject): String;
var
vRetorno:PAnsiChar;
begin
if DLLProg = 0 then exit;
@MetodoSIP := GetProcAddress(DLLProg, PAnsiChar('Registrar'));
try
vRetorno := MetodoSIP(TRegistrar(pObj));
if vRetorno <> '' then
raise Exception.Create(vRetorno);
except
on E: Exception do
raise Exception.Create(e.message);
end;
end;
function TRotinasSIPAntigo.Transferir(const pObj: TObject): String;
var
vRetorno:PAnsiChar;
begin
if DLLProg = 0 then exit;
@MetodoSIP := GetProcAddress(DLLProg, PAnsiChar('Transferir'));
try
vRetorno := MetodoSIP(TModelLigar(pObj));
if vRetorno <> '' then
raise Exception.Create(vRetorno);
except
on E: Exception do
raise Exception.Create(e.message);
end;
end;
function TRotinasSIPAntigo.Desligar: String;
var
vRetorno:PAnsiChar;
begin
if DLLProg = 0 then exit;
@MetodoSIP := GetProcAddress(DLLProg, PAnsiChar('Desligar'));
try
vRetorno := MetodoSIP(nil);
if vRetorno <> '' then
raise Exception.Create(vRetorno);
except
on E: Exception do
raise Exception.Create(e.message);
end;
end;
destructor TRotinasSIPAntigo.destroy;
begin
end;
function TRotinasSIPAntigo.EnviarDTMF(const pObj: TObject): String;
var
vRetorno:PAnsiChar;
begin
if DLLProg = 0 then exit;
@MetodoSIP := GetProcAddress(DLLProg, PAnsiChar('EnviarDTMF'));
try
vRetorno := MetodoSIP(TModelLigar(pObj));
if vRetorno <> '' then
raise Exception.Create(vRetorno);
except
on E: Exception do
raise Exception.Create(e.message);
end;
end;
function TRotinasSIPAntigo.GetState: String;
var
vRetorno:WideString;
begin
if DLLProg = 0 then exit;
@MetodoSIP := GetProcAddress(DLLProg, PAnsiChar('GetState'));
try
vRetorno := MetodoSIP(TModelLigar(nil));
if Pos('ERRO',UpperCase(Pchar(vRetorno))) > 0 then
raise Exception.Create(vRetorno)
else
Result := vRetorno;
except
on E: Exception do
raise Exception.Create(e.message);
end;
end;
function TRotinasSIPAntigo.Ligar(const pObj: TObject): String;
var
vRetorno:PAnsiChar;
begin
if DLLProg = 0 then exit;
@MetodoSIP := GetProcAddress(DLLProg, PAnsiChar('Ligar'));
try
vRetorno := MetodoSIP(TModelLigar(pObj));
if vRetorno <> '' then
raise Exception.Create(vRetorno);
except
on E: Exception do
raise Exception.Create(e.message);
end;
end;
end.
|
unit uAddAdmin;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBase, StdCtrls, Buttons, ExtCtrls, ComCtrls, ADODB;
type
TfrmAddAdmin = class(TfrmBase)
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
edtId: TEdit;
edtPwd: TEdit;
cbType: TComboBox;
Label5: TLabel;
meoDes: TMemo;
cbUse: TCheckBox;
Label6: TLabel;
private
{ Private declarations }
FEditMode: Boolean;
FListView: TListView;
protected
//数据操作过程
procedure LoadData; override;
procedure SaveData; override;
//检查数据
function CheckData: Boolean; override;
public
{ Public declarations }
end;
var
frmAddAdmin: TfrmAddAdmin;
function ShowAddAdmin(AListView: TListView; AEditMode: Boolean = False): Boolean;
implementation
uses uData, uGlobal;
{$R *.dfm}
function ShowAddAdmin(AListView: TListView; AEditMode: Boolean): Boolean;
begin
with TfrmAddAdmin.Create(Application) do
begin
FEditMode := AEditMode;
FListView := AListView;
if FEditMode then
Caption := '编辑管理员'
else Caption := '添加管理员';
imgHelp.Visible := False;
try
LoadData();
Result := ShowModal() = mrOk;
finally
Free;
end;
end;
end;
procedure TfrmAddAdmin.LoadData;
var
aqAdmin: TADOQuery;
id: Integer;
begin
if not FEditMode then Exit;
aqAdmin := TADOQuery.Create(Self);
try
id := Integer(FListView.Selected.Data);
dmPer.OpenQuery(aqAdmin, 'SELECT * FROM [admin] WHERE id=' + IntToStr(id));
if aqAdmin.RecordCount <> 0 then
begin
edtId.Text := aqAdmin.FieldByName('uid').AsString;
edtPwd.Text := aqAdmin.FieldByName('pwd').AsString;
cbType.ItemIndex := aqAdmin.FieldByName('type').AsInteger;
cbUse.Checked := aqAdmin.FieldByName('inUse').AsBoolean;
meoDes.Text := aqAdmin.FieldByName('des').AsString;
end;
finally
aqAdmin.Free;
end;
end;
procedure TfrmAddAdmin.SaveData;
var
id: Integer;
begin
if FEditMode then //编辑
begin
id := Integer(FListView.Selected.Data);
dmPer.ExecSQL('UPDATE [admin] SET uid=' + QuotedStr(Trim(edtId.Text)) + ', pwd=' + QuotedStr(edtPwd.Text) +
', type=' + IntToStr(cbType.ItemIndex) + ', inUse=' + BoolToStr(cbUse.Checked, True) + ', des=' + QuotedStr(meoDes.Text) + ' WHERE id=' + IntToStr(id));
//更新列表信息
with FListView.Selected do
begin
Caption := Trim(edtId.Text);
SubItems[0] := cbType.Text;
if cbUse.Checked then
SubItems[1] := '启用'
else SubItems[1] := '禁用';
SubItems[2] := meoDes.Text;
end;
Log.Write('更新了' + ADMIN_TYPE[cbType.ItemIndex] + '[' + edtId.Text + ']');
end
else //添加
begin
dmPer.ExecSQL('INSERT INTO [admin](uid, pwd, type, inUse, des) VALUES(' + QuotedStr(Trim(edtId.Text)) + ', ' + QuotedStr(edtPwd.Text) +
', ' + IntToStr(cbType.ItemIndex) + ', ' + BoolToStr(cbUse.Checked, True) + ', ' + QuotedStr(meoDes.Text) + ')');
//获取其ID,生成新的列表项
id := StrToIntDef(VarToStr(dmPer.GetFieldValue('SELECT @@identity AS id FROM [admin]', 'id')), 0);
with FListView.Items.Add do
begin
Caption := Trim(edtId.Text);
SubItems.Append(cbType.Text);
if cbUse.Checked then
SubItems.Append('启用')
else SubItems.Append('禁用');
SubItems.Append(meoDes.Text);
ImageIndex := 8;
//以Data记录对应试题
Data := PInteger(id);
end;
Log.Write(App.UserID + '添加了' + ADMIN_TYPE[cbType.ItemIndex] + '[' + edtId.Text + ']');
end;
end;
function TfrmAddAdmin.CheckData: Boolean;
var
i: Integer;
ListItem: TListItem;
begin
Result := False;
if Trim(edtId.Text) = '' then
begin
MessageBox(Handle, '管理员的用户名不能为空,请输入!', '提示', MB_ICONINFORMATION + MB_OK);
edtId.SetFocus;
Exit;
end;
//是否已存在
for i := 0 to FListView.Items.Count - 1 do
begin
ListItem := FListView.Items[i];
if SameText(Trim(edtId.Text), ListItem.Caption) and (not FEditMode or FEditMode and (ListItem <> FListView.Selected)) then
begin
MessageBox(Handle, '此管理员帐号已存在,请重新设定', '提示', MB_ICONWARNING + MB_OK);
edtId.SetFocus;
Result := False;
Exit;
end;
end;
Result := inherited CheckData();
end;
end.
|
unit UFolioCarpetaDigi;
interface
uses
Classes;
type
TFolioCarpetaDigi = class
private
FImagenLocal : string; {NOMBRE DEL ARCHIVO DE IMAGEN QUE SE DESCARGA CON RUTA COMPLETA}
FXmlLocal : string; {NOMBRE DEL ARCHIVO XML QUE SE DESCARGA CON RUTA COMPLETA}
FNombreImagenFirm : string; {NOMBRE DEL ARCHIVO DE IMAGEN CON FIRMA Y ESTAMPA (CON EXTENSION PDF)}
FNombreImagenOrig : string; {NOMBRE DEL ARCHIVO DE IMAGEN ORIGINAL (CON EXTENSION TIF)}
FNombreXmlOrig : string; {NOMBRE DEL ARCHIVO XML ORIGINAL (CON EXTENSION XML)}
FRutaFtpOrig : string; {RUTA DE LA CARPETA EN EL FTP IMAGENES ORIGINALES}
FRutaFtpFirm : string; {RUTA DE LA CARPETA EN EL FTP IMAGENES FIRMADAS Y ESTAMPADAS}
FRutaLocal : string; {RUTA LOCAL DONDE SE DESCARGA LA IMAGEN}
public
property ImagenLocal : string read FImagenLocal write FImagenLocal;
property XmlLocal : string read FXmlLocal write FXmlLocal;
property NombreImagenFirm : string read FNombreImagenFirm write FNombreImagenFirm;
property NombreImagenOrig : string read FNombreImagenOrig write FNombreImagenOrig;
property NombreXmlOrig : string read FNombreXmlOrig write FNombreXmlOrig;
property RutaFtpOrig : string read FRutaFtpOrig write FRutaFtpOrig;
property RutaFtpFirm : string read FRutaFtpFirm write FRutaFtpFirm;
property RutaLocal : string read FRutaLocal write FRutaLocal;
{CONSTRUCTOR - DESTRUCTOR}
constructor Create;
destructor Destroy;
end;
implementation
{$REGION 'CONSTRUTOR AND DESTRUCTOR'}
constructor TFolioCarpetaDigi.Create;
begin
end;
destructor TFolioCarpetaDigi.Destroy;
begin
end;
{$ENDREGION}
end.
|
// FXCollectionEditor
{: Egg<p>
Edits a TXCollection<p>
<b>Historique : </b><font size=-1><ul>
<li>11/04/00 - Egg - Fixed crashes in IDE
<li>06/04/00 - Egg - Creation
</ul></font>
}
unit FXCollectionEditor;
interface
uses
Windows, Forms, XCollection, Messages, ImgList, Controls, Classes,
ActnList, Menus, ComCtrls, ToolWin, DsgnIntf;
type
TXCollectionEditor = class(TForm)
ListView: TListView;
PMListView: TPopupMenu;
ActionList: TActionList;
ACRemove: TAction;
ACMoveUp: TAction;
ACMoveDown: TAction;
ImageList: TImageList;
MIAdd: TMenuItem;
N1: TMenuItem;
N2: TMenuItem;
Moveup1: TMenuItem;
Movedown1: TMenuItem;
ToolBar1: TToolBar;
TBAdd: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
PMToolBar: TPopupMenu;
procedure TBAddClick(Sender: TObject);
procedure ListViewChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure ACRemoveExecute(Sender: TObject);
procedure ACMoveUpExecute(Sender: TObject);
procedure ACMoveDownExecute(Sender: TObject);
procedure PMToolBarPopup(Sender: TObject);
procedure PMListViewPopup(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormHide(Sender: TObject);
private
{ Déclarations privées }
FXCollection : TXCollection;
ownerComponent : TComponent;
FDesigner : IFormDesigner;
updatingListView : Boolean;
procedure PrepareListView;
procedure PrepareXCollectionItemPopup(parent : TMenuItem);
procedure OnAddXCollectionItemClick(Sender : TObject);
procedure OnNameChanged(Sender : TObject);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
{ Déclarations publiques }
procedure SetXCollection(aXCollection: TXCollection; designer: IFormDesigner);
end;
function XCollectionEditor : TXCollectionEditor;
procedure ReleaseXCollectionEditor;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
{$R *.DFM}
uses GLMisc, SysUtils, GLBehaviours, GLScene;
resourcestring
cXCollectionEditor = 'XCollection editor';
var
vXCollectionEditor : TXCollectionEditor;
function XCollectionEditor : TXCollectionEditor;
begin
if not Assigned(vXCollectionEditor) then
vXCollectionEditor:=TXCollectionEditor.Create(nil);
Result:=vXCollectionEditor;
end;
procedure ReleaseXCollectionEditor;
begin
if Assigned(vXCollectionEditor) then begin
vXCollectionEditor.Free;
vXCollectionEditor:=nil;
end;
end;
// FormCreate
procedure TXCollectionEditor.FormCreate(Sender: TObject);
begin
RegisterGLBehaviourNameChangeEvent(OnNameChanged);
end;
// FormDestroy
//
procedure TXCollectionEditor.FormDestroy(Sender: TObject);
begin
DeRegisterGLBehaviourNameChangeEvent(OnNameChanged);
end;
// FormHide
//
procedure TXCollectionEditor.FormHide(Sender: TObject);
begin
SetXCollection(nil, nil);
end;
// SetXCollection
//
procedure TXCollectionEditor.SetXCollection(aXCollection: TXCollection; designer: IFormDesigner);
begin
// if Assigned(ownerComponent) then
// ownerComponent.RemoveFreeNotification(Self);
FXCollection:=aXCollection;
FDesigner:=designer;
if Assigned(FXCollection) then begin
if Assigned(FXCollection.Owner) and (FXCollection.Owner is TComponent) then
// ownerComponent:=TComponent(FXCollection.Owner);
// if Assigned(ownerComponent) then
// ownerComponent.FreeNotification(Self);
Caption:=FXCollection.GetNamePath;
end else begin
ownerComponent:=nil;
Caption:=cXCollectionEditor;
end;
PrepareListView;
end;
// TBAddClick
//
procedure TXCollectionEditor.TBAddClick(Sender: TObject);
begin
TBAdd.CheckMenuDropdown;
end;
// ListViewChange
//
procedure TXCollectionEditor.ListViewChange(Sender: TObject;
Item: TListItem; Change: TItemChange);
var
sel : Boolean;
begin
if (Change=ctState) and Assigned(FDesigner) and (not updatingListView) then begin
// setup enablings
sel:=(ListView.Selected<>nil);
TBAdd.Enabled:=Assigned(FDesigner);
ACRemove.Enabled:=sel;
ACMoveUp.Enabled:=sel and (ListView.Selected.Index>0);
ACMoveDown.Enabled:=sel and (ListView.Selected.Index<ListView.Items.Count-1);
if Assigned(FDesigner) then
if sel then
FDesigner.SelectComponent(ListView.Selected.Data)
else FDesigner.SelectComponent(nil);
end;
end;
// PrepareListView
//
procedure TXCollectionEditor.PrepareListView;
var
i : Integer;
prevSelData : Pointer;
XCollectionItem : TXCollectionItem;
begin
Assert(Assigned(ListView));
updatingListView:=True;
try
if ListView.Selected<>nil then
prevSelData:=ListView.Selected.Data
else prevSelData:=nil;
with ListView.Items do begin
BeginUpdate;
Clear;
if Assigned(FXCollection) then begin
for i:=0 to FXCollection.Count-1 do with Add do begin
XCollectionItem:=FXCollection[i];
Caption:=Format('%d - %s', [i, XCollectionItem.Name]);
SubItems.Add(XCollectionItem.FriendlyName);
Data:=XCollectionItem;
end;
if prevSelData<>nil then
ListView.Selected:=ListView.FindData(0, prevSelData, True, False);
end;
EndUpdate;
end;
finally
updatingListView:=False;
end;
ListViewChange(Self, nil, ctState);
end;
// PrepareXCollectionItemPopup
//
procedure TXCollectionEditor.PrepareXCollectionItemPopup(parent : TMenuItem);
var
i : Integer;
list : TList;
XCollectionItemClass : TXCollectionItemClass;
mi : TMenuItem;
begin
list:=GetXCollectionItemClassesList(FXCollection.ItemsClass);
try
{$ifdef DFS_DELPHI_5_UP}
parent.Clear;
{$else}
for i:=parent.Count-1 downto 0 do parent.Delete(i);
{$endif}
for i:=0 to list.Count-1 do begin
XCollectionItemClass:=TXCollectionItemClass(list[i]);
mi:=TMenuItem.Create(owner);
mi.Caption:=XCollectionItemClass.FriendlyName;
mi.OnClick:=OnAddXCollectionItemClick;
mi.Tag:=Integer(XCollectionItemClass);
mi.Enabled:=Assigned(FXCollection) and FXCollection.CanAdd(XCollectionItemClass);
parent.Add(mi);
end;
finally
list.Free;
end;
end;
// OnNameChanged
//
procedure TXCollectionEditor.OnNameChanged(Sender : TObject);
begin
if TXCollectionItem(Sender).Owner=FXCollection then
PrepareListView;
end;
// Notification
//
procedure TXCollectionEditor.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (Operation=opRemove) and (AComponent=ownerComponent) then begin
ownerComponent:=nil;
SetXCollection(nil, nil);
Close;
end;
inherited;
end;
// OnAddXCollectionItemClick
//
procedure TXCollectionEditor.OnAddXCollectionItemClick(Sender : TObject);
var
XCollectionItemClass : TXCollectionItemClass;
XCollectionItem : TXCollectionItem;
begin
XCollectionItemClass:=TXCollectionItemClass((Sender as TMenuItem).Tag);
XCollectionItem:=XCollectionItemClass.Create(FXCollection);
PrepareListView;
ListView.Selected:=ListView.FindData(0, XCollectionItem, True, False);
FDesigner.Modified;
end;
// ACRemoveExecute
//
procedure TXCollectionEditor.ACRemoveExecute(Sender: TObject);
begin
if ListView.Selected<>nil then begin
TXCollectionItem(ListView.Selected.Data).Free;
PrepareListView;
FDesigner.Modified;
end;
end;
// ACMoveUpExecute
//
procedure TXCollectionEditor.ACMoveUpExecute(Sender: TObject);
begin
if ListView.Selected<>nil then begin
TXCollectionItem(ListView.Selected.Data).MoveUp;
PrepareListView;
FDesigner.Modified;
end;
end;
// ACMoveDownExecute
//
procedure TXCollectionEditor.ACMoveDownExecute(Sender: TObject);
begin
if ListView.Selected<>nil then begin
TXCollectionItem(ListView.Selected.Data).MoveDown;
PrepareListView;
FDesigner.Modified;
end;
end;
// PMToolBarPopup
//
procedure TXCollectionEditor.PMToolBarPopup(Sender: TObject);
begin
PrepareXCollectionItemPopup(PMToolBar.Items);
end;
// PMListViewPopup
//
procedure TXCollectionEditor.PMListViewPopup(Sender: TObject);
begin
PrepareXCollectionItemPopup(MIAdd);
end;
initialization
finalization
ReleaseXCollectionEditor;
end.
|
unit TextEditor.Selection.Colors;
interface
uses
System.Classes, Vcl.Graphics, TextEditor.Consts;
type
TTextEditorSelectionColors = class(TPersistent)
strict private
FBackground: TColor;
FForeground: TColor;
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
published
property Background: TColor read FBackground write FBackground default clSelectionColor;
property Foreground: TColor read FForeground write FForeground default clHighLightText;
end;
implementation
constructor TTextEditorSelectionColors.Create;
begin
inherited;
FBackground := clSelectionColor;
FForeground := clHighLightText;
end;
procedure TTextEditorSelectionColors.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TTextEditorSelectionColors) then
with ASource as TTextEditorSelectionColors do
begin
Self.FBackground := FBackground;
Self.FForeground := FForeground;
end
else
inherited Assign(ASource);
end;
end.
|
unit ProjectUnitsRegistratorVisitor;
interface
uses
Classes, SysUtils, StrUtils,
ParseTreeNode, ParseTreeNodeType, SourceToken,
SourceTreeWalker;
type
TProjectUnitsRegistratorVisitor = class (TInterfacedObject, INodeVisitor)
private
function ExtractUnitName(Node: TParseTreeNode): String;
function ExtractFileName(Node: TParseTreeNode): String;
public
procedure Visit(Node: TParseTreeNode);
end;
implementation
uses
UnitRegistry;
{ TProjectUnitsRegistratorVisitor }
function TProjectUnitsRegistratorVisitor.ExtractUnitName(Node: TParseTreeNode): String;
begin
Result := Node.ChildNodes[0].ChildNodes[0].Describe;
end;
function TProjectUnitsRegistratorVisitor.ExtractFileName(Node: TParseTreeNode): String;
begin
Result := '';
if (Node.ChildNodeCount = 3) and (Node.ChildNodes[2] is TSourceToken) then
begin
Result := TSourceToken(Node.ChildNodes[2]).SourceCode;
Result := AnsiReplaceStr(Result, '''', '');
end;
end;
procedure TProjectUnitsRegistratorVisitor.Visit(Node: TParseTreeNode);
var
UnitName, FileName: String;
begin
if Node.NodeType = nUsesItem then
begin
UnitName := ExtractUnitName(Node);
FileName := ExtractFileName(Node);
if (UnitName <> '') and (FileName <> '') then
TUnitRegistry.Instance.RegisterUnit(UnitName, FileName, True);
end;
end;
end. |
unit uRegisterMocks;
interface
type
/// <summary>
/// <para>
/// Recurd to make sure the Mock classes are registered, and the unique
/// ServiceNames are obtained.
/// </para>
/// <para>
/// You need to register the mock variety globally once, and give it a
/// unique name, otherwise:
/// </para>
/// <list type="bullet">
/// <item>
/// you cannot run the test twice
/// </item>
/// <item>
/// all routines after the Build use the Mock classes
/// </item>
/// </list>
/// </summary>
RegisterMocks = record
strict private
class var FTOrderEntryMockServiceName: string;
class var FTOrderValidatorMockServiceName: string;
class function GetTOrderEntryMockServiceName(): string; static;
class function GetTOrderValidatorMockServiceName(): string; static;
class procedure RegisterMockClassesIfNeeded(); static;
public
class property TOrderEntryMockServiceName: string read GetTOrderEntryMockServiceName;
class property TOrderValidatorMockServiceName: string read GetTOrderValidatorMockServiceName;
end;
implementation
uses
uRTTI,
Spring.Container,
uOrderValidatorMock,
uOrderEntryMock,
uOrderInterfaces;
class function RegisterMocks.GetTOrderEntryMockServiceName(): string;
begin
RegisterMockClassesIfNeeded();
Result := FTOrderEntryMockServiceName;
end;
class function RegisterMocks.GetTOrderValidatorMockServiceName(): string;
begin
RegisterMockClassesIfNeeded();
Result := FTOrderValidatorMockServiceName;
end;
class procedure RegisterMocks.RegisterMockClassesIfNeeded();
begin
if '' = FTOrderValidatorMockServiceName then
begin
FTOrderValidatorMockServiceName := TRtti.GetMostQualifiedName<TOrderValidatorMock, IOrderValidator>();
GlobalContainer.RegisterType<TOrderValidatorMock>().Implements<IOrderValidator>(FTOrderValidatorMockServiceName);
end;
if '' = FTOrderEntryMockServiceName then
begin
FTOrderEntryMockServiceName := TRtti.GetMostQualifiedName<TOrderEntryMock, IOrderEntry>();
GlobalContainer.RegisterType<TOrderEntryMock>().Implements<IOrderEntry>(FTOrderEntryMockServiceName);
end;
end;
initialization
RegisterMocks.TOrderValidatorMockServiceName; // force initialization
end.
|
unit untCalculoImposto;
interface
uses
System.Classes, System.SysUtils;
type
IBaseCalculoImposto = interface
['{CE2B1696-3B65-41D1-9869-586F3B511D88}']
function fcCalcular: Double;
function GetBaseCalculo: Double;
procedure SetBaseCalculo(const Value: Double);
property BaseCalculo: Double read GetBaseCalculo write SetBaseCalculo;
end;
TImpostoA = class(TInterfacedObject, IBaseCalculoImposto)
private
FBaseCalculo: Double;
procedure SetBaseCalculo(const Value: Double);
function GetBaseCalculo: Double;
public
function fcCalcular: Double;
property BaseCalculo: Double read GetBaseCalculo write SetBaseCalculo;
end;
TImpostoB = class(TInterfacedObject, IBaseCalculoImposto)
private
FImpostoA: TImpostoA;
FBaseCalculo: Double;
procedure SetImpostoA(const Value: TImpostoA);
function GetBaseCalculo: Double;
procedure SetBaseCalculo(const Value: Double);
public
function fcCalcular: Double;
property ImpostoA: TImpostoA read FImpostoA write SetImpostoA;
property BaseCalculo: Double read GetBaseCalculo write SetBaseCalculo;
end;
TImpostoC = class(TInterfacedObject, IBaseCalculoImposto)
private
FImpostoB: TImpostoB;
FBaseCalculo: Double;
procedure SetImpostoB(const Value: TImpostoB);
function GetBaseCalculo: Double;
procedure SetBaseCalculo(const Value: Double);
public
function fcCalcular: Double;
property ImpostoB: TImpostoB read FImpostoB write SetImpostoB;
property BaseCalculo: Double read GetBaseCalculo write SetBaseCalculo;
end;
implementation
{ TImpostoA }
function TImpostoA.fcCalcular: Double;
begin
Result := (FBaseCalculo * 0.20) - 500;
if Result < 0 then
Result := 0;
end;
function TImpostoA.GetBaseCalculo: Double;
begin
Result := FBaseCalculo;
end;
procedure TImpostoA.SetBaseCalculo(const Value: Double);
begin
FBaseCalculo := Value;
end;
{ TImpostoB }
function TImpostoB.fcCalcular: Double;
begin
Result := FImpostoA.fcCalcular - 15;
if Result < 0 then
Result := 0;
end;
function TImpostoB.GetBaseCalculo: Double;
begin
Result := FBaseCalculo;
end;
procedure TImpostoB.SetBaseCalculo(const Value: Double);
begin
FBaseCalculo := Value;
end;
procedure TImpostoB.SetImpostoA(const Value: TImpostoA);
begin
FImpostoA := Value;
end;
{ TImpostoC }
function TImpostoC.fcCalcular: Double;
begin
Result := FImpostoB.ImpostoA.fcCalcular + FImpostoB.fcCalcular;
if Result < 0 then
Result := 0;
end;
function TImpostoC.GetBaseCalculo: Double;
begin
Result := FBaseCalculo;
end;
procedure TImpostoC.SetBaseCalculo(const Value: Double);
begin
FBaseCalculo := Value;
end;
procedure TImpostoC.SetImpostoB(const Value: TImpostoB);
begin
FImpostoB := Value;
end;
end.
|
unit Classe.LayoutUtils;
interface
uses
interfaces.LayoutUtils, Vcl.Forms, Vcl.Graphics, System.SysUtils, Winapi.Windows, Vcl.Controls, Winapi.Messages;
type
TLayoutUtils = class(TInterfacedObject, iLayoutUtils)
private
FFormBase: TForm;
procedure CriarFormBaseEsmaecer();
public
procedure EsmaecerFundoShow();
procedure EsmaecerFundoClose();
procedure ArredondarBordas(pComponent: TWinControl);
public
constructor Create();
destructor Destroy(); override;
class function New(): iLayoutUtils;
end;
implementation
{ TLayoutUtils }
procedure TLayoutUtils.ArredondarBordas(pComponent: TWinControl);
var
R: TRect;
Rgn: HRGN;
begin
R := pComponent.ClientRect;
rgn := CreateRoundRectRgn(R.Left, R.Top, R.Right, R.Bottom, 10, 10) ;
pComponent.Perform(EM_GETRECT, 0, lParam(@r)) ;
InflateRect(r, - 4, - 4) ;
pComponent.Perform(EM_SETRECTNP, 0, lParam(@r)) ;
SetWindowRgn(pComponent.Handle, rgn, True) ;
pComponent.Invalidate;
end;
constructor TLayoutUtils.Create;
begin
CriarFormBaseEsmaecer();
end;
procedure TLayoutUtils.CriarFormBaseEsmaecer;
begin
FFormBase := TForm.Create(nil);
FFormBase.Color := ClBlack;
FFormBase.WindowState := wsMaximized;
FFormBase.AlphaBlend := True;
FFormBase.AlphaBlendValue := 110;
FFormBase.BorderStyle := bsNone;
end;
destructor TLayoutUtils.Destroy;
begin
FreeAndNil(FFormBase);
inherited;
end;
procedure TLayoutUtils.EsmaecerFundoClose;
begin
FFormBase.Close();
end;
procedure TLayoutUtils.EsmaecerFundoShow;
begin
FFormBase.Show();
end;
class function TLayoutUtils.New: iLayoutUtils;
begin
Result := Self.Create;
end;
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit ormbr.utils;
interface
uses
Rtti,
Classes,
SysUtils,
StrUtils,
Variants,
Generics.Collections;
type
TStrArray = array of String;
IUtilSingleton = interface
['{D41BA6C1-EFDB-4C58-937A-59B864A8F0F4}']
function DateTimeToIso8601(AValue: TDateTime): string;
function Iso8601ToDateTime(const AValue: string): TDateTime;
end;
TUtilSingleton = class sealed(TInterfacedObject, IUtilSingleton)
private
class var
FInstance: IUtilSingleton;
private
constructor CreatePrivate;
public
{ Public declarations }
constructor Create;
class function GetInstance: IUtilSingleton;
function DateTimeToIso8601(AValue: TDateTime): string;
function Iso8601ToDateTime(const AValue: string): TDateTime;
end;
implementation
{ TUtilSingleton }
constructor TUtilSingleton.Create;
begin
raise Exception.Create('Para usar o MappingEntity use o método TRttiSingleton.GetInstance()');
end;
constructor TUtilSingleton.CreatePrivate;
begin
inherited;
end;
/// <summary>
/// YYYY-MM-DD Thh:mm:ss or YYYY-MM-DDThh:mm:ss
/// </summary>
function TUtilSingleton.DateTimeToIso8601(AValue: TDateTime): string;
begin
if AValue = 0 then
Result := ''
else
if Frac(AValue) = 0 then
Result := FormatDateTime('yyyy"-"mm"-"dd', AValue)
else
if Trunc(AValue) = 0 then
Result := FormatDateTime('"T"hh":"nn":"ss', AValue)
else
Result := FormatDateTime('yyyy"-"mm"-"dd"T"hh":"nn":"ss', AValue);
end;
class function TUtilSingleton.GetInstance: IUtilSingleton;
begin
if not Assigned(FInstance) then
FInstance := TUtilSingleton.CreatePrivate;
Result := FInstance;
end;
function TUtilSingleton.Iso8601ToDateTime(const AValue: string): TDateTime;
var
Y, M, D, HH, MI, SS: Cardinal;
begin
// YYYY-MM-DD Thh:mm:ss or YYYY-MM-DDThh:mm:ss
// 1234567890 123456789 1234567890123456789
Result := 0;
case Length(AValue) of
9:
if (AValue[1] = 'T') and (AValue[4] = ':') and (AValue[7] = ':') then
begin
HH := Ord(AValue[2]) * 10 + Ord(AValue[3]) - (48 + 480);
MI := Ord(AValue[5]) * 10 + Ord(AValue[6]) - (48 + 480);
SS := Ord(AValue[8]) * 10 + Ord(AValue[9]) - (48 + 480);
if (HH < 24) and (MI < 60) and (SS < 60) then
Result := EncodeTime(HH, MI, SS, 0);
end;
10:
if (AValue[5] = AValue[8]) and (Ord(AValue[8]) in [Ord('-'), Ord('/')]) then
begin
Y := Ord(AValue[1]) * 1000 + Ord(AValue[2]) * 100 + Ord(AValue[3]) * 10 + Ord(AValue[4]) - (48 + 480 + 4800 + 48000);
M := Ord(AValue[6]) * 10 + Ord(AValue[7]) - (48 + 480);
D := Ord(AValue[9]) * 10 + Ord(AValue[10]) - (48 + 480);
if (Y <= 9999) and ((M - 1) < 12) and ((D - 1) < 31) then
Result := EncodeDate(Y, M, D);
end;
19,24:
if (AValue[5] = AValue[8]) and
(Ord(AValue[8]) in [Ord('-'), Ord('/')]) and
(Ord(AValue[11]) in [Ord(' '), Ord('T')]) and
(AValue[14] = ':') and
(AValue[17] = ':') then
begin
Y := Ord(AValue[1]) * 1000 + Ord(AValue[2]) * 100 + Ord(AValue[3]) * 10 + Ord(AValue[4]) - (48 + 480 + 4800 + 48000);
M := Ord(AValue[6]) * 10 + Ord(AValue[7]) - (48 + 480);
D := Ord(AValue[9]) * 10 + Ord(AValue[10]) - (48 + 480);
HH := Ord(AValue[12]) * 10 + Ord(AValue[13]) - (48 + 480);
MI := Ord(AValue[15]) * 10 + Ord(AValue[16]) - (48 + 480);
SS := Ord(AValue[18]) * 10 + Ord(AValue[19]) - (48 + 480);
if (Y <= 9999) and ((M - 1) < 12) and ((D - 1) < 31) and (HH < 24) and (MI < 60) and (SS < 60) then
Result := EncodeDate(Y, M, D) + EncodeTime(HH, MI, SS, 0);
end;
end;
end;
end.
|
{14. En una estación de peaje hay N cabinas por donde pasan varios vehículos. Desde un archivo
se lee la siguiente información:
• Número de cabina
• Tipo de vehículo (1=auto, 2=moto, 3=camioneta, 4=camión, 5=colectivo)
• Hora (0..23)
Las tarifas son: moto= $ 15, auto y camioneta=$ 30, camión=$70, colectivo=$90.
Si la hora está entre 10 y 18 sufre un incremento del %10.
Calcular e informar
a) cuántos vehículos atendió cada una de las N cabinas
b) Cuál fue la que más importe recaudó. }
program Ej14;
Uses
crt;
const
cantElem = 30;
type
TVC = array[1..cantElem] of byte;
TVI = array[1..cantElem] of real;
Procedure start(var Cant: TVC; var Imp: TVI); //incializo los dos vectores
var
i: byte;
begin
for i:= 1 to cantElem do
begin
Cant[i]:= 0;
Imp[i]:= 0;
end;
end;
Procedure lectura(var Cant: TVC; var Imp: TVI; var cabina, N: byte);
const
incremento = 0.1;
var
arch: text;
vehiculo, hora: byte;
tarifa: real;
begin
N:= 1;
assign(arch, 'datos.txt'); reset(arch);
while not eof(arch) do
begin
tarifa:= 0;
read(arch, cabina, vehiculo, hora);
case vehiculo of
1: tarifa:= 30;
2: tarifa:= 15;
3: tarifa:= 30;
4: tarifa:= 70;
5: tarifa:= 90;
end;
case hora of
10..18: tarifa:= tarifa + (tarifa*incremento);
end;
Imp[cabina]:= Imp[cabina] + tarifa;
Cant[cabina]:= Cant[cabina] + 1;
N:= N + 1;
readln(arch); //bajo de linea en el archivo
end;
close(arch);
end;
//inciso a)
Procedure show(Cant: TVC; Imp: TVI; N: byte);
var
i: byte;
begin
for i:= 1 to N do
writeln('La cabina ',i,' atendio ',Cant[i],' vehiculos. Recaudo $',Imp[i]:2:1);
writeln();
end;
//Inciso b) cual recaudo mas
Function masImp(Imp: TVI; N: byte) : byte;
var
i, k: byte;
maxImp: real;
begin
maxImp:= 0;
k:= 1;
for i:= 1 to N do
begin
if Imp[i] > maxImp then
begin
maxImp:= Imp[i];
end;
end;
while (k <= N) and (Imp[k] <> maxImp) do
k:= k + 1;
if k <= N then //lo encontro
masImp:= k
else
masImp:= 0;
end;
//Programa principal
var
Cant: TVC;
Imp: TVI;
cabina, N: byte;
begin
start(Cant, Imp);
lectura(Cant, Imp, cabina, N);
show(Cant, Imp, N);
writeln('La cabina que mas recaudo es la ', masImp(Imp, N));
writeln();
readln();
end.
|
unit REPWorldCanvas;
{$writeableconst on}
interface
uses
Classes, Console, Graphics, Windows, ShareTools;
type
TMoveDirection = (MD_DECREASE, MD_NONE, MD_INCREASE);
PGG_DArea = ^TGG_DArea;
TGG_DArea = record // Tento typ definuje obdélníkovou obálku geometrického elementu - jeho RANGE BLOCK.
minE : Double; // Minimální souřadnice v ose E.
maxE : Double; // Maximální souřadnice v ose E.
minN : Double; // Minimální souřadnice v ose N.
maxN : Double; // Maximální souřadnice v ose N.
end;
PGG_SArea = ^TGG_SArea;
TGG_SArea = record // Tento typ definuje obdélníkovou obálku geometrického elementu - jeho RANGE BLOCK.
minE : Single; // Minimální souřadnice v ose E.
maxE : Single; // Maximální souřadnice v ose E.
minN : Single; // Minimální souřadnice v ose N.
maxN : Single; // Maximální souřadnice v ose N.
end;
TGG_GeodeticSystem = class
end;
TREPWorldCanvas = class
private
__CallSetDynamics : boolean;
fLeft : LongInt;
fTop : LongInt;
fGeodeticSystem : TGG_GeodeticSystem;
fMaxScale : Double;
FOriginE : Double; // left edge coordinate in projected meters
FOriginN : Double; // top edge coordinate in projected meters
FWUperRPelE : Double; // horizontal size of Canvas pixel in projected meters
FWUperRPelN : Double; // vertical size of Canvas pixel in projected meters
FEPixels : LongInt; // number of valid pixels in E-axis, can be under zero
FNPixels : LongInt; // number of valid pixels in N-axis, it can be under zero
FMaxE : Double; // calculated from FOriginE
FMinN : Double; // calculated from FOriginN
fCanvas : TCanvas;
fOnChange : TNotifyEvent;
_CallOnChangeCalled : boolean;
procedure SetOriginE(NewValue : Double);
procedure SetOriginN(NewValue : Double);
procedure SetEPixels(NewValue : LongInt);
procedure SetNPixels(NewValue : LongInt);
function GetMBR : TGG_DArea;
function GetMinN : Double;
function GetMaxE : Double;
procedure StopCallOnChange;
procedure StartCallOnChange;
public
property OnChange : TNotifyEvent read fOnChange write fOnChange;
property Canvas : TCanvas read fCanvas write fCanvas;
property OriginE : Double read FOriginE write SetOriginE; // canvas origin N coordinate
property OriginN : Double read FOriginN write SetOriginN; // canvas origin N coordinat
property MaxScale : Double read fMaxScale write fMaxScale;
property WUperRPelE : Double read FWUperRPelE write fWUperRPelE; // width resolution in working units
property WUperRPelN : Double read FWUperRPelN write fWUperRPelN; // height resolution in working units
property EPixels : LongInt read FEPixels write SetEPixels; // width of canvas in pixels
property NPixels : LongInt read FNPixels write SetNPixels; // height of canvas in pixels
property MinE : Double read FOriginE write SetOriginE; // MBR.MinE
property MaxN : Double read FOriginN write SetOriginN; // MBR.MaxN
property MinN : Double read GetMinN; // MBR.MinN
property MaxE : Double read GetMaxE; // MBR.MaxE
property Left : LongInt read fLeft write fLeft; // Use for print only !
property Top : LongInt read fTop write fTop; // Use for print only !
function WUfromEIndex(const EIndex : LongInt) : Double; // Returns world E coordinate from canvas column
function WUfromNIndex(const NIndex : LongInt) : Double; // Returns world N coordinate from canvas row
function NIndexFromWU(N : Double) : Int64; // Returns canvas row from N world coordinate
function EIndexFromWU(E : Double) : Int64; // Returns canvas column from E world coordinate
function sNIndexFromWU(N : Double) : Int64; // Returns canvas row from N world coordinate
function sEIndexFromWU(E : Double) : Int64; // Returns canvas column from E world coordinate
procedure CallOnChange;
property MBR : TGG_DArea read GetMBR;
function GetDrawHeight : LongInt;
function GetDrawWidth : LongInt;
constructor Create; // initializa instance
property GeodeticSystem : TGG_GeodeticSystem read fGeodeticSystem write fGeodeticSystem; // Declared for use in future
procedure NewCenter(const AboutE, AboutN: integer); overload; // Set center of canvas to point (AboutE, AboutN), scale is the same
procedure NewCenter(const AboutE, AboutN: Double); overload;
procedure NewCenter(const AboutE, AboutN: Double; aGeoSystem : TGG_GeodeticSystem); overload;
procedure ZoomIn(const AboutE, AboutN: Double; aGeoSystem : TGG_GeodeticSystem); overload; // Zoom in canvas around point (AboutE, AboutN), Scale := Scale * 2
procedure ZoomOut(const AboutE, AboutN: Double; aGeoSystem : TGG_GeodeticSystem); overload; // Zoom out canvas around point (AboutE, AboutN), Scale := Scale / 2
procedure ViewArea(Source : TGG_DArea; aGeoSystem : TGG_GeodeticSystem = nil); overload;
procedure ViewArea(UserMinE, UserMinN, UserMaxE, UserMaxN : Double; aGeoSystem : TGG_GeodeticSystem = nil); overload;
procedure ZoomAroundXY(const AboutX, AboutY : integer; ScaleMult: Double);
procedure ZoomIn; overload; // Zoom in canvas around point (AboutE, AboutN), Scale := Scale * 2
procedure ZoomIn(const AboutE, AboutN: integer); overload; // Zoom in canvas around point (AboutE, AboutN), Scale := Scale * 2
procedure ZoomIn(const AboutE, AboutN: Double); overload; // Zoom in canvas around point (AboutE, AboutN), Scale := Scale * 2
procedure ZoomInXY(const x, y : integer); // Zoom in canvas around point (AboutE, AboutN), Scale := Scale * 2
procedure ZoomOut; overload; // Zoom out canvas around point (AboutE, AboutN), Scale := Scale / 2
procedure ZoomOut(const AboutE, AboutN: integer); overload; // Zoom out canvas around point (AboutE, AboutN), Scale := Scale / 2
procedure ZoomOut(const AboutE, AboutN: Double); overload; // Zoom out canvas around point (AboutE, AboutN), Scale := Scale / 2
procedure Move(MoveE, MoveN : TMoveDirection; Overlap : Double = 0.9);
procedure ViewAreaXY(UserMinE, UserMinN, UserMaxE, UserMaxN : integer);
procedure SetScale(aScale : Double);
procedure CheckMaxScale(aMaxScale : Double);
function Scale : Double;
procedure Assign(Source : TREPWorldCanvas); // Copy settings from source
function IsInside(const E, N : Double) : Boolean; // Returns true, if point (E, N) is inside canvas
function IsMBRVisible(const RMinE, RMinN, RMaxE, RMaxN : Double) : boolean; overload; // Returns true, if rectangle defined by parameters is inside canvas
function IsMBRVisible(const MBR : TGG_DArea) : boolean; overload; // Returns true, if rectangle MBR is inside canvas
function WUtoPels(Value : Double) : Double; // Returns world distance Value in canvas pixel units
function AWUtoPels(Value : Double) : Double; // Returns world distance Value in canvas pixel units
function PelsToWU(Value : Double) : Double;
function dEtoWidth(dE : Double) : integer;
function dNtoHeight(dN : Double) : integer;
procedure LowLevel_SetSize(SizeE, SizeN : integer);
(*
GetGeodeticSystemByWorldViewProc : TGetGeodeticSystemByWorldView;
WasDrawToCanvasInterrupted : boolean;
procedure DrawMGRSLayout(l : TLayoutItem);
procedure SaveToIniFile(Section, Prefix : string; IniFile : TNonCzechIniFile); // Save parameters to specified IniFile
procedure LoadFromIniFile(Section, Prefix : string; IniFile : TNonCzechIniFile); // Load parameters from specified IniFile
procedure CenterBLWGS(var BWGSrad, LWGSrad : Double);
procedure DrawLongitude(MinBdeg, MaxBdeg, Ldeg : Double);
procedure DrawLatitude(MinLdeg, MaxLdeg, Bdeg : Double);
procedure DrawMGRSGridStrip(var llMGRSSquare : string; BorderWidthMM, StepM : Double; MinLdeg, CenterLdeg, MaxLdeg : Double); overload;
procedure DrawMGRSGridStrip(var llMGRSSquare : string; BorderWidthMM, StepM, MinLdeg, CenterLdeg, MaxLdeg, aMinE, aMinN, aMaxE, aMaxN : Double); overload;
procedure DrawMGRSGrid(var StripsLabel, llMGRSSquare : string; MBR : TGG_DArea; BorderWidthMM : Double; StepM : Double = 0);
procedure LatLonToMouseXY(LatDeg, LonDeg : Double; var x, y : integer);
function BuildXML : string;
*)
end;
TWordCanvasList = class(TList)
private
function GetWorldCanvas(i : integer) : TREPWorldCanvas;
public
property WorldCanvas[i : integer] : TREPWorldCanvas read GetWorldCanvas; default;
procedure Add(Item : TREPWorldCanvas);
procedure RedrawAll;
end;
TWorldCanvasProcObject = procedure(wc : TREPWorldCanvas) of object;
TWorldCanvasProc = procedure(wc : TREPWorldCanvas);
// *****************************************************************************
// PRIVATE GLOBALS
const
__StopCallOnChange : boolean = false;
// *****************************************************************************
function IsInside(MBR : TGG_DArea; E, N : Double) : boolean; overload;
function IsInside(MinE, MinN, MaxE, MaxN : Double; E, N : Double) : boolean; overload;
procedure DoForEachWorldCanvas(Proc : TWorldCanvasProcObject); overload;
procedure DoForEachWorldCanvas(Proc : TWorldCanvasProc); overload;
function WordCanvasList : TWordCanvasList;
implementation
const
_WordCanvasList : TWordCanvasList = nil;
function WordCanvasList : TWordCanvasList;
begin
if _WordCanvasList = nil then _WordCanvasList := TWordCanvasList.Create;
Result := _WordCanvasList;
end;
procedure DoForEachWorldCanvas(Proc : TWorldCanvasProcObject);
var
i : integer;
wc : TREPWorldCanvas;
begin
if Assigned(Proc) then
for i := 0 to WordCanvasList.Count - 1 do begin
wc := WordCanvasList.Items[i];
Proc(wc);
end;
end;
procedure DoForEachWorldCanvas(Proc : TWorldCanvasProc);
var
i : integer;
wc : TREPWorldCanvas;
begin
if Assigned(Proc) then
for i := 0 to WordCanvasList.Count - 1 do begin
wc := WordCanvasList.Items[i];
Proc(wc);
end;
end;
function IsInside(MinE, MinN, MaxE, MaxN : Double; E, N : Double) : boolean;
begin
SortDouble(MinE, MaxE);
SortDouble(MinN, MaxN);
Result := (E >= MinE) and (E <= MaxE) and (N >= MinN) and (N <= MaxN);
end;
function IsInside(MBR : TGG_DArea; E, N : Double) : boolean;
begin
with MBR do Result := IsInside(MinE, MinN, MaxE, MaxN, E, N);
end;
function StretchLongToInt(Value : LongInt) : SmallInt;
{
Tato funkce vrací hodnotu Value převedenou do intervalu <-32768,32767>.
%MAYBETTER:
Tato funkce pracuje pomocí podmínek. Použitím bitové aritmetiky bychom
dosáhli rychlejšího běhu.
}
begin
if Value < -32768 then Result := -32768
else if Value > 32767 then Result := 32767
else Result := Value;
end;
// *****************************************************************************
// TWordCanvasList
// *****************************************************************************
procedure TWordCanvasList.RedrawAll;
var
i : integer;
begin
{ TODO : dodelat }
{
for i := 0 to Count - 1 do
WorldCanvas[i].Draw(nil);
}
end;
procedure TWordCanvasList.Add(Item : TREPWorldCanvas);
begin
inherited Add(Item);
end;
function TWordCanvasList.GetWorldCanvas(i : integer) : TREPWorldCanvas;
begin
Result := Pointer(Items[i]);
end;
// *****************************************************************************
// TREPWorldCanvas
// *****************************************************************************
procedure TREPWorldCanvas.SetOriginE;
{
Tato metoda nastaví levou hranu pohledu na souřadnici NewValue tak, že celý
pohled posune.
}
begin
FOriginE := NewValue;
FMaxE := NewValue + EPixels*WUperRPelE;
CallOnChange;
end;
procedure TREPWorldCanvas.SetOriginN;
{
Tato metoda nastaví horní hranu pohledu na souřadnici NewValue tak, že celý
pohled posune.
}
begin
FOriginN := NewValue;
FMinN := NewValue + NPixels*WUperRPelN;
CallOnChange;
end;
procedure TREPWorldCanvas.SetNPixels;
{
Tato metoda nastaví novou výšku pohledu v pixelech.
Origin pohledu zůstane nezměněn.
}
begin
FNPixels := NewValue;
FMinN := OriginN + NPixels*WUperRPelN;
CallOnChange;
end;
function TREPWorldCanvas.WUfromEIndex;
{
Tato metoda vrací souřadnici pixelu EIndex převedenou na metry.
}
begin
{$O-}
Result := OriginE + (EIndex - fLeft)*WUPerRPelE;
end;
function TREPWorldCanvas.WUfromNIndex;
{
Tato metoda vrací souřadnici pixelu NIndex převedenou na metry.
}
begin
{$O-}
Result := OriginN + (NIndex - fTop)*WUPerRPelN;
end;
function TREPWorldCanvas.NIndexFromWU;
// Tato funkce vrací souřadnici N v metrech převedenou na pixely.
var
Pom : Double;
begin
{$O-}
Pom := (N-fOriginN)/fWUperRPelN;
if Pom > 9223372036854775807 then Pom := 9223372036854775807;
if Pom < -9223372036854775807 then Pom := -9223372036854775807;
NIndexFromWU := fTop + Trunc(Pom);
end;
function TREPWorldCanvas.EIndexfromWU;
// Tato funkce vrací souřadnici E v metrech převedenou na pixely.
var
Pom : Double;
begin
{$O-}
Pom := (E-fOriginE)/fWUperRPelE;
if Pom > 9223372036854775807 then Pom := 9223372036854775807;
if Pom < -9223372036854775807 then Pom := -9223372036854775807;
EIndexfromWU := fLeft + Trunc(Pom);
end;
function TREPWorldCanvas.sNIndexFromWU;
begin
Result := StretchLongToInt(NIndexFromWU(N));
end;
function TREPWorldCanvas.sEIndexfromWU;
begin
Result := StretchLongToInt(EIndexFromWU(E));
end;
procedure TREPWorldCanvas.SetEPixels;
{
Tato metoda nastaví novou šířku pohledu v pixelech.
Origin pohledu zůstane nezměněn.
}
begin
FEPixels := NewValue;
FMaxE := OriginE + EPixels*WUperRPelE;
CallOnChange;
end;
function TREPWorldCanvas.GetMinN : Double;
begin
Result := FOriginN + NPixels*WUperRPelN;
end;
function TREPWorldCanvas.GetMaxE : Double;
begin
Result := FOriginE + EPixels*WUperRPelE;
end;
procedure TREPWorldCanvas.StopCallOnChange;
begin
Console.DisplayMsg('StopCallOnChange', cic_DetailDebug);
if __StopCallOnChange then Exit;
_CallOnChangeCalled := false;
__StopCallOnChange := true;
end;
procedure TREPWorldCanvas.StartCallOnChange;
begin
Console.DisplayMsg('StartCallOnChange', cic_DetailDebug);
__StopCallOnChange := false;
if _CallOnChangeCalled then CallOnChange;
end;
procedure TREPWorldCanvas.CallOnChange;
begin
{ TODO : doplnit kod }
end;
procedure TREPWorldCanvas.CheckMaxScale(aMaxScale : Double);
var
s, k : Double;
begin
if aMaxScale = 0 then Exit;
{ TODO : doplnit kod }
(*
s := Scale;
if s > aMaxScale then begin
k := aMaxScale/(1.01*s);
FWUperRPelE := k*FWUperRPelE;
FWUperRPelN := k*FWUperRPelN;
s := Scale;
end;
*)
end;
procedure TREPWorldCanvas.ZoomOut(const AboutE, AboutN: Double; aGeoSystem : TGG_GeodeticSystem);
var
e, n : Double;
begin
// aGeoSystem.ConvertStoreCoorsToGS(GeodeticSystem, AboutE, AboutN, e, n); { TODO : doplnit kod }
ZoomOut(e, n);
end;
procedure TREPWorldCanvas.ViewAreaXY(UserMinE, UserMinN, UserMaxE, UserMaxN : integer);
begin
ViewArea(WUfromEIndex(UserMinE), WUfromNIndex(UserMinN), WUfromEIndex(UserMaxE), WUfromNIndex(UserMaxN));
end;
procedure TREPWorldCanvas.ViewArea(
UserMinE, UserMinN, UserMaxE, UserMaxN : Double;
aGeoSystem : TGG_GeodeticSystem
);
{
Tato metoda nastaví pohled tak, aby byl vidět celý obdélník
UserMinE, UserMinN, UserMaxE, UserMaxN. Hodnota měřítka bude
přizpůsobena.
}
var
hMinE, hMinN, hMaxE, hMaxN : Double;
PomDouble : Double;
dE, dN : DOuble;
PredStopCallOnChange : boolean;
begin
if aGeoSystem = nil then begin
PredStopCallOnChange := __StopCallOnChange;
try
__StopCallOnChange := true;
dE := Abs(UserMinE - UserMaxE);
dN := Abs(UserMinN - UserMaxN);
if (dE <> 0) and (dN <> 0) then begin
if UserMinE > UserMaxE then begin
PomDouble := UserMinE;
UserMinE := UserMaxE;
UserMaxE := PomDouble;
end;
if UserMinN > UserMaxN then begin
PomDouble := UserMinN;
UserMinN := UserMaxN;
UserMaxN := PomDouble;
end;
if NPixels/dN < EPixels/dE then begin { shodna se zadanou bude svisla hrana }
WUPerRPelN := (UserMinN - UserMaxN)/NPixels;
WUPerRPelE := -WUPerRPelN;
end
else begin { shodna se zadanou bude vodorovna hrana }
WUPerRPelE := (UserMaxE - UserMinE)/EPixels;
WUPerRPelN := -WUPerRPelE;
end;
CheckMaxScale(MaxScale);
OriginN := UserMaxN;
OriginE := UserMinE;
NewCenter((UserMinE + UserMaxE)/2, (UserMinN + UserMaxN)/2);
end;
finally
__StopCallOnChange := PredStopCallOnChange;
CallOnChange;
end;
end
else begin
{ TODO : doplnit kod }
{
aGeoSystem.ConvertStoreCoorsToGS(GeodeticSystem, UserMinE, UserMinN, hMinE, hMinN);
aGeoSystem.ConvertStoreCoorsToGS(GeodeticSystem, UserMaxE, UserMaxN, hMaxE, hMaxN);
}
ViewArea(hMinE, hMinN, hMaxE, hMaxN, nil);
end;
end;
procedure TREPWorldCanvas.ViewArea(Source : TGG_DArea; aGeoSystem : TGG_GeodeticSystem = nil);
begin
with Source do
ViewArea(MinE, MinN, MaxE, MaxN, aGeoSystem);
end;
procedure TREPWorldCanvas.Move(MoveE, MoveN : TMoveDirection; Overlap : Double = 0.9);
var
dE, dN : Double;
NewE, NewN : Double;
PredStopCallOnChange : boolean;
begin
PredStopCallOnChange := __StopCallOnChange;
try
__StopCallOnChange := true;
dE := Overlap * (MaxE - MinE);
dN := Overlap * (MaxN - MinN);
NewE := (MaxE + MinE) / 2;
NewN := (MaxN + MinN) / 2;
if MoveE = MD_DECREASE then NewE := NewE - dE;
if MoveE = MD_INCREASE then NewE := NewE + dE;
if MoveN = MD_DECREASE then NewN := NewN - dN;
if MoveN = MD_INCREASE then NewN := NewN + dN;
NewCenter(NewE, NewN);
finally
__StopCallOnChange := PredStopCallOnChange;
CallOnChange;
end;
end;
procedure TREPWorldCanvas.SetScale(aScale : Double);
var
E, N, ZoomValue : Double;
PredStopCallOnChange : boolean;
begin
ZoomValue := Scale/aScale;
PredStopCallOnChange := __StopCallOnChange;
try
__StopCallOnChange := true;
E := (MaxE + MinE)/2;
N := (MaxN + MinN)/2;
WUPerRPelE := WUPerRPelE / ZoomValue;
WUPerRPelN := WUPerRPelN / ZoomValue;
OriginE := E - WUPerRPelE*EPixels/2;
OriginN := N - WUPerRPelN*NPixels/2;
finally
__StopCallOnChange := PredStopCallOnChange;
CallOnChange;
end;
end;
function TREPWorldCanvas.Scale : Double;
{
This procedure calculates scale of CanvasDef in aGeoSystem.
It is done in MBRGeoSystem according to the vertical size of MBR. So, result is Geodetic system independent.
}
var
aMBR : TGG_DArea;
HeightMM, HeightPx, d : Double;
begin
aMBR := GetMBR;
// ProjectMBRToGS(GeodeticSystem, MBRGeoSystem, aMBR); { TODO : doplnit kod }
if (Canvas = nil) or (not Canvas.HandleAllocated) then begin
HeightMM := 0.25;
HeightPx := 1;
end
else begin
HeightMM := GetDeviceCaps(Canvas.Handle, VERTSIZE);
HeightPx := GetDeviceCaps(Canvas.Handle, VERTRES);
end;
d := FNPixels * HeightMM;
if d <> 0
then //Result := HeightPx*StandardMeridianArcToM(aMBR.MaxN - aMBR.MinN)*1000/d { TODO : doplnit kod }
else begin
Console.DisplayErrorMsg('Scale delimeter smaller is zero');
Result := 1;
end;
end;
procedure TREPWorldCanvas.Assign(Source : TREPWorldCanvas);
{
Tato metoda kopíruje hodnoty objektu Source, přičemž kontroluje,
jestli je Source platným objektem.
}
var
PredStopCallOnChange : boolean;
begin
if Assigned(Source) then begin
PredStopCallOnChange := __StopCallOnChange;
try
__StopCallOnChange := true;
FOriginE := Source.FOriginE;
FOriginN := Source.FOriginN;
FWUperRPelE := Source.FWUperRPelE;
FWUperRPelN := Source.FWUperRPelN;
FEPixels := Source.FEPixels;
FNPixels := Source.FNPixels;
FMaxE := Source.FMaxE;
FMinN := Source.FMinN;
//fGeodeticSystem.AsString := Source.GeodeticSystem.AsString; { TODO : doplnit kod }
finally
__StopCallOnChange := PredStopCallOnChange;
CallOnChange;
end;
end;
end;
function TREPWorldCanvas.IsInside(const E, N : Double) : Boolean;
{
Tato metoda vrací TRUE, jestliže je bod (E,N) v pohledu vidět.
}
begin
Result := REPWorldCanvas.IsInside(MinE, MinN, MaxE, MaxN, E, N);
end;
function TREPWorldCanvas.IsMBRVisible(const RMinE, RMinN, RMaxE, RMaxN : Double) : boolean;
{
Tato metoda vrací TRUE, jestliže je alespoň část obdélníku
RMinE, RMinN, RMaxE, RMaxN v pohledu vidět.
}
begin
Result := not (
(((MINE < RMinE) and (MAXE < RMinE)) or ((MINE > RMaxE) and (MAXE > RMaxE))) or
(((MINN < RMinN) and (MAXN < RMinN)) or ((MINN > RMaxN) and (MAXN > RMaxN))) );
end;
function TREPWorldCanvas.WUtoPels(Value : Double) : Double;
begin
Result := Value / WUPerRPelN;
end;
function TREPWorldCanvas.AWUtoPels(Value : Double) : Double;
begin
Result := Abs(WUtoPels(Value));
end;
function TREPWorldCanvas.PelsToWU(Value : Double) : Double;
begin
Result := Abs(Value * WUPerRPelN);
end;
function TREPWorldCanvas.IsMBRVisible(const MBR : TGG_DArea) : boolean;
begin
{$O-}
Result := IsMBRVisible(MBR.MinE, MBR.MinN, MBR.MaxE, MBR.MaxN);
end;
function TREPWorldCanvas.dEtoWidth(dE : Double) : integer;
begin
Result := Round(dE / FWUperRPelE);
end;
function TREPWorldCanvas.dNtoHeight(dN : Double) : integer;
begin
Result := Round(dN / FWUperRPelN);
end;
procedure TREPWorldCanvas.LowLevel_SetSize(SizeE, SizeN : integer);
begin
fEPixels := SizeE;
fNPixels := SizeN;
CallOnChange;
end;
(*
const
FromHere : boolean = false;
var
B, L : Double;
WGSMBR : TGG_DArea;
NeedViewArea : boolean;
PrevScale : Double;
gs : TGG_GeodeticSystem;
begin
if FromHere then Exit;
FromHere := true;
try
_CallOnChangeCalled := true;
if __StopCallOnChange then Exit;
Console.DefConsole.OpenSection('TREPWorldCanvas.CallOnChange', CONSOLEINFOCLASS_DETAILDEBUG);
if Assigned(OnChangeCanvasDefs) then OnChangeCanvasDefs(Self);
NeedViewArea := false;
if Assigned(GeodeticSystem) then begin
Console.DefConsole.OpenSection('Assigning geodetic system', CONSOLEINFOCLASS_DETAILDEBUG);
WGSMBR := GetMBR;
ProjectMBRToGS(GeodeticSystem, MBRGeoSystem, WGSMBR);
GeodeticSystem.ConvertStoreCoorsToGS(MBRGeoSystem, (MinE + MaxE)/2, (MinN + MaxN)/2, L, B);
PrevScale := Scale;
NeedViewArea := GeodeticSystem.SetByWorldView((WGSMBR.MinN + WGSMBR.MaxN)/2, (WGSMBR.MinE + WGSMBR.MaxE)/2, PrevScale);
if Assigned(GetGeodeticSystemByWorldViewProc) then begin
gs := GetGeodeticSystemByWorldViewProc((WGSMBR.MinN + WGSMBR.MaxN)/2, (WGSMBR.MinE + WGSMBR.MaxE)/2, PrevScale);
NeedViewArea := gs <> nil;
if gs <> nil then GeodeticSystem.Assign(gs);
end;
if NeedViewArea then begin
AssignGeodeticSystemToEdits(GeodeticSystem);
with GeodeticSystem.StoreDef do begin
StoreGeographic := false;
ToMasterMult := 1;
end;
end;
Console.DefConsole.CloseSection('OK', CONSOLEINFOCLASS_DETAILDEBUG);
end;
try
__StopCallOnChange := true;
if __CallSetDynamics and Assigned(GeodeticSystem) and GeodeticSystem.Projection.HasDynamics then begin
try
__CallSetDynamics := false;
if GeodeticSystem.Projection.SetDynamicsByWGSArea(WGSMBR.MinE, WGSMBR.MinN, WGSMBR.MaxE, WGSMBR.MaxN) then NeedViewArea := true;
finally
__CallSetDynamics := true;
end;
end;
if NeedViewArea then begin
Console.DisplayMsg('NeedViewArea', CONSOLEINFOCLASS_DETAILDEBUG);
SetScale(PrevScale);
NewCenter(L, B, MBRGeoSystem);
end;
finally
__StopCallOnChange := false;
end;
Console.DisplayMsg('Calling fOnChange', CONSOLEINFOCLASS_DETAILDEBUG);
if Assigned(fOnChange) then fOnChange(Self);
Console.DisplayMsg('Calling OnAfterChangeCanvasDefs', CONSOLEINFOCLASS_DETAILDEBUG);
if Assigned(OnAfterChangeCanvasDefs) then OnAfterChangeCanvasDefs(Self);
{$ifndef PreviewInMapViewOnly}
{$ifndef NOGISFUNCTIONALITY}
LocationDiagramFrm.ShowPrimaryWorldCanvas(Self);
{$endif}
{$endif}
Console.DefConsole.CloseSection('OK', CONSOLEINFOCLASS_DETAILDEBUG);
finally
FromHere := false;
end;
end;
*)
function TREPWorldCanvas.GetMBR;
begin
Result.MinE := MinE;
Result.MinN := MinN;
Result.MaxE := MaxE;
Result.MaxN := MaxN;
end;
function TREPWorldCanvas.GetDrawHeight : LongInt;
begin
Result := NPixels - Top;
end;
function TREPWorldCanvas.GetDrawWidth : LongInt;
begin
Result := EPixels - Left;
end;
constructor TREPWorldCanvas.Create;
{
Tento konstruktor vyvolá konstruktor předka a nastaví následující hodnoty okna:
}
begin
{ OLD CODE
inherited Create;
__CallSetDynamics := true;
fLeft := 0;
fTop := 0;
OriginE := 3500000;
OriginN := 5500000;
FWUperRPelE := 1000;
FWUperRPelN := -1000;
EPixels := 10;
NPixels := 10;
fMaxScale := 0;
fGeodeticSystem := TGG_GeodeticSystem.Create;
fGeodeticSystem.StoreDef.StoreGeographic := false;
fGeodeticSystem.StoreDef.ToMasterMult := 1;
GetGeodeticSystemByWorldViewProc := nil;
**************** }
Console.DefConsole.OpenSection('TREPWorldCanvas.Create');
inherited Create;
__CallSetDynamics := true;
StopCallOnChange;
try
fLeft := 0;
fTop := 0;
OriginE := 15;
OriginN := 50;
FWUperRPelE := 0.1;
FWUperRPelN := -0.1;
EPixels := 100;
NPixels := 100;
fMaxScale := 0;
finally
StartCallOnChange;
end;
// fGeodeticSystem := TGG_GeodeticSystem.Create;
// fGeodeticSystem.Assign(MBRGeoSystem);
// fGeodeticSystem.StoreDef.ToMasterMult := 1;
// GetGeodeticSystemByWorldViewProc := nil;
Console.DefConsole.CloseSection;
end;
procedure TREPWorldCanvas.NewCenter(const AboutE, AboutN: Double; aGeoSystem : TGG_GeodeticSystem);
var
e, n : Double;
begin
// aGeoSystem.ConvertStoreCoorsToGS(GeodeticSystem, AboutE, AboutN, e, n); { TODO : doplnit kod }
NewCenter(e, n);
end;
procedure TREPWorldCanvas.NewCenter(const AboutE, AboutN: integer);
begin
NewCenter(WUfromEIndex(AboutE), WUfromNIndex(AboutN));
end;
procedure TREPWorldCanvas.NewCenter(const AboutE, AboutN: Double);
{
Tato metoda nastaví pohled tak, že bude mít střed v bodě AboutE, AboutN.
Velikost a zvětšení pohledu zůstane nezměněno.
}
var
PredStopCallOnChange : boolean;
begin
PredStopCallOnChange := __StopCallOnChange;
try
__StopCallOnChange := true;
OriginE := OriginE + AboutE - WUFromEIndex(EPixels div 2);
OriginN := OriginN + AboutN - WUFromNIndex(NPixels div 2);
finally
__StopCallOnChange := PredStopCallOnChange;
CallOnChange;
end;
end;
procedure TREPWorldCanvas.ZoomInXY(const x, y : integer); // Zoom in canvas around point (AboutE, AboutN), Scale := Scale * 2
begin
DisplayDLLMsg('TREPWorldCanvas.ZoomInXY(%d, %d)', [x, y]);
ZoomIn(x, y);
end;
procedure TREPWorldCanvas.ZoomIn(const AboutE, AboutN: Double; aGeoSystem : TGG_GeodeticSystem);
var
e, n : Double;
begin
// aGeoSystem.ConvertStoreCoorsToGS(GeodeticSystem, AboutE, AboutN, e, n); { TODO : doplnit kod }
ZoomIn(e, n);
end;
procedure TREPWorldCanvas.ZoomIn;
begin
ZoomIn((MaxE + MinE)/2, (MaxN + MinN)/2);
end;
procedure TREPWorldCanvas.ZoomIn(const AboutE, AboutN: integer);
begin
DisplayDLLMsg('TREPWorldCanvas.ZoomIn(%d, %d : integer)', [AboutE, AboutN]);
ZoomIn(WUfromEIndex(AboutE), WUfromNIndex(AboutN));
end;
procedure TREPWorldCanvas.ZoomAroundXY(const AboutX, AboutY : integer; ScaleMult: Double);
var
PredStopCallOnChange : boolean;
AboutE, AboutN : Double;
begin
if ScaleMult = 0 then Exit;
DisplayDLLMsg('TREPWorldCanvas.Zoom(%f, %f, %f : Double)', [AboutE, AboutN, ScaleMult]);
PredStopCallOnChange := __StopCallOnChange;
try
__StopCallOnChange := true;
AboutE := WUFromEIndex(AboutX);
AboutN := WUFromNIndex(AboutY);
WUPerRPelE := WUPerRPelE * ScaleMult;
WUPerRPelN := WUPerRPelN * ScaleMult;
OriginE := AboutE - AboutX*WUPerRPelE;
OriginN := AboutN - AboutY*WUPerRPelN;
DisplayDLLMsg('TREPWorldCanvas.Zoom Done.');
finally
__StopCallOnChange := PredStopCallOnChange;
CallOnChange;
end;
end;
procedure TREPWorldCanvas.ZoomIn(const AboutE, AboutN: Double);
{
Tato metoda nastaví pohled tak, že bude mít střed v bodě AboutE, AboutN a
měřítko bude dvakrát větší (zvětšení).
}
var
PredStopCallOnChange : boolean;
begin
DisplayDLLMsg('TREPWorldCanvas.ZoomIn(%f, %f : Double)', [AboutE, AboutN]);
PredStopCallOnChange := __StopCallOnChange;
try
__StopCallOnChange := true;
WUPerRPelE := WUPerRPelE / 2;
WUPerRPelN := WUPerRPelN / 2;
OriginE := AboutE - WUPerRPelE*EPixels/2;
OriginN := AboutN - WUPerRPelN*NPixels/2;
DisplayDLLMsg('TREPWorldCanvas.ZoomIn Done.');
finally
__StopCallOnChange := PredStopCallOnChange;
CallOnChange;
end;
end;
procedure TREPWorldCanvas.ZoomOut(const AboutE, AboutN: integer);
begin
ZoomOut(WUfromEIndex(AboutE), WUfromNIndex(AboutN));
end;
procedure TREPWorldCanvas.ZoomOut(const AboutE, AboutN: Double);
{
Tato metoda nastaví pohled tak, že bude mít střed v bodě AboutE, AboutN a
měřítko bude dvakrát menší (zmenšení).
}
var
PredStopCallOnChange : boolean;
begin
PredStopCallOnChange := __StopCallOnChange;
try
__StopCallOnChange := true;
WUPerRPelE := WUPerRPelE * 2;
WUPerRPelN := WUPerRPelN * 2;
CheckMaxScale(MaxScale);
OriginE := AboutE - WUPerRPelE*EPixels/2;
OriginN := AboutN - WUPerRPelN*NPixels/2;
finally
__StopCallOnChange := PredStopCallOnChange;
CallOnChange;
end;
end;
procedure TREPWorldCanvas.ZoomOut;
begin
ZoomOut((MaxE + MinE)/2, (MaxN + MinN)/2);
end;
(*
type
TPointClass = class
x, y : integer;
end;
function TREPWorldCanvas.BuildXML : string;
begin
Result := BuildXMLTag(ClassName,
GeodeticSystem.BuildXML +
BuildXMLTag('RangeBlock',
BuildXMLTag('MinE', MinE) +
BuildXMLTag('MinN', MinN) +
BuildXMLTag('MaxE', MaxE) +
BuildXMLTag('MaxN', MaxN)
) +
BuildXMLTag('Window properties',
BuildXMLTag('OriginE', OriginE) +
BuildXMLTag('OriginN', OriginN) +
BuildXMLTag('Left', Left) +
BuildXMLTag('Top', Top) +
BuildXMLTag('MaxScale', MaxScale) +
BuildXMLTag('WUperRPelE', WUperRPelE) +
BuildXMLTag('WUperRPelN', WUperRPelN) +
BuildXMLTag('EPixels', EPixels) +
BuildXMLTag('NPixels', NPixels)
)
);
end;
procedure TREPWorldCanvas.LatLonToMouseXY(LatDeg, LonDeg : Double; var x, y : integer);
var
E, N : Double;
begin
MBRGeoSystem.ConvertStoreCoorsToGS(GeodeticSystem, LonDeg, LatDeg, E, N);
x := EIndexFromWU(E);
y := NIndexFromWU(N);
end;
procedure TREPWorldCanvas.DrawMGRSLayout(l : TLayoutItem);
var
ItemMBR : TGG_DArea;
begin
l.Layout.PrinterPage.wt_PaperToWorld(l.AbsRect.minX, l.AbsRect.MinY, ItemMBR.MinE, ItemMBR.MaxN);
l.Layout.PrinterPage.wt_PaperToWorld(l.AbsRect.maxX, l.AbsRect.MaxY, ItemMBR.MaxE, ItemMBR.MinN);
MGRSDisplayRec.GridColor := l.GetGridColor;
MGRSDisplayRec.TickColor := l.GetPenColor;
DrawMGRSGrid(l.Layout.StripsLabel, l.Layout.MGRSSquare, ItemMBR, l.GridRec.TickLen, 0);
end;
procedure TREPWorldCanvas.DrawLatitude(MinLdeg, MaxLdeg, Bdeg : Double);
var
LatLonEdge : TLatLonPointArray;
ScreenArray : TPointVarArray;
begin
LatLonEdge := StrokeLatitude(Bdeg, MinLdeg, MaxLDeg, 0.1);
LatLonArray_to_Screen(LatLonEdge, Self, ScreenArray);
with Canvas.Pen do begin
Mode := pmCopy;
Style := psDot;
Color := clRed;
Width := 3;
end;
Canvas.Polyline(ScreenArray);
end;
procedure TREPWorldCanvas.DrawLongitude(MinBdeg, MaxBdeg, Ldeg : Double);
var
l : TObjectList;
procedure AddPoint(x, y, Index : integer);
var
Item : TPointClass;
begin
Item := TPointClass.Create;
Item.x := x;
Item.y := y;
l.Insert(Index, Item);
end;
procedure StrokeEdge(
MinX, MinY, MaxX, MaxY : integer;
MinBrad, MaxBrad : Double;
Index : integer
);
begin
end;
var
MinBrad, MaxBrad, Lrad : Double;
MinX, MinY, MaxX, MaxY : integer;
E, N : Double;
Edge : TPointVarArray;
i : integer;
begin
MinBrad := DegToRad(MinBdeg);
MaxBrad := DegToRad(MaxBdeg);
Lrad := DegToRad(Ldeg);
l := TObjectList.Create;
try
MBRGeoSystem.ConvertStoreCoorsToGS(GeodeticSystem, Ldeg, MinBdeg, E, N);
MinX := EIndexFromWU(E); MinY := NIndexFromWU(N);
MBRGeoSystem.ConvertStoreCoorsToGS(GeodeticSystem, Ldeg, MaxBdeg, E, N);
MaxX := EIndexFromWU(E); MaxY := NIndexFromWU(N);
AddPoint(MinX, MinY, 0);
AddPoint(MaxX, MaxY, 1);
SetLength(Edge, l.Count);
for i := 0 to l.Count - 1 do begin
Edge[i].x := TPointClass(l.Items[i]).x;
Edge[i].y := TPointClass(l.Items[i]).y;
end;
with Canvas.Pen do begin
Mode := pmCopy;
Style := psDot;
Color := clRed;
Width := 3;
end;
Canvas.Polyline(Edge);
finally
l.Free;
end;
end;
procedure TREPWorldCanvas.CenterBLWGS(var BWGSrad, LWGSrad : Double);
begin
GeodeticSystem.ConvertStoreCoorsToGS(
MBRGeoSystem,
(mbr.maxE + mbr.minE)/2, (mbr.maxN + mbr.minN)/2,
LWGSrad, BWGSrad
);
BWGSrad := DegToRad(BWGSrad);
LWGSrad := DegToRad(LWGSrad);
end;
procedure TREPWorldCanvas.SaveToIniFile;
begin
IniFile.WriteDouble(Section, Prefix + ORIGINE_ITEM, FOriginE, 0);
IniFile.WriteDouble(Section, Prefix + ORIGINN_ITEM, FOriginN, 0);
IniFile.WriteDouble(Section, Prefix + WUPERRPELE_ITEM, FWUperRPelE, 1);
IniFile.WriteDouble(Section, Prefix + WUPERRPELN_ITEM, FWUperRPelN, 1);
if Assigned(fGeodeticSystem) then
fGeodeticSystem.SaveToIniFile(Section, GEOSYSTEM_PREFIX, IniFile);
end;
procedure TREPWorldCanvas.LoadFromIniFile;
var
PredStopCallOnChange : boolean;
begin
PredStopCallOnChange := __StopCallOnChange;
try
__StopCallOnChange := true;
OriginE := IniFile.ReadDouble(Section, Prefix + ORIGINE_ITEM, 0);
OriginN := IniFile.ReadDouble(Section, Prefix + ORIGINN_ITEM, 0);
WUperRPelE := IniFile.ReadDouble(Section, Prefix + WUPERRPELE_ITEM, 1);
WUperRPelN := IniFile.ReadDouble(Section, Prefix + WUPERRPELN_ITEM, 1);
if Assigned(fGeodeticSystem) then
fGeodeticSystem.LoadFromIniFile(Section, GEOSYSTEM_PREFIX, IniFile);
finally
__StopCallOnChange := PredStopCallOnChange;
CallOnChange;
end;
end;
*)
initialization
finalization
_WordCanvasList.Free;
end.
|
unit TestPhisicsControllerUnit;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, PhisicsControllerUnit, ControllersUnit, System.Generics.Collections;
type
// Test methods for class PhisicsController
TestPhisicsController = class(TTestCase)
strict private
FPhisicsController: Controllers;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestGetListAnswer;
procedure TestGetQuestCaption;
procedure TestSetTest;
procedure TestGetMenu;
procedure TestGetCorrect;
end;
implementation
procedure TestPhisicsController.SetUp;
begin
FPhisicsController := PhisicsController.Create;
//FPhisicsController.setTest('Test2');
end;
procedure TestPhisicsController.TearDown;
begin
//FPhisicsController.Free;
FPhisicsController := nil;
end;
procedure TestPhisicsController.TestGetCorrect;
var
ReturnValue1: TDictionary<integer, integer>;
begin
FPhisicsController.setTest('Движение с постоянным ускорением');
ReturnValue1:=FPhisicsController.getCorrect;
CheckEquals(ReturnValue1.Items[1], 1);
CheckEquals(ReturnValue1.Items[2], 2);
CheckNotEquals(ReturnValue1.Items[2], 1);
end;
procedure TestPhisicsController.TestGetListAnswer;
var
ReturnValue1: TList<string>;
begin
FPhisicsController.setTest('Движение с постоянным ускорением');
ReturnValue1:=FPhisicsController.getAnswer;
CheckEquals(ReturnValue1.Items[0],
'абстрактный объект (модель), не имеющий размеров, но обладающий другими характеристиками');
CheckNotEquals(ReturnValue1.Items[0], 'ууууу');
CheckNotEquals(ReturnValue1.Items[1], 'nnnnnnnn');
CheckEquals(ReturnValue1.Count, 10);
CheckNotEquals(ReturnValue1.Count, 3);
end;
procedure TestPhisicsController.TestGetQuestCaption;
var
ReturnValue:TList<string>;
begin
FPhisicsController.setTest('Движение с постоянным ускорением');
ReturnValue:=FPhisicsController.getQuest;
CheckEquals(ReturnValue.Items[0], 'Дайте определение материальной точки.');
CheckNotEquals(ReturnValue.Items[0], '');
end;
procedure TestPhisicsController.TestSetTest;
var
caption:string;
ReturnValue1: TList<string>;
ReturnValue2: TList<string>;
begin
FPhisicsController.setTest('Движение с постоянным ускорением');
caption:='Test2';
ReturnValue1:=FPhisicsController.getQuest;
CheckEquals(ReturnValue1.Items[0], 'Дайте определение материальной точки.');
CheckNotEquals(ReturnValue1.Items[0], 'Как определяется положение материальной точки?');
ReturnValue2:=FPhisicsController.getQuest;
CheckEquals(ReturnValue2.Items[1], 'Как определяется положение материальной точки?');
CheckNotEquals(ReturnValue2.Items[1], 'Дайте определение материальной точки.');
CheckNotEquals(ReturnValue1.Items[0], ReturnValue2.Items[1]);
end;
procedure TestPhisicsController.TestGetMenu;
var
ReturnValue:TList<string>;
begin
ReturnValue:=FPhisicsController.getMenu;
CheckEquals(ReturnValue.Items[0],'Движение с постоянным ускорением');
CheckEquals(ReturnValue.Count,1);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestPhisicsController.Suite);
end.
|
{
Created by BGRA Controls Team
Dibo, Circular, lainz (007) and contributors.
For detailed information see readme.txt
Site: https://sourceforge.net/p/bgra-controls/
Wiki: http://wiki.lazarus.freepascal.org/BGRAControls
Forum: http://forum.lazarus.freepascal.org/index.php/board,46.0.html
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your 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 Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit BCImageButton;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, LResources, LMessages, ExtCtrls,
Types,
{ BGRAControls }
BCBaseCtrls, BCEffect,
{ BGRABitmap }
BGRABitmap, BGRABitmapTypes, BGRASliceScaling;
{off $DEFINE DEBUG}
function CalculateAspectRatioH(W1, H1, W2: integer): integer; //result H2
function CalculateAspectRatioW(W1, H1, H2: integer): integer; //result W2
function CalculateDestRect(ImageW, ImageH, DestW, DestH: integer;
Stretch, Proportional, Center: boolean): TRect;
procedure AssignFontToBGRA(Source: TFont; Dest: TBGRABitmap);
type
TBCGraphicButtonState = (gbsNormal, gbsHover, gbsActive, gbsDisabled);
TOnRenderControl = procedure(Sender: TObject; Bitmap: TBGRABitmap;
State: TBCGraphicButtonState) of object;
type
{ TBCGraphicButton }
TBCGraphicButton = class(TBCGraphicControl)
protected
FState: TBCGraphicButtonState;
FModalResult: TModalResult;
protected
procedure DoClick; virtual;
procedure DoMouseDown; virtual;
procedure DoMouseUp; virtual;
procedure DoMouseEnter; virtual;
procedure DoMouseLeave; virtual;
protected
procedure Click; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override;
procedure MouseEnter; override;
procedure MouseLeave; override;
public
property ModalResult: TModalResult
read FModalResult write FModalResult default mrNone;
end;
{ TBCXButton }
TBCXButton = class(TBCGraphicButton)
protected
FOnRenderControl: TOnRenderControl;
FBGRANormal, FBGRAHover, FBGRAActive, FBGRADisabled: TBGRABitmap;
protected
class function GetControlClassDefaultSize: TSize; override;
procedure DrawControl; override;
procedure RenderControl; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property OnRenderControl: TOnRenderControl
read FOnRenderControl write FOnRenderControl;
published
property Action;
property Align;
property Anchors;
property AutoSize;
property BidiMode;
property BorderSpacing;
property Caption;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property ParentBidiMode;
property ModalResult;
property OnChangeBounds;
property OnClick;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnResize;
property OnStartDrag;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
end;
{ TBCSliceScalingOptions }
TBCCustomSliceScalingOptions = class(TPersistent)
protected
FOwner: TControl;
FBitmap: TBGRABitmap;
FAutoDetectRepeat, FRepeatTop, FRepeatLeft, FRepeatMiddleHorizontal,
FRepeatMiddleVertical, FRepeatRight, FRepeatBottom: boolean;
FMarginTop, FMarginRight, FMarginBottom, FMarginLeft, FNumberOfItems: integer;
FDirection: TSliceScalingDirection;
FDrawMode: TDrawMode;
FResampleMode: TResampleMode;
FResampleFilter: TResampleFilter;
private
procedure SetFBitmap(AValue: TBGRABitmap);
procedure SetFMarginBottom(AValue: integer);
procedure SetFMarginLeft(AValue: integer);
procedure SetFMarginRight(AValue: integer);
procedure SetFMarginTop(AValue: integer);
procedure SetFAutoDetectRepeat(AValue: boolean);
procedure SetFDirection(AValue: TSliceScalingDirection);
procedure SetFDrawMode(AValue: TDrawMode);
procedure SetFNumberOfItems(AValue: integer);
procedure SetFRepeatBottom(AValue: boolean);
procedure SetFRepeatLeft(AValue: boolean);
procedure SetFRepeatMiddleHorizontal(AValue: boolean);
procedure SetFRepeatMiddleVertical(AValue: boolean);
procedure SetFRepeatRight(AValue: boolean);
procedure SetFRepeatTop(AValue: boolean);
procedure SetFResampleFilter(AValue: TResampleFilter);
procedure SetFResampleMode(AValue: TResampleMode);
public
constructor Create(AOwner: TControl);
destructor Destroy; override;
published
property Bitmap: TBGRABitmap read FBitmap write SetFBitmap;
property AutoDetectRepeat: boolean read FAutoDetectRepeat
write SetFAutoDetectRepeat default False;
property RepeatTop: boolean read FRepeatTop write SetFRepeatTop default False;
property RepeatLeft: boolean read FRepeatLeft write SetFRepeatLeft default False;
property RepeatMiddleHorizontal: boolean
read FRepeatMiddleHorizontal write SetFRepeatMiddleHorizontal default False;
property RepeatMiddleVertical: boolean read FRepeatMiddleVertical
write SetFRepeatMiddleVertical default False;
property RepeatRight: boolean read FRepeatRight write SetFRepeatRight default False;
property RepeatBottom: boolean
read FRepeatBottom write SetFRepeatBottom default False;
property MarginTop: integer read FMarginTop write SetFMarginTop default 0;
property MarginRight: integer read FMarginRight write SetFMarginRight default 0;
property MarginBottom: integer read FMarginBottom write SetFMarginBottom default 0;
property MarginLeft: integer read FMarginLeft write SetFMarginLeft default 0;
property NumberOfItems: integer
read FNumberOfItems write SetFNumberOfItems default 1;
property Direction: TSliceScalingDirection read FDirection write SetFDirection;
property DrawMode: TDrawMode read FDrawMode write SetFDrawMode default
dmDrawWithTransparency;
property ResampleMode: TResampleMode read FResampleMode
write SetFResampleMode default rmFineResample;
property ResampleFilter: TResampleFilter read FResampleFilter
write SetFResampleFilter default rfBestQuality;
end;
{ TBCImageButtonSliceScalingOptions }
TBCImageButtonSliceScalingOptions = class(TBCCustomSliceScalingOptions)
private
procedure SetFCenter(AValue: boolean);
procedure SetFProportional(AValue: boolean);
procedure SetFStretch(AValue: boolean);
protected
FCenter, FStretch, FProportional: boolean;
published
property NumberOfItems: integer read FNumberOfItems default 4;
property Center: boolean read FCenter write SetFCenter default True;
property Stretch: boolean read FStretch write SetFStretch default True;
property Proportional: boolean
read FProportional write SetFProportional default False;
public
constructor Create(AOwner: TControl);
procedure Assign(Source: TPersistent); override;
end;
{ TBCCustomImageButton }
TBCCustomImageButton = class(TBCGraphicButton)
private
{ Private declarations }
{$IFDEF DEBUG}
FDrawCount: integer;
FRenderCount: integer;
{$ENDIF}
FBitmapOptions: TBCImageButtonSliceScalingOptions;
FBGRAMultiSliceScaling: TBGRAMultiSliceScaling;
FBGRANormal, FBGRAHover, FBGRAActive, FBGRADisabled: TBGRABitmap;
FDestRect: TRect;
FPressed: boolean;
FTimer: TTimer;
FFade: TFading;
FAnimation: boolean;
FBitmapFile: string;
FTextVisible: boolean;
FToggle: boolean;
procedure SetFAnimation(AValue: boolean);
procedure SetFBitmapFile(AValue: string);
procedure SetFBitmapOptions(AValue: TBCImageButtonSliceScalingOptions);
procedure Fade({%H-}Sender: TObject);
procedure SetFPressed(AValue: boolean);
procedure SetFTextVisible(AValue: boolean);
procedure SetFToggle(AValue: boolean);
protected
{ Protected declarations }
procedure DrawControl; override;
procedure RenderControl; override;
procedure TextChanged; override;
procedure CMChanged(var {%H-}Message: TLMessage); message CM_CHANGED; virtual;
{$IFDEF DEBUG}
function GetDebugText: string;
{$ENDIF}
procedure DoMouseDown; override;
procedure DoMouseUp; override;
procedure DoMouseEnter; override;
procedure DoMouseLeave; override;
procedure Click; override;
public
{ Public declarations }
property Toggle: boolean read FToggle write SetFToggle default False;
property Pressed: boolean read FPressed write SetFPressed default False;
//property State: TBCGraphicButtonState read FState;
property BitmapOptions: TBCImageButtonSliceScalingOptions
read FBitmapOptions write SetFBitmapOptions;
property Animation: boolean read FAnimation write SetFAnimation default True;
property BitmapFile: string read FBitmapFile write SetFBitmapFile;
property TextVisible: boolean read FTextVisible write SetFTextVisible default True;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ It loads the 'BitmapFile' }
procedure LoadFromBitmapResource(Resource: string; ResourceType: PChar); overload;
procedure LoadFromBitmapResource(Resource: string); overload;
procedure LoadFromBitmapFile;
procedure Assign(Source: TPersistent); override;
{ Streaming }
procedure SaveToFile(AFileName: string);
procedure LoadFromFile(AFileName: string);
procedure AssignFromFile(AFileName: string);
procedure OnFindClass({%H-}Reader: TReader; const AClassName: string;
var ComponentClass: TComponentClass);
published
{ Published declarations }
end;
TBCImageButton = class(TBCCustomImageButton)
published
property Action;
property Align;
property Anchors;
property Animation;
property AutoSize;
//property AutoSizeExtraHorizontal;
//property AutoSizeExtraVertical;
property BidiMode;
//property Bitmap;
property BitmapFile;
property BitmapOptions;
property BorderSpacing;
property Caption;
//property Checked;
property Color;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property ModalResult;
property OnChangeBounds;
property OnClick;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
//property OnPlaySound;
//property OnRedraw;
property OnResize;
property OnStartDrag;
property ParentBidiMode;
property ParentFont;
property ParentShowHint;
property PopupMenu;
//property Shadow;
property ShowHint;
//property Sound;
//property SoundClick;
//property SoundEnter;
property TextVisible;
property Toggle;
property Pressed;
property Visible;
end;
procedure Register;
implementation
uses
LCLType;
procedure Register;
begin
{$I icons\bcimagebutton_icon.lrs}
RegisterComponents('BGRA Controls', [TBCImageButton]);
{$I icons\bcxbutton_icon.lrs}
RegisterComponents('BGRA Controls', [TBCXButton]);
end;
function CalculateAspectRatioH(W1, H1, W2: integer): integer;
begin
Result := Round(H1 / W1 * W2);
end;
function CalculateAspectRatioW(W1, H1, H2: integer): integer;
begin
Result := Round(W1 / H1 * H2);
end;
function CalculateDestRect(ImageW, ImageH, DestW, DestH: integer;
Stretch, Proportional, Center: boolean): TRect;
var
w: integer;
h: integer;
begin
// Stretch or Proportional when Image (Width or Height) is bigger than Destination
if Stretch or (Proportional and ((ImageW > DestW) or (ImageH > DestH))) then
begin
// Proportional when Image (Width or Height) is bigger than 0
if Proportional and (ImageW > 0) and (ImageH > 0) then
begin
w := DestW;
h := CalculateAspectRatioH(ImageW, ImageH, DestW);
if h > DestH then
begin
h := DestH;
w := CalculateAspectRatioW(ImageW, ImageH, DestH);
end;
ImageW := w;
ImageH := h;
end
// Stretch not Proportional or when Image (Width or Height) is 0
else
begin
ImageW := DestW;
ImageH := DestH;
end;
end;
Result := Rect(0, 0, ImageW, ImageH);
// Center: Destination (Width or Height) - Image divided by 2
if Center then
begin
Result.Left := Round((DestW - ImageW) div 2);
Result.Top := Round((DestH - ImageH) div 2);
end;
end;
procedure AssignFontToBGRA(Source: TFont; Dest: TBGRABitmap);
begin
Dest.FontAntialias := True;
Dest.FontName := Source.Name;
Dest.FontStyle := Source.Style;
Dest.FontOrientation := Source.Orientation;
case Source.Quality of
fqNonAntialiased: Dest.FontQuality := fqSystem;
fqAntialiased: Dest.FontQuality := fqFineAntialiasing;
fqProof: Dest.FontQuality := fqFineClearTypeRGB;
fqDefault, fqDraft, fqCleartype, fqCleartypeNatural: Dest.FontQuality :=
fqSystemClearType;
end;
Dest.FontHeight := -Source.Height;
end;
{ TBCXButton }
class function TBCXButton.GetControlClassDefaultSize: TSize;
begin
Result := inherited GetControlClassDefaultSize;
end;
procedure TBCXButton.DrawControl;
begin
if Enabled then
case FState of
gbsNormal: FBGRANormal.Draw(Canvas, 0, 0, False);
gbsHover: FBGRAHover.Draw(Canvas, 0, 0, False);
gbsActive: FBGRAActive.Draw(Canvas, 0, 0, False);
end
else
FBGRADisabled.Draw(Canvas, 0, 0, False);
end;
procedure TBCXButton.RenderControl;
begin
{ Free cache bitmaps }
if FBGRANormal <> nil then
FreeAndNil(FBGRANormal);
if FBGRAHover <> nil then
FreeAndNil(FBGRAHover);
if FBGRAActive <> nil then
FreeAndNil(FBGRAActive);
if FBGRADisabled <> nil then
FreeAndNil(FBGRADisabled);
{ Create cache bitmaps }
FBGRANormal := TBGRABitmap.Create(Width, Height);
FBGRAHover := TBGRABitmap.Create(Width, Height);
FBGRAActive := TBGRABitmap.Create(Width, Height);
FBGRADisabled := TBGRABitmap.Create(Width, Height);
if Assigned(FOnRenderControl) then
begin
FOnRenderControl(Self, FBGRANormal, gbsNormal);
FOnRenderControl(Self, FBGRAHover, gbsHover);
FOnRenderControl(Self, FBGRAActive, gbsActive);
FOnRenderControl(Self, FBGRADisabled, gbsDisabled);
end;
end;
constructor TBCXButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
with GetControlClassDefaultSize do
SetInitialBounds(0, 0, CX, CY);
end;
destructor TBCXButton.Destroy;
begin
if FBGRANormal <> nil then
FreeAndNil(FBGRANormal);
if FBGRAHover <> nil then
FreeAndNil(FBGRAHover);
if FBGRAActive <> nil then
FreeAndNil(FBGRAActive);
if FBGRADisabled <> nil then
FreeAndNil(FBGRADisabled);
inherited Destroy;
end;
{ TBCImageButtonSliceScalingOptions }
procedure TBCImageButtonSliceScalingOptions.SetFCenter(AValue: boolean);
begin
if FCenter = AValue then
Exit;
FCenter := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCImageButtonSliceScalingOptions.SetFProportional(AValue: boolean);
begin
if FProportional = AValue then
Exit;
FProportional := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCImageButtonSliceScalingOptions.SetFStretch(AValue: boolean);
begin
if FStretch = AValue then
Exit;
FStretch := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
constructor TBCImageButtonSliceScalingOptions.Create(AOwner: TControl);
begin
inherited Create(AOwner);
FNumberOfItems := 4;
FCenter := True;
FProportional := False;
FStretch := True;
end;
procedure TBCImageButtonSliceScalingOptions.Assign(Source: TPersistent);
begin
if Source is TBCImageButtonSliceScalingOptions then
begin
FAutoDetectRepeat := TBCImageButtonSliceScalingOptions(Source).AutoDetectRepeat;
FCenter := TBCImageButtonSliceScalingOptions(Source).Center;
FRepeatTop := TBCImageButtonSliceScalingOptions(Source).RepeatTop;
FRepeatLeft := TBCImageButtonSliceScalingOptions(Source).RepeatLeft;
FRepeatMiddleHorizontal :=
TBCImageButtonSliceScalingOptions(Source).RepeatMiddleHorizontal;
FRepeatMiddleVertical := TBCImageButtonSliceScalingOptions(
Source).RepeatMiddleVertical;
FRepeatRight := TBCImageButtonSliceScalingOptions(Source).RepeatRight;
FRepeatBottom := TBCImageButtonSliceScalingOptions(Source).RepeatBottom;
FMarginTop := TBCImageButtonSliceScalingOptions(Source).MarginTop;
FMarginRight := TBCImageButtonSliceScalingOptions(Source).MarginRight;
FMarginBottom := TBCImageButtonSliceScalingOptions(Source).MarginBottom;
FMarginLeft := TBCImageButtonSliceScalingOptions(Source).MarginLeft;
FDirection := TBCImageButtonSliceScalingOptions(Source).Direction;
FDrawMode := TBCImageButtonSliceScalingOptions(Source).DrawMode;
FResampleMode := TBCImageButtonSliceScalingOptions(Source).ResampleMode;
FResampleFilter := TBCImageButtonSliceScalingOptions(Source).ResampleFilter;
FStretch := TBCImageButtonSliceScalingOptions(Source).Stretch;
FProportional := TBCImageButtonSliceScalingOptions(Source).Proportional;
end
else
inherited Assign(Source);
end;
{ TBCCustomSliceScalingOptions }
procedure TBCCustomSliceScalingOptions.SetFBitmap(AValue: TBGRABitmap);
begin
if FBitmap = AValue then
Exit;
FBitmap := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFMarginBottom(AValue: integer);
begin
if FMarginBottom = AValue then
Exit;
FMarginBottom := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFMarginLeft(AValue: integer);
begin
if FMarginLeft = AValue then
Exit;
FMarginLeft := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFMarginRight(AValue: integer);
begin
if FMarginRight = AValue then
Exit;
FMarginRight := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFMarginTop(AValue: integer);
begin
if FMarginTop = AValue then
Exit;
FMarginTop := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFAutoDetectRepeat(AValue: boolean);
begin
if FAutoDetectRepeat = AValue then
Exit;
FAutoDetectRepeat := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFDirection(AValue: TSliceScalingDirection);
begin
if FDirection = AValue then
Exit;
FDirection := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFDrawMode(AValue: TDrawMode);
begin
if FDrawMode = AValue then
Exit;
FDrawMode := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFNumberOfItems(AValue: integer);
begin
if FNumberOfItems = AValue then
Exit;
FNumberOfItems := AValue;
end;
procedure TBCCustomSliceScalingOptions.SetFRepeatBottom(AValue: boolean);
begin
if FRepeatBottom = AValue then
Exit;
FRepeatBottom := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFRepeatLeft(AValue: boolean);
begin
if FRepeatLeft = AValue then
Exit;
FRepeatLeft := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFRepeatMiddleHorizontal(AValue: boolean);
begin
if FRepeatMiddleHorizontal = AValue then
Exit;
FRepeatMiddleHorizontal := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFRepeatMiddleVertical(AValue: boolean);
begin
if FRepeatMiddleVertical = AValue then
Exit;
FRepeatMiddleVertical := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFRepeatRight(AValue: boolean);
begin
if FRepeatRight = AValue then
Exit;
FRepeatRight := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFRepeatTop(AValue: boolean);
begin
if FRepeatTop = AValue then
Exit;
FRepeatTop := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFResampleFilter(AValue: TResampleFilter);
begin
if FResampleFilter = AValue then
Exit;
FResampleFilter := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
procedure TBCCustomSliceScalingOptions.SetFResampleMode(AValue: TResampleMode);
begin
if FResampleMode = AValue then
Exit;
FResampleMode := AValue;
FOwner.Perform(CM_CHANGED, 0, 0);
FOwner.Invalidate;
end;
constructor TBCCustomSliceScalingOptions.Create(AOwner: TControl);
begin
FOwner := AOwner;
FBitmap := nil;
FAutoDetectRepeat := False;
FRepeatTop := False;
FRepeatLeft := False;
FRepeatMiddleHorizontal := False;
FRepeatMiddleVertical := False;
FRepeatRight := False;
FRepeatBottom := False;
FMarginTop := 0;
FMarginRight := 0;
FMarginBottom := 0;
FMarginLeft := 0;
FNumberOfItems := 1;
FDirection := sdVertical;
FDrawMode := dmDrawWithTransparency;
FResampleMode := rmFineResample;
FResampleFilter := rfBestQuality;
inherited Create;
end;
destructor TBCCustomSliceScalingOptions.Destroy;
begin
if FBitmap <> nil then
FreeAndNil(FBitmap);
inherited Destroy;
end;
{ TBCGraphicButton }
procedure TBCGraphicButton.DoClick;
var
Form: TCustomForm;
begin
if ModalResult <> mrNone then
begin
Form := GetParentForm(Self);
if Form <> nil then
Form.ModalResult := ModalResult;
end;
end;
procedure TBCGraphicButton.DoMouseDown;
var
NewState: TBCGraphicButtonState;
begin
NewState := gbsActive;
if NewState <> FState then
begin
FState := NewState;
Invalidate;
end;
end;
procedure TBCGraphicButton.DoMouseUp;
var
NewState: TBCGraphicButtonState;
p: TPoint;
begin
p := ScreenToClient(Mouse.CursorPos);
if (p.x >= 0) and (p.x <= Width) and (p.y >= 0) and (p.y <= Height) then
NewState := gbsHover
else
NewState := gbsNormal;
if NewState <> FState then
begin
FState := NewState;
Invalidate;
end;
end;
procedure TBCGraphicButton.DoMouseEnter;
var
NewState: TBCGraphicButtonState;
begin
if Enabled then
NewState := gbsHover
else
begin
FState := gbsNormal;
NewState := FState;
end;
if NewState <> FState then
begin
FState := NewState;
Invalidate;
end;
end;
procedure TBCGraphicButton.DoMouseLeave;
var
NewState: TBCGraphicButtonState;
begin
if Enabled then
NewState := gbsNormal
else
begin
FState := gbsNormal;
NewState := FState;
end;
if NewState <> FState then
begin
FState := NewState;
Invalidate;
end;
end;
procedure TBCGraphicButton.Click;
begin
DoClick;
inherited Click;
end;
procedure TBCGraphicButton.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: integer);
begin
inherited MouseDown(Button, Shift, X, Y);
if Button = mbLeft then
DoMouseDown;
end;
procedure TBCGraphicButton.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: integer);
begin
inherited MouseUp(Button, Shift, X, Y);
DoMouseUp;
end;
procedure TBCGraphicButton.MouseEnter;
begin
inherited MouseEnter;
DoMouseEnter;
end;
procedure TBCGraphicButton.MouseLeave;
begin
inherited MouseLeave;
DoMouseLeave;
end;
{ TBCCustomImageButton }
procedure TBCCustomImageButton.Fade(Sender: TObject);
begin
if FFade.Mode <> fmSuspended then
Invalidate;
end;
procedure TBCCustomImageButton.SetFPressed(AValue: boolean);
begin
if FPressed = AValue then
Exit;
FPressed := AValue;
RenderControl;
end;
procedure TBCCustomImageButton.SetFTextVisible(AValue: boolean);
begin
if FTextVisible = AValue then
Exit;
FTextVisible := AValue;
RenderControl;
end;
procedure TBCCustomImageButton.SetFToggle(AValue: boolean);
begin
if FToggle = AValue then
Exit;
FToggle := AValue;
end;
procedure TBCCustomImageButton.SetFBitmapOptions(AValue:
TBCImageButtonSliceScalingOptions);
begin
if FBitmapOptions = AValue then
Exit;
FBitmapOptions := AValue;
end;
procedure TBCCustomImageButton.SetFAnimation(AValue: boolean);
begin
if FAnimation = AValue then
Exit;
FAnimation := AValue;
end;
procedure TBCCustomImageButton.SetFBitmapFile(AValue: string);
begin
if FBitmapFile = AValue then
Exit;
FBitmapFile := AValue;
end;
procedure TBCCustomImageButton.DrawControl;
var
temp: TBGRABitmap;
begin
if Color <> clDefault then
begin
Canvas.Brush.Color := Color;
Canvas.FillRect(0, 0, Width, Height);
end;
if Enabled then
begin
if (Toggle) then
begin
if (Pressed) then
FBGRAActive.Draw(Canvas, FDestRect.Left, FDestRect.Top, False)
else
case FState of
gbsHover: FBGRAHover.Draw(Canvas, FDestRect.Left,
FDestRect.Top, False);
else
FBGRANormal.Draw(Canvas, FDestRect.Left,
FDestRect.Top, False);
end;
end
else
begin
case FState of
gbsNormal, gbsHover: FBGRANormal.Draw(Canvas, FDestRect.Left,
FDestRect.Top, False);
gbsActive: FBGRAActive.Draw(Canvas, FDestRect.Left, FDestRect.Top, False);
end;
temp := TBGRABitmap.Create(Width, Height);
FFade.Execute;
FFade.PutImage(temp, 0, 0, FBGRAHover);
temp.Draw(Canvas, FDestRect.Left, FDestRect.Top, False);
temp.Free;
end;
end
else
FBGRADisabled.Draw(Canvas, FDestRect.Left, FDestRect.Top, False);
{$IFDEF DEBUG}
FDrawCount += 1;
{$ENDIF}
{$IFDEF DEBUG}
Canvas.Brush.Color := clWhite;
Canvas.TextOut(0, 0, GetDebugText);
{$ENDIF}
end;
procedure TBCCustomImageButton.RenderControl;
procedure DrawText(ABitmap: TBGRABitmap);
begin
AssignFontToBGRA(Font, ABitmap);
ABitmap.TextRect(Rect(0, 0, Width, Height), Caption, taCenter, tlCenter,
Font.Color);
end;
{$IFDEF DEBUG}
const
Debug = True;
{$ELSE}
const
Debug = False;
{$ENDIF}
var
i: integer;
begin
{ Free cache bitmaps }
if FBGRANormal <> nil then
FreeAndNil(FBGRANormal);
if FBGRAHover <> nil then
FreeAndNil(FBGRAHover);
if FBGRAActive <> nil then
FreeAndNil(FBGRAActive);
if FBGRADisabled <> nil then
FreeAndNil(FBGRADisabled);
{ Create cache bitmaps }
FBGRANormal := TBGRABitmap.Create(Width, Height);
FBGRAHover := TBGRABitmap.Create(Width, Height);
FBGRAActive := TBGRABitmap.Create(Width, Height);
FBGRADisabled := TBGRABitmap.Create(Width, Height);
{ Free FBGRAMultiSliceScaling }
if FBGRAMultiSliceScaling <> nil then
FreeAndNil(FBGRAMultiSliceScaling);
if (FBitmapOptions.Bitmap <> nil) then
begin
{ Create FBGRAMultiSliceScaling }
FBGRAMultiSliceScaling := TBGRAMultiSliceScaling.Create(FBitmapOptions.Bitmap,
FBitmapOptions.MarginTop, FBitmapOptions.MarginRight,
FBitmapOptions.MarginBottom, FBitmapOptions.MarginLeft,
FBitmapOptions.NumberOfItems, FBitmapOptions.Direction);
{ Set FBGRAMultiSliceScaling properties }
for i := 0 to High(FBGRAMultiSliceScaling.SliceScalingArray) do
begin
FBGRAMultiSliceScaling.SliceScalingArray[i].ResampleFilter :=
FBitmapOptions.ResampleFilter;
FBGRAMultiSliceScaling.SliceScalingArray[i].ResampleMode :=
FBitmapOptions.ResampleMode;
FBGRAMultiSliceScaling.SliceScalingArray[i].DrawMode := FBitmapOptions.DrawMode;
FBGRAMultiSliceScaling.SliceScalingArray[i].SliceRepeat[srpTop] :=
FBitmapOptions.RepeatTop;
FBGRAMultiSliceScaling.SliceScalingArray[i].SliceRepeat[srpBottom] :=
FBitmapOptions.RepeatBottom;
FBGRAMultiSliceScaling.SliceScalingArray[i].SliceRepeat[srpLeft] :=
FBitmapOptions.RepeatLeft;
FBGRAMultiSliceScaling.SliceScalingArray[i].SliceRepeat[srpRight] :=
FBitmapOptions.RepeatRight;
FBGRAMultiSliceScaling.SliceScalingArray[i].SliceRepeat[srpMiddleHorizontal] :=
FBitmapOptions.RepeatMiddleHorizontal;
FBGRAMultiSliceScaling.SliceScalingArray[i].SliceRepeat[srpMiddleVertical] :=
FBitmapOptions.RepeatMiddleVertical;
if FBitmapOptions.AutoDetectRepeat then
FBGRAMultiSliceScaling.SliceScalingArray[i].AutodetectRepeat;
end;
{ Calculate FDestRect }
FDestRect := CalculateDestRect(
FBGRAMultiSliceScaling.SliceScalingArray[0].BitmapWidth,
FBGRAMultiSliceScaling.SliceScalingArray[0].BitmapHeight, Width,
Height, FBitmapOptions.Stretch, FBitmapOptions.Proportional,
FBitmapOptions.Center);
{ Draw in cache bitmaps }
FBGRAMultiSliceScaling.Draw(0, FBGRANormal, 0, 0, FDestRect.Right,
FDestRect.Bottom, Debug);
FBGRAMultiSliceScaling.Draw(1, FBGRAHover, 0, 0, FDestRect.Right,
FDestRect.Bottom, Debug);
FBGRAMultiSliceScaling.Draw(2, FBGRAActive, 0, 0, FDestRect.Right,
FDestRect.Bottom, Debug);
FBGRAMultiSliceScaling.Draw(3, FBGRADisabled, 0, 0, FDestRect.Right,
FDestRect.Bottom, Debug);
if TextVisible then
begin
{ Draw Text }
DrawText(FBGRANormal);
DrawText(FBGRAHover);
DrawText(FBGRAActive);
DrawText(FBGRADisabled);
end;
end
else
begin
{ Calculate FDestRect }
FDestRect := Rect(0, 0, Width, Height);
{ Draw default style in cache bitmaps }
FBGRANormal.Rectangle(0, 0, Width, Height, BGRABlack, BGRA(0, 0, 255),
dmSet);
FBGRAHover.Rectangle(0, 0, Width, Height, BGRABlack, BGRA(0, 255, 0),
dmSet);
FBGRAActive.Rectangle(0, 0, Width, Height, BGRABlack, BGRA(255, 0, 0),
dmSet);
FBGRADisabled.Rectangle(0, 0, Width, Height, BGRABlack, BGRA(100, 100, 100),
dmSet);
{ Draw Text }
DrawText(FBGRANormal);
DrawText(FBGRAHover);
DrawText(FBGRAActive);
DrawText(FBGRADisabled);
end;
{$IFDEF DEBUG}
FRenderCount += 1;
{$ENDIF}
end;
procedure TBCCustomImageButton.TextChanged;
begin
InvalidatePreferredSize;
if Assigned(Parent) and Parent.AutoSize then
Parent.AdjustSize;
AdjustSize;
RenderControl;
Invalidate;
end;
procedure TBCCustomImageButton.CMChanged(var Message: TLMessage);
begin
if csReadingState in ControlState then
Exit;
RenderControl;
end;
{$IFDEF DEBUG}
function TBCCustomImageButton.GetDebugText: string;
begin
Result := 'Render: ' + IntToStr(FRenderCount) + ' Draw: ' + IntToStr(FDrawCount);
end;
{$ENDIF}
procedure TBCCustomImageButton.DoMouseDown;
begin
FFade.Mode := fmFadeOut;
if Animation then
FFade.Step := 60
else
FFade.Step := 255;
inherited DoMouseDown;
end;
procedure TBCCustomImageButton.DoMouseUp;
var
Ctrl: TControl;
begin
FFade.Mode := fmFadeIn;
if Animation then
FFade.Step := 20
else
FFade.Step := 255;
Ctrl := Application.GetControlAtMouse;
if Ctrl = Self then
DoMouseEnter
else
DoMouseLeave;
inherited DoMouseUp;
end;
procedure TBCCustomImageButton.DoMouseEnter;
begin
FFade.Mode := fmFadeIn;
if Animation then
FFade.Step := 15
else
FFade.Step := 255;
inherited DoMouseEnter;
end;
procedure TBCCustomImageButton.DoMouseLeave;
begin
FFade.Mode := fmFadeOut;
if Animation then
FFade.Step := 8
else
FFade.Step := 255;
inherited DoMouseLeave;
end;
procedure TBCCustomImageButton.Click;
begin
inherited Click;
if (Toggle) then
begin
Pressed := not Pressed;
end;
end;
constructor TBCCustomImageButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
{$IFDEF DEBUG}
FDrawCount := 0;
FRenderCount := 0;
{$ENDIF}
DisableAutoSizing;
Include(FControlState, csCreating);
BeginUpdate;
try
with GetControlClassDefaultSize do
SetInitialBounds(0, 0, CX, CY);
ControlStyle := ControlStyle + [csAcceptsControls];
FBitmapOptions := TBCImageButtonSliceScalingOptions.Create(Self);
{FBitmapOptions.Bitmap := TBGRABitmap.Create(1,4,BGRAWhite);
FBitmapOptions.Bitmap.SetPixel(0,0,BGRA(255,0,0,255));
FBitmapOptions.Bitmap.SetPixel(0,1,BGRA(0,255,0,255));
FBitmapOptions.Bitmap.SetPixel(0,2,BGRA(0,0,255,255));
FBitmapOptions.Bitmap.SetPixel(0,3,BGRA(100,100,100,255));}
FFade.Step := 15;
FFade.Mode := fmFadeOut;
FTimer := TTimer.Create(Self);
FTimer.Interval := 15;
FTimer.OnTimer := @Fade;
FAnimation := True;
FTextVisible := True;
finally
Exclude(FControlState, csCreating);
EnableAutoSizing;
EndUpdate;
end;
end;
destructor TBCCustomImageButton.Destroy;
begin
FTimer.Free;
if FBGRAMultiSliceScaling <> nil then
FreeAndNil(FBGRAMultiSliceScaling);
if FBGRANormal <> nil then
FreeAndNil(FBGRANormal);
if FBGRAHover <> nil then
FreeAndNil(FBGRAHover);
if FBGRAActive <> nil then
FreeAndNil(FBGRAActive);
if FBGRADisabled <> nil then
FreeAndNil(FBGRADisabled);
FreeAndNil(FBitmapOptions);
inherited Destroy;
end;
procedure TBCCustomImageButton.LoadFromBitmapResource(Resource: string;
ResourceType: PChar);
var
res: TResourceStream;
begin
res := TResourceStream.Create(HInstance, Resource, ResourceType);
if BitmapOptions.Bitmap <> nil then
BitmapOptions.Bitmap.Free;
BitmapOptions.Bitmap := TBGRABitmap.Create(res);
res.Free;
end;
procedure TBCCustomImageButton.LoadFromBitmapResource(Resource: string);
begin
LoadFromBitmapResource(Resource, RT_RCDATA);
end;
procedure TBCCustomImageButton.LoadFromBitmapFile;
begin
if BitmapFile <> '' then
if BitmapOptions.Bitmap <> nil then
BitmapOptions.Bitmap.LoadFromFile(BitmapFile)
else
BitmapOptions.Bitmap := TBGRABitmap.Create(BitmapFile);
end;
procedure TBCCustomImageButton.Assign(Source: TPersistent);
begin
if Source is TBCCustomImageButton then
begin
FBitmapOptions.Assign(TBCCustomImageButton(Source).BitmapOptions);
FAnimation := TBCCustomImageButton(Source).Animation;
FBitmapFile := TBCCustomImageButton(Source).BitmapFile;
FTextVisible := TBCCustomImageButton(Source).TextVisible;
if TBCCustomImageButton(Source).BitmapOptions.Bitmap <> nil then
begin
if FBitmapOptions.Bitmap <> nil then
FBitmapOptions.Bitmap.Free;
FBitmapOptions.Bitmap :=
TBGRABitmap.Create(TBCCustomImageButton(Source).BitmapOptions.Bitmap.Bitmap);
end
else
LoadFromBitmapFile;
RenderControl;
Invalidate;
end
else
inherited Assign(Source);
end;
procedure TBCCustomImageButton.SaveToFile(AFileName: string);
var
AStream: TMemoryStream;
begin
AStream := TMemoryStream.Create;
try
WriteComponentAsTextToStream(AStream, Self);
AStream.SaveToFile(AFileName);
finally
AStream.Free;
end;
end;
procedure TBCCustomImageButton.LoadFromFile(AFileName: string);
var
AStream: TMemoryStream;
begin
AStream := TMemoryStream.Create;
try
AStream.LoadFromFile(AFileName);
ReadComponentFromTextStream(AStream, TComponent(Self), @OnFindClass);
finally
AStream.Free;
end;
end;
procedure TBCCustomImageButton.AssignFromFile(AFileName: string);
var
AStream: TMemoryStream;
AButton: TBCImageButton;
begin
AButton := TBCImageButton.Create(nil);
AStream := TMemoryStream.Create;
try
AStream.LoadFromFile(AFileName);
ReadComponentFromTextStream(AStream, TComponent(AButton), @OnFindClass);
Assign(AButton);
finally
AStream.Free;
AButton.Free;
end;
end;
procedure TBCCustomImageButton.OnFindClass(Reader: TReader;
const AClassName: string; var ComponentClass: TComponentClass);
begin
if CompareText(AClassName, 'TBCImageButton') = 0 then
ComponentClass := TBCImageButton;
end;
end.
|
(*
* TWebBrowserEx Classes
* WebBrowser Componet for FireMonkey.
*
* Copyright (c) 2013, 2014 HOSOKAWA Jun.
*
* Platform:
* Windows, OS X, iOS, Android
* Delphi / C++Builder XE5, XE6, XE7 and Appmethod 1.14, 1.15
*
* Contact:
* Twitter @pik or freeonterminate@gmail.com
*
* Original Source:
* https://github.com/freeonterminate/delphi/tree/master/TWebBrowser
*
* How to Use:
* 1. Add FMX.WebBroserEx to "uses" block.
*
* 2. Create WebBroserEx and Set parent.
* procedure TForm1.FormCreate(Sender: TObject);
* begin
* FWebBrowser := TWebBrowserEx.Create(Self);
* FWebBrowser.Parent := Panel1;
* FWebBrowser.Align := TAlignLayout.Client;
* end;
*
* 3. Set URL property.
* procedure TForm1.Button1Click(Sender: TObject);
* begin
* FWebBrowser.URL := 'https://twitter.com/pik';
* end;
*
* LICENSE:
* 本ソフトウェアは「現状のまま」で、明示であるか暗黙であるかを問わず、
* 何らの保証もなく提供されます。
* 本ソフトウェアの使用によって生じるいかなる損害についても、
* 作者は一切の責任を負わないものとします。
*
* 以下の制限に従う限り、商用アプリケーションを含めて、本ソフトウェアを
* 任意の目的に使用し、自由に改変して再頒布することをすべての人に許可します。
*
* 1. 本ソフトウェアの出自について虚偽の表示をしてはなりません。
* あなたがオリジナルのソフトウェアを作成したと主張してはなりません。
* あなたが本ソフトウェアを製品内で使用する場合、製品の文書に謝辞を入れて
* いただければ幸いですが、必須ではありません。
*
* 2. ソースを変更した場合は、そのことを明示しなければなりません。
* オリジナルのソフトウェアであるという虚偽の表示をしてはなりません。
*
* 3. ソースの頒布物から、この表示を削除したり、表示の内容を変更したりしては
* なりません。
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute
* it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented;
* you must not claim that you wrote the original software.
* If you use this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such,
* and must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*)
unit Macapi.WebView;
{$IF not defined(MACOS) or defined(IOS)}
{$WARNINGS OFF 1011}
interface
implementation
end.
{$ENDIF}
interface
uses
System.Classes
, Macapi.ObjectiveC, Macapi.CocoaTypes, Macapi.Foundation, Macapi.AppKit
, FMX.Types, FMX.Controls
;
type
WebFrame = interface;
WebView = interface;
WebFrameView = interface;
WebDocumentView = interface;
WebDataSource = interface;
WebResource = interface;
WebDocumentRepresentation = interface;
WebArchive = interface;
DOMDocument = interface;
WebScriptObject = interface;
WebBackForwardList = interface;
WebHistoryItem = interface;
WebPreferences = interface;
WebCacheModel = NSUInteger;
WebResource = interface(NSObject)
['{616664A6-28D7-49F4-82D4-67A9C9B0ABBE}']
function data: NSData; cdecl;
function frameName: NSString; cdecl;
function initWithData(
data: NSData;
URL: NSURL;
MIMEType: NSString;
textEncodingName: NSString;
frameName: NSString): Pointer; cdecl;
function MIMEType: NSString; cdecl;
function textEncodingName: NSString; cdecl;
function URL: NSURL; cdecl;
end;
WebDocumentRepresentation = interface(NSObject)
['{F1996B50-2F93-4DE3-84AB-42F588AFE74A}']
function canProvideDocumentSource: Boolean; cdecl;
function documentSource: NSString; cdecl;
procedure finishedLoadingWithDataSource(dataSource: WebDataSource); cdecl;
procedure receivedData(data: NSData; dataSource: WebDataSource); cdecl;
procedure receivedError(error: NSError; dataSource: WebDataSource); cdecl;
procedure setDataSource(dataSource: WebDataSource); cdecl;
function title: NSString; cdecl;
end;
WebArchive = interface(NSObject)
['{182A3424-31CE-4E93-BD4E-736859206529}']
function data: NSData; cdecl;
function initWithData(data: NSData): Pointer; cdecl;
function initWithMainResource(
mainResource: WebResource;
subresources: NSArray;
subframeArchives: NSArray): Pointer; cdecl;
function mainResource: WebResource; cdecl;
function subframeArchives: NSArray; cdecl;
function subresources: NSArray; cdecl;
end;
WebDataSource = interface(NSObject)
['{D138FA02-49A7-4F29-9AE0-EEC381C1AFED}']
procedure addSubresource(subresource: WebResource); cdecl;
function data: NSData; cdecl;
function initialRequest: NSURLRequest; cdecl;
function initWithRequest(request: NSURLRequest): Pointer; cdecl;
function isLoading: Boolean; cdecl;
function mainResource: WebResource; cdecl;
function pageTitle: NSString; cdecl;
function representation: WebDocumentRepresentation; cdecl;
function request: NSMutableURLRequest; cdecl;
function response: NSURLResponse; cdecl;
function subresourceForURL(URL: NSURL): WebResource; cdecl;
function subSOurces: NSArray; cdecl;
function textEncodingName: NSString; cdecl;
function unreachableURL: NSURL; cdecl;
function webArchive: WebArchive; cdecl;
function webFrame: WebFrame; cdecl;
end;
WebDocumentView = interface(NSObject)
['{1175C5ED-14A6-4115-A3C3-547650316EAC}']
procedure dataSourceUpdate(dataSource: WebDataSource); cdecl;
procedure layout; cdecl;
procedure setDataSource(dataSource: WebDataSource); cdecl;
procedure setNeedsLayout(flag: Boolean); cdecl;
procedure viewDidMoveToHostWindow; cdecl;
procedure viewWillMoveToHostWindow(hostWindow: NSWindow); cdecl;
end;
WebFrameView = interface(NSView)
['{348DEC2C-1594-4C5F-B625-4FA382090A49}']
function allowScrolling: Boolean; cdecl;
function canPrintHeadersAndFooters: Boolean; cdecl;
function documentView: WebDocumentView; cdecl;
function documentViewShouldHandlePrint: Boolean; cdecl;
procedure printDocumentView; cdecl;
function printOperationWithPrintInfo(
printInfo: NSPrintInfo): NSPrintOperation; cdecl;
procedure setAllowsScrolling(flag: Boolean); cdecl;
function webFrame: WebFrame; cdecl;
end;
WebFrameClass = interface(NSObjectClass)
['{7BE750C8-DFEC-4870-851A-12DBCB0B78F6}']
end;
WebFrame = interface(NSObject)
['{BCFA04BE-41AB-4B78-89C0-3330F12C7695}']
function childDrames: NSArray; cdecl;
function dataSource: WebDataSource; cdecl;
function DOMDocument: DOMDocument; cdecl;
function findFrameNamed(name: NSString): WebFrame; cdecl;
// function frameElement: DOMHtmlElement; cdecl;
function frameView: WebFrameView; cdecl;
// function globalContext: JSGlobalContextRef; cdecl;
function initWithFrame(
frameName: NSString;
view: WebFrameView;
webView: WebView): Pointer; cdecl;
procedure loadAlternateHTMLString(
string_: NSString;
URL: NSURL;
unreachableURL: NSURL); cdecl;
procedure loadArchive(archive: WebArchive); cdecl;
procedure loadData(
data: NSData;
MIMEType: NSString;
encodingName: NSString;
URL: NSURL); cdecl;
procedure loadHTMLString(string_: NSString; baseURL: NSURL); cdecl;
procedure loadRequest(request: NSURLRequest); cdecl;
function name: NSString; cdecl;
function parentFrame: WebFrame; cdecl;
function provisionalDataSource: WebDataSource; cdecl;
procedure reload; cdecl;
procedure reloadFromOrigin; cdecl;
procedure stopLoading; cdecl;
function webView: WebView; cdecl;
function windowObject: WebScriptObject; cdecl;
end;
DOMDocument = interface(NSObject)
function URLWithAttributeString(string_: NSString): NSURL; cdecl;
function webFrame: WebFrame; cdecl;
end;
WebScriptObjectClass = interface(NSObjectClass)
{class} function throwException(exceptionMessage: NSString): Boolean; cdecl;
end;
WebScriptObject = interface(NSObject)
function callWebScriptMethod(name: NSString; args: NSArray): Pointer; cdecl;
function evaluateWebScript(script: NSString): Pointer; cdecl;
// function JSObject: JSObjectRec; cdecl;
procedure removeWebScriptKey(name: NSString); cdecl;
procedure setException(description: NSString); cdecl;
procedure setWebScriptValueAtIndex(index: UInt32; value: Pointer); cdecl;
function stringRepresentation: NSString; cdecl;
function webScriptValueAtIndex(index: UInt32): Pointer; cdecl;
end;
WebViewClass = interface(NSViewClass)
['{0D9F44B7-09FD-4E35-B96E-8DB71B9A2537}']
{class} function canShowMIMEType(MIMEType: NSString): Boolean; cdecl;
{class} function canShowMIMETypeAsHTML(MIMEType: NSString): Boolean; cdecl;
{class} function MIMETypesShownAsHTML: NSArray; cdecl;
{class} procedure registerURLSchemeAsLocal(scheme: NSString); cdecl;
{class} procedure registerViewClass(
viewClass: Pointer;
representationClass: Pointer;
MIMEType: NSString); cdecl;
{class} procedure setMIMETypesShownAsHTML(MIMETypes: NSArray); cdecl;
{class} function URLFromPasteboard(pasteboard: NSPasteboard): NSURL; cdecl;
{class} function URLTitleFromPasteboard(
pasteboard: NSPasteBoard): NSString; cdecl;
end;
WebView = interface(NSView)
['{C36D8016-2FCB-49F0-BA1C-C9913A37F9AC}']
procedure alignCenter(sender: Pointer); cdecl;
procedure alignJustified(sender: Pointer); cdecl;
procedure alignLeft(sender: Pointer); cdecl;
procedure alignRight(sender: Pointer); cdecl;
function applicationNameForUserAgent: NSString; cdecl;
//procedure applyStyle(style: DOMCSSStyleDeclaration ); cdecl;
function backForwardList: WebBackForwardList; cdecl;
function canGoBack: Boolean; cdecl;
function canGoForward: Boolean; cdecl;
function canMakeTextLarger: Boolean; cdecl;
function canMakeTextSmaller: Boolean; cdecl;
function canMakeTextStandardSize: Boolean; cdecl;
procedure changeAttributes(sender: Pointer); cdecl;
procedure changeColor(sender: Pointer); cdecl;
procedure changeDocumentBackgroundColor(sender: Pointer); cdecl;
procedure changeFont(sender: Pointer); cdecl;
procedure checkSpelling(sender: Pointer); cdecl;
procedure close; cdecl;
//function computedStyleForElement(
//element: DOMElement;
//pseudoElement: NSString): DOMCSSStyleDeclaration; cdecl;
procedure copy(sender: Pointer); cdecl;
procedure copyFont(sender: Pointer); cdecl;
function customTextEncodingName: NSString; cdecl;
function customUserAgent: NSString; cdecl;
procedure cut(sender: Pointer); cdecl;
procedure delete(sender: Pointer); cdecl;
procedure deleteSelection; cdecl;
function downloadDelegate: Pointer; cdecl;
function drawsBackground: Boolean; cdecl;
//function editableDOMRangeForPoint(point: NSPoint): DOMRange; cdecl;
function editingDelegate: Pointer; cdecl;
function elementAtPoint(point: NSPoint): NSDictionary; cdecl;
function estimatedProgress: Double; cdecl;
function frameLoadDelegate: Pointer; cdecl;
function goBack: Boolean; cdecl; overload;
procedure goBack(sender: Pointer); cdecl; overload;
function goForward: Boolean; cdecl; overload;
procedure goForward(sender: Pointer); cdecl; overload;
function goToBackForwardItem(item: WebHistoryItem): Boolean; cdecl;
function groupName: NSString; cdecl;
function hostWindow: NSWindow; cdecl;
function initWithFrame(
frame: NSRect;
frameName: NSString;
groupName: NSString): Pointer; cdecl;
function isContinuousSpellCheckingEnabled: Boolean; cdecl;
function isEditable: Boolean; cdecl;
function isLoading: Boolean; cdecl;
function mainFrame: WebFrame; cdecl;
function mainFrameDocument: DOMDocument; cdecl;
function mainFrameIcon: NSImage; cdecl;
function mainFrameTitle: NSString; cdecl;
function mainFrameURL: NSString; cdecl;
function maintainsInactiveSelection: Boolean; cdecl;
procedure makeTextLarger(sender: Pointer); cdecl;
procedure makeTextSmaller(sender: Pointer); cdecl;
procedure makeTextStandardSize(sender: Pointer); cdecl;
function mediaStyle: NSString; cdecl;
procedure moveDragCaretToPoint(point: NSPoint); cdecl;
procedure moveToBeginningOfSentence(sender: Pointer); cdecl;
procedure moveToBeginningOfSentenceAndModifySelection(
sender: Pointer); cdecl;
procedure moveToEndOfSentence(sender: Pointer); cdecl;
procedure moveToEndOfSentenceAndModifySelection(sender: Pointer); cdecl;
procedure paste(sender: Pointer); cdecl;
procedure pasteAsPlainText(sender: Pointer); cdecl;
procedure pasteAsRichText(sender: Pointer); cdecl;
function pasteboardTypesForElement(element: NSDictionary): NSArray; cdecl;
function pasteboardTypesForSelection: NSArray; cdecl;
procedure pasteFont(sender: Pointer); cdecl;
procedure performFindPanelAction(sender: Pointer); cdecl;
function policyDelegate: Pointer; cdecl;
function preferences: WebPreferences; cdecl;
function preferencesIdentifier: NSString; cdecl;
procedure reload(sender: Pointer); cdecl;
procedure reloadFromOrigin(sender: Pointer); cdecl;
procedure removeDragCaret; cdecl;
procedure replaceSelectionWithArchive(archive: WebArchive); cdecl;
procedure replaceSelectionWithMarkupString(markupString: NSString); cdecl;
//procedure replaceSelectionWithNode(node: DOMNode); cdecl;
procedure replaceSelectionWithText(text: NSString); cdecl;
function resourceLoadDelegate: Pointer; cdecl;
function searchFor(
string_: NSString;
forward_: Boolean;
caseFlag: Boolean;
wrapFlag: Boolean): Boolean; cdecl;
//function selectedDOMRange: DOMRange; cdecl;
function selectedFrame: WebFrame; cdecl;
function selectionAffinity: NSSelectionAffinity; cdecl;
procedure selectSentence(sender: Pointer); cdecl;
procedure setApplicationNameForUserAgent(applicationName: NSString); cdecl;
procedure setContinuousSpellCheckingEnabled(flag: Boolean); cdecl;
procedure setCustomTextEncodingName(encodingName: NSString); cdecl;
procedure setCustomUserAgent(userAgent: NSString); cdecl;
procedure setDownloadDelegate(delegate: Pointer); cdecl;
procedure setDrawsBackground(drawsBackgound: Boolean); cdecl;
procedure setEditable(flag: Boolean); cdecl;
procedure setEditingDelegate(delegate: Pointer); cdecl;
procedure setFrameLoadDelegate(delegate: Pointer); cdecl;
procedure setGroupName(groupName: NSString); cdecl;
procedure setHostWindow(hostWindow: NSWindow); cdecl;
procedure setMainFrameURL(URLString: NSString); cdecl;
procedure setMaintainsBackForwardList(flag: Boolean); cdecl;
procedure setMediaStyle(mediaStyle: NSString); cdecl;
procedure setPolicyDelegate(delegate: Pointer); cdecl;
procedure setPreferences(preferences: WebPreferences); cdecl;
procedure setPreferencesIdentifier(anIdentifier: NSString); cdecl;
procedure setResourceLoadDelegate(delegate: Pointer); cdecl;
//procedure setSelectedDOMRange(
//range: DOMRange;
//selectionAffinity: NSSelectionAffinity); cdecl;
procedure setShouldCloseWithWindow(close: Boolean); cdecl;
procedure setShouldUpdateWhileOffscreen(
updateWhileOffscreen: Boolean); cdecl;
procedure setSmartInsertDeleteEnabled(flag: Boolean); cdecl;
procedure setTextSizeMultiplier(multiplier: Single); cdecl;
//procedure setTypingStyle(style: DOMCSSStyleDeclaratoin); cdecl;
procedure setUIDelegate(delegate: Pointer); cdecl;
function shouldCloseWithWindow: Boolean; cdecl;
function shouldUpdateWhileOffscreen: Boolean; cdecl;
procedure showGuessPanel(sender: Pointer); cdecl;
function smartInsertDeleteEnabled: Boolean; cdecl;
function spellCheckerDocumentTag: NSInteger; cdecl;
procedure startSpeaking(sender: Pointer); cdecl;
procedure stopLoading(sender: Pointer); cdecl;
procedure stopSpeaking(sender: Pointer); cdecl;
function stringByEvaluatingJavaScriptFromString(
script: NSString): NSString; cdecl;
//function styleDeclarationWithText(
//text: NSString): DOMCSSStyleDeclaration; cdecl;
function supportsTextEncoding: Boolean; cdecl;
procedure takeStringURLFrom(sender: Pointer); cdecl;
function textSizeMultiplier: Single; cdecl;
procedure toggleContinuousSpellChecking(sender: Pointer);cdecl;
procedure toggleSmartInsertDelete(sender: Pointer); cdecl;
//function typingStyle: DOMCSSStyleDeclaration; cdecl;
function UIDelegate: Pointer; cdecl;
function undoManager: NSUndoManager; cdecl;
function userAgentForURL(URL: NSURL): NSString; cdecl;
function windowScriptObject: WebScriptObject; cdecl;
procedure writeElement(
element: NSDictionary;
types: NSArray;
pasteboard: NSPasteBoard); cdecl;
procedure writeSelectionWithPasteboardTypes(
types: NSArray;
pasteboard: NSPasteBoard); cdecl;
end;
WebBackForwardList = interface(NSObject)
['{FAC642D3-A5AC-490F-A1B6-5ACBEB2D6C20}']
procedure addItem(item: WebHistoryItem); cdecl;
function backItem: WebHistoryItem; cdecl;
function backListCount: Int32; cdecl;
function backListWithLimit(limit: Int32): NSArray; cdecl;
function capacity: Int32; cdecl;
function containsItem(item: WebHistoryItem): Boolean; cdecl;
function currentItem: WebHistoryItem; cdecl;
function forwardItem: WebHistoryItem; cdecl;
function forwardListCount: Int32; cdecl;
function forwardListWithLimit(limit: Int32): NSArray; cdecl;
procedure goBack; cdecl;
procedure goForward; cdecl;
procedure goToItem(item: WebHistoryItem); cdecl;
function itemAtIndex(index: Int32): WebHistoryItem; cdecl;
procedure setCapacity(size: Int32); cdecl;
end;
WebHistoryItem = interface(NSObject)
['{E0642BE4-04F1-40A6-91AD-ABEE665A7717}']
function alternateTitle: NSString; cdecl;
function icon: NSImage; cdecl;
function initWithURLString(
URLString: NSString;
title: NSString;
time: NSTimeInterval): Pointer; cdecl;
function lastVisitedTimeInterval: NSTImeInterval; cdecl;
function originalURLString: NSString; cdecl;
procedure setAlternateTitle(alternateTitle: NSString); cdecl;
function title: NSString; cdecl;
function URLString: NSString; cdecl;
end;
WebPreferencesClass = interface(NSObjectClass)
['{1830695E-5C7A-424A-AABB-1600B7F2DE61}']
{class} function standardPreferences: WebPreferences; cdecl;
end;
WebPreferences = interface(NSObject)
['{65D8916F-6503-4EE2-8A8B-3A3CFFF6B133}']
function allowsAnimatedImageLooping: Boolean; cdecl;
function allowsAnimatedImages: Boolean; cdecl;
function arePlugInsEnabled: Boolean; cdecl;
function autosaves: Boolean; cdecl;
function cacheModel: WebCacheModel; cdecl;
function cursiveFontFamily: NSString; cdecl;
function defaultFixedFontSize: Int32; cdecl;
function defaultFontSize: Int32; cdecl;
function defaultTextEncodingName: NSString; cdecl;
function fantasyFontFamily: NSString; cdecl;
function fixedFontFamily: NSString; cdecl;
function identifier: NSString; cdecl;
function initWithIdentifier(anIdentifier: NSString): Pointer; cdecl;
function isJavaEnabled: Boolean; cdecl;
function isJavaScriptEnabled: Boolean; cdecl;
function javaScriptCanOpenWindowsAutomatically: Boolean; cdecl;
function loadsImagesAutomatically: Boolean; cdecl;
function minimumFontSize: Int32; cdecl;
function minimumLogicalFontSize: Int32; cdecl;
function privateBrowsingEnabled: Boolean; cdecl;
function sansSerifFontFamily: NSString; cdecl;
function serifFontFamily: NSString; cdecl;
procedure setAllowsAnimatedImageLooping(flag: Boolean); cdecl;
procedure setAllowsAnimatedImages(flag: Boolean); cdecl;
procedure setAutosaves(flag: Boolean); cdecl;
procedure setCacheModel(cacheMode: WebCacheModel); cdecl;
procedure setCursiveFontFamily(family: NSString); cdecl;
procedure setDefaultFixedFontSize(size: Int32); cdecl;
procedure setDefaultFontSize(size: Int32); cdecl;
procedure setDefaultTextEncodingName(encoding: NSString); cdecl;
procedure setFantasyFontFamily(family: NSString); cdecl;
procedure setFixedFontFamily(family: NSString); cdecl;
procedure setJavaEnabled(flag: Boolean); cdecl;
procedure setJavaScriptCanOpenWindowsAutomatically(flag: Boolean); cdecl;
procedure setJavaScriptEnabled(flag: Boolean); cdecl;
procedure setLoadsImagesAutomatically(flag: Boolean); cdecl;
procedure setMinimumFontSize(size: Int32); cdecl;
procedure setMinimumLogicalFontSize(size: Int32); cdecl;
procedure setPlugInsEnabled(flag: Boolean); cdecl;
procedure setPrivateBrowsingEnabled(flag: Boolean); cdecl;
procedure setSansSerifFontFamily(family: NSString); cdecl;
procedure setSerifFontFamily(family: NSString); cdecl;
procedure setShouldPrintBackgrounds(flag: Boolean); cdecl;
procedure setStandardFontFamily(family: NSString); cdecl;
procedure setSuppressesIncrementalRendering(
suppressesIncrementalRendering: Boolean); cdecl;
procedure setTabsToLinks(flag: Boolean); cdecl;
procedure setUserStyleSheetEnabled(flag: Boolean); cdecl;
procedure setUserStyleSheetLocation(URL: NSURL); cdecl;
procedure setUsesPageCache(usesPageCache: Boolean); cdecl;
function shouldPrintBackgrounds: Boolean; cdecl;
function standardFontFamily: NSString; cdecl;
function suppressesIncrementalRendering: Boolean; cdecl;
function tabsToLinks: Boolean; cdecl;
function userStyleSheetEnabled: Boolean; cdecl;
function userStyleSheetLocation: NSURL; cdecl;
function usesPageCache: Boolean; cdecl;
end;
// Overload needs TypeName from which a name is different.
WebFrame2 = type WebFrame;
WebFrame3 = type WebFrame;
WebFrame4 = type WebFrame;
WebFrame5 = type WebFrame;
WebFrame6 = type WebFrame;
WebFrame7 = type WebFrame;
WebFrame8 = type WebFrame;
WebFrameLoadDelegate = interface(IObjectiveC)
['{00FFAF7F-51EC-4F8D-84C2-B0FE4F24270A}']
procedure webView(
sender: WebView;
didStartProvisionalLoadForFrame: WebFrame); overload; cdecl;
procedure webView(
sender: WebView;
didReceiveServerRedirectForProvisionalLoadForFrame: WebFrame2);
overload; cdecl;
procedure webView(
sender: WebView;
didFailProvisionalLoadWithError: NSError;
frame: WebFrame); overload; cdecl;
procedure webView(
sender: WebView;
didCommitLoadForFrame: WebFrame3); overload; cdecl;
procedure webView(
sender: WebView;
didReceiveTitle: NSString;
frame: WebFrame); overload; cdecl;
procedure webView(
sender: WebView;
didReceiveIcon: NSImage;
frame: WebFrame); overload; cdecl;
procedure webView(
sender: WebView;
didFinishLoadForFrame: WebFrame4); overload; cdecl;
procedure webView(
sender: WebView;
didFailLoadWithError: NSError;
frame: WebFrame5); overload; cdecl;
procedure webView(
sender: WebView;
didChangeLocationWithinPageForFrame: WebFrame6); overload; cdecl;
procedure webView(
sender: WebView;
willPerformClientRedirectToURL: NSURL;
seconds: NSTimeInterval;
date: NSDate;
frame: WebFrame); overload; cdecl;
procedure webView(
sender: WebView;
didCancelClientRedirectForFrame: WebFrame7); overload; cdecl;
procedure webView(
sender: WebView;
willCloseFrame: WebFrame8); overload; cdecl;
procedure webView(
sender: WebView;
didClearWindowObject: WebScriptObject;
frame: WebFrame); overload; cdecl;
//procedure webView(
//sender: WebView;
//windowScriptObjectAvailable: WebScriptObject); overload; cdecl;
//procedure webView(
//sender: WebView;
//didCreateJavaScriptContext: JSContext;
//frame: WebFrame); overload; cdecl;
end;
TWebCacheModel = (
WebCacheModelDocumentViewer = 0,
WebCacheModelDocumentBrowser = 1,
WebCacheModelPrimaryWebBrowser = 2
);
TWebFrame = class(TOCGenericImport<WebFrameClass, WebFrame>)
end;
TWebView = class(TOCGenericImport<WebViewClass, WebView>)
end;
implementation
end.
|
// Ford-Fulkerson Algorithm
// Coded by Denis Tamkovich
// Review by @jaselnik
Const
MAX_N = 10;
Type
TMatrAdj = array[1..MAX_N, 1..MAX_N] of integer;
TParent = array[1..MAX_N]of integer;
// Read Graph from file
Procedure Input(Var mas:TMatrAdj; Var n:integer; filename:string);
Var
f:textfile;
i,j:integer;
Begin
assignfile(f,filename); reset(f);
readln(f,n);
For i:=1 to n do
For j:=1 to n do
read(f,mas[i,j]);
closefile(f);
End;
// Print the Graph
Procedure Output(mas:TMatrAdj; n:integer);
Var
i,j:integer;
begin
For i:=1 to N do
begin
For j:=1 to N do
begin
write(mas[i,j]:2);
end;
writeln;
end;
end;
// BFS - Breadth-First Search
Function BFS(graph:TMatrAdj;n,source,sink:integer;Var parent:TParent):boolean;
Var
i,j,q_index,q_len,s:integer;
visited:array[1..MAX_N]of boolean;
queue:array[1..MAX_N]of integer;
Begin
For i:=1 to n do
begin
visited[i]:=False;
queue[i]:=0;
end;
// Mark the source node as visited and add it into the queue
q_index:=1;
q_len:=1;
queue[q_index]:=source;
visited[source]:=True;
s:=source;
While q_index <= q_len do
begin
For i:=1 to n do
if not visited[i] and (graph[s,i]>0) then
begin
inc(q_len);
queue[q_len]:=i;
visited[i]:=True;
parent[i]:=s;
end;
inc(q_index);
s:=queue[q_index];
end;
BFS:=visited[sink];
End;
// Algorithm Ford-Falkeson
Function FordFulkerson(graph: TMatrAdj; n,source,sink:integer):integer;
Var
i,j,max_flow,path_flow,s,u,v:integer;
parent: TParent; // there we are saving the parent-node
Begin
For i:=1 to n do
parent[i]:=0;
max_flow:=0; // initially our maximum flow is = 0
// Check if there are any available ways
While BFS(graph,n,source,sink,parent) do
begin
path_flow:=graph[parent[sink],sink];
s:=parent[sink];
// There we looking for minimum flow to sink (path flow)
While s <> source do
begin
path_flow:=min(path_flow,graph[parent[s],s]);
s:=parent[s];
end;
// increasing our max flow to the path flow
inc(max_flow,path_flow);
v:=sink;
// decrease the current path values
// and increase the opposite of this path
// According to a Lecture graph[u,v]=-graph[v,u]
// we have:
// graph[u,v]-=path_flow
// graph[v,u]+=path_flow
While v <> source do
begin
u:=parent[v];
dec(graph[u,v],path_flow);
inc(graph[v,u],path_flow);
v:=parent[v];
end;
end;
// return our maximum flow
FordFulkerson:=max_flow;
End;
Var
graph: TMatrAdj; // adjacency matrix
n,source,sink:integer;
Begin
Input(graph,n,'input.txt');
Output(graph,n);
source:=1;
sink:=n;
write('The maximum possible flow is ',FordFulkerson(graph,n,source,sink));
End.
|
unit HTMLParserTests;
interface
uses
TestFramework, DomCore;
type
THtmlParserTests = class(TTestCase)
published
procedure TestCreateHtmlDocument;
procedure TestParseString;
procedure TestParseString_Html4Transitional;
procedure TestParseString_Html5;
procedure TestParseString_TrailingTextAddedToBody;
procedure TestParseString_TrailingTextAddedToBodyNewTextNode;
procedure TestParseString_TrailingText_Fails;
procedure TestParseString_CanReadAttributeValues;
procedure TestParseString_AttrValueIsSameAsNodeValue;
procedure TestParseString_DocTypes;
procedure TestParseString_DocTypes_LegacyAppCompat;
procedure TestParseString_FailsToParse;
procedure TestParseString_NodesAfterHtml;
procedure TestInvalidFirstCharacterOfTagName;
procedure TestNewHtmlDocumentHasHeadAndBody;
procedure TestCustomElement;
end;
THtmlFormatterTests = class(TTestCase)
published
procedure TestGetHtml;
procedure TestGetHtml_IncludesDocType;
procedure TestAmpersandNotAlwaysEscaped;
procedure TestCrashParser;
end;
implementation
uses
Html4Parser, HtmlParser, Formatter;
type
TObjectHolder = class(TInterfacedObject)
private
FValue: TObject;
public
constructor Create(AObject: TObject);
destructor Destroy; override;
end;
function AutoFree(AObject: TObject): IUnknown;
begin
if AObject <> nil then
Result := TObjectHolder.Create(AObject)
else
Result := nil;
end;
{ THtmlParserTests }
procedure THtmlParserTests.TestCreateHtmlDocument;
var
doc: TDocument;
begin
//The simple DOMImplementation class function to make us a new empty html document
doc := DOMImplementation.createHtmlDocument('');
AutoFree(doc);
CheckTrue(doc <> nil);
end;
procedure THtmlParserTests.TestInvalidFirstCharacterOfTagName;
var
s: string;
doc: TDocument;
begin
(*
https://html.spec.whatwg.org/#parsing
invalid-first-character-of-tag-name
This error occurs if the parser encounters a code point that is not an ASCII alpha
where first code point of a start tag name or an end tag name is expected.
If a start tag was expected such code point and a preceding U+003C (<) is treated as
text content, and all content that follows is treated as markup.
Whereas, if an end tag was expected, such code point and all content that follows up
to a U+003E (>) code point (if present) or to the end of the input stream is treated
as a comment.
For example, consider the following markup:
<42></42>
This will be parsed into:
html
- head
- body
- #text: <42>
- #comment: 42
*)
doc := THtmlParser.Parse(s);
end;
procedure THtmlParserTests.TestNewHtmlDocumentHasHeadAndBody;
var
doc: TDocument;
begin
{
Spec has a DOMImplementation.CreateHtmlDocument(title?) method,
and it creates a head a body node automatically.
In fact, if you parse an empty string as html, you will still still
a document with HEAD and BODY elements.
}
doc := DOMImplementation.CreateHtmlDocument;
AutoFree(doc);
CheckTrue(doc <> nil);
CheckTrue(doc.Head <> nil);
CheckTrue(doc.Body <> nil);
end;
procedure THtmlParserTests.TestParseString;
var
szHtml: string;
doc: TDocument;
begin
szHtml := '<HTML><BODY>Hello, world!</BODY></HTML>';
doc := THtmlParser.Parse(szHtml);
CheckTrue(doc <> nil);
AutoFree(doc);
Status(DumpDOM(doc));
{
HTML
BODY
#text: "Hello, world!"
}
CheckEquals(1, doc.ChildNodes.Length);
end;
procedure THtmlParserTests.TestParseString_AttrValueIsSameAsNodeValue;
var
doc: TDocument;
span: TElement;
attr: TAttr;
begin
{
If you have an ATTRIBUTE (TAttr) node, then
attr.NodeName === attr.Name
attr.NodeValue === attr.Value
In other words:
attr.NodeName is an alias of attr.Name
attr.NodeValue is an alias of attr.Value
Which HTMLParser fails.
}
doc := THtmlParser.Parse('<SPAN id="st">Hello, world!</SPAN');
CheckTrue(doc <> nil);
Status(#13#10+'DOM tree'+#13#10+'----------'+DumpDOM(doc));
span := doc.getElementById('st') as TElement;
CheckTrue(span <> nil);
attr := span.Attributes.getNamedItem('id') as TAttr;
CheckTrue(attr <> nil);
CheckEquals(attr.name, attr.NodeName);
CheckEquals(attr.value, attr.NodeValue);
end;
procedure THtmlParserTests.TestParseString_CanReadAttributeValues;
var
szHtml: string;
doc: TDocument;
st: TElement;
begin
szHtml :=
'<html>'+#13#10+
'<body>'+#13#10+
'<div id="st">'+#13#10+
'</div>'+#13#10+
'</body>'+#13#10+
'</html>';
doc := THtmlParser.Parse(szHtml);
CheckTrue(doc <> nil);
Status(#13#10+'DOM tree'+#13#10+'----------'+DumpDOM(doc));
st := doc.getElementById('st');
CheckTrue(st <> nil);
CheckEquals('st', st.getAttribute('id'));
end;
procedure THtmlParserTests.TestParseString_DocTypes;
procedure t(const DocType, ExpectedName, ExpectedPublicID, ExpectedSystemID: TDomString);
var
doc: TDocument;
begin
doc := THtmlParser.Parse(DocType+'<HTML/>');
CheckTrue(doc <> nil);
Status(DumpDOM(doc));
CheckNotNull(doc.DocType, 'doc.DocType');
if doc.DocType = nil then
Exit;
CheckEquals(ExpectedName, doc.DocType.NodeName, DocType);
CheckEquals(ExpectedPublicID, doc.DocType.PublicID, DocType);
CheckEquals(ExpectedSystemID, doc.DocType.SystemID, DocType);
end;
begin
{ Recommended list of Doctype declarations
https://www.w3.org/QA/2002/04/valid-dtd-list.html
}
// HTML 5:
t('<!DOCTYPE html>', 'html', '', '');
t('<!DOCTYPE HTML>', 'html', '', ''); //doctype names should be converted to lowercase during parsing
t('<!doctype html>', 'html', '', ''); //doctype keyword is case insensitive
t('<!dOcTyPe html>', 'html', '', ''); //doctype keyword is case insensitive
// HTML 4.01
t('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html',
'-//W3C//DTD HTML 4.01//EN',
'http://www.w3.org/TR/html4/strict.dtd');
t('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html',
'-//W3C//DTD HTML 4.01 Transitional//EN',
'http://www.w3.org/TR/html4/loose.dtd');
t('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
'html',
'-//W3C//DTD HTML 4.01 Frameset//EN',
'http://www.w3.org/TR/html4/frameset.dtd');
// XHTML 1.0
t('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'html',
'-//W3C//DTD XHTML 1.0 Strict//EN',
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
t('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'html',
'-//W3C//DTD XHTML 1.0 Transitional//EN',
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd');
t('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'html',
'-//W3C//DTD XHTML 1.0 Frameset//EN',
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd');
// MathML 2.0
t('<!DOCTYPE math PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">',
'math',
'-//W3C//DTD MathML 2.0//EN',
'http://www.w3.org/Math/DTD/mathml2/mathml2.dtd');
// MathML 1.0
t('<!DOCTYPE math SYSTEM "http://www.w3.org/Math/DTD/mathml1/mathml.dtd">',
'math',
'', //no public - only system
'http://www.w3.org/Math/DTD/mathml1/mathml.dtd');
// SVG 1.1 Full
t('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',
'svg',
'-//W3C//DTD SVG 1.1//EN',
'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd');
end;
procedure THtmlParserTests.TestParseString_DocTypes_LegacyAppCompat;
procedure t(const DocType, ExpectedName, ExpectedPublicID, ExpectedSystemID: TDomString);
var
doc: TDocument;
begin
doc := THtmlParser.Parse(DocType+'<HTML/>');
CheckTrue(doc <> nil);
Status(DumpDOM(doc));
CheckNotNull(doc.DocType, 'doc.DocType');
if doc.DocType = nil then
Exit;
CheckEquals(ExpectedName, doc.DocType.NodeName, DocType);
CheckEquals(ExpectedPublicID, doc.DocType.PublicID, DocType);
CheckEquals(ExpectedSystemID, doc.DocType.SystemID, DocType);
end;
begin
{
HTML 5 legacy appcompat strings
https://html.spec.whatwg.org/#doctype-legacy-string
For the purposes of HTML generators that cannot output HTML markup with the
short DOCTYPE "<!DOCTYPE html>", a DOCTYPE legacy string may be inserted
into the DOCTYPE.
}
t('<!DOCTYPE html SYSTEM "about:legacy-compat">',
'html', '', 'about:legacy-compat');
//Apostrophe character is also allowed
t('<!DOCTYPE html SYSTEM ''about:legacy-compat''>',
'html', '', 'about:legacy-compat');
end;
procedure THtmlParserTests.TestParseString_FailsToParse;
var
szHtml: string;
doc: TDocument;
begin
{
In the past this was a sample HTML page that refused to parse.
}
szHtml :=
'<HTML>'+#13#10+
'<BODY>'+#13#10+
'<IMG HREF="\"'+#13#10+
' tppabs="default.asp?PR=win2000&FR=0&SD=GN&LN=EN-US&">'+#13#10+
' Frequently Asked Questions'+#13#10+
'</A>'+#13#10+
'</BODY>'+#13#10+
'</HTML>';
Status(szHtml);
doc := THtmlParser.Parse(szHtml);
CheckTrue(doc <> nil);
Status(#13#10+'DOM tree'+#13#10+'----------'+DumpDOM(doc));
end;
procedure THtmlParserTests.TestParseString_Html4Transitional;
var
szHtml: string;
doc: TDocument;
begin
szHtml :=
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">'+#13#10+
'<HTML>'+#13#10+
'<BODY>'+#13#10+
'Hello, world!'+#13#10+
'</BODY>'+#13#10+
'</HTML>';
Status(szHtml);
doc := THtmlParser.Parse(szHtml);
CheckTrue(doc <> nil);
Status(DumpDOM(doc));
{
#doctype HTML
HTML
BODY
#text "Hello, world!"
}
CheckEquals(2, doc.ChildNodes.Length, 'Document should have only two top level elements: doctype and html. Known bug that HTML Parser does not eliminate whitespace'); //doctype and html
end;
procedure THtmlParserTests.TestParseString_Html5;
var
szHtml: string;
doc: TDocument;
begin
{
HTML5 doctype breaks processing
https://sourceforge.net/p/htmlp/support-requests/2/
> The unit nicely precesses HTML4 doctype, like
>
> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
>
> But simple HTML5:
>
> <!doctype html>
>
> breaks whole processing, because quote not found.
>
> My quick fix in function THtmlReader.ReadDocumentType:
>
> if (FHtmlStr[FPosition]='"') or (FHtmlStr[FPosition]='''') then // <-- added
> if not ReadQuotedValue(FPublicID) then
> Exit;
}
szHtml :=
'<!doctype html>'+#13#10+
'<HTML>'+#13#10+
'<BODY>'+#13#10+
'Hello, world!'+#13#10+
'</BODY>'+#13#10+
'</HTML>';
doc := THtmlParser.Parse(szHtml);
CheckTrue(doc <> nil);
Status(DumpDOM(doc));
{
#doctype HTML
HTML
BODY
#text "Hello, world!"
}
CheckEquals(2, doc.ChildNodes.Length, 'Document should have only two top level elements: doctype and html. Known bug that HTML Parser does not eliminate whitespace'); //doctype and html
end;
procedure THtmlParserTests.TestParseString_NodesAfterHtml;
var
szHtml: string;
doc: TDocument;
begin
szHtml := '<html><body>Hello, world!</body></html><IMG>';
Status(szHtml);
doc := THtmlParser.Parse(szHtml);
CheckTrue(doc <> nil);
Status(#13#10+'DOM tree'+#13#10+'----------'+DumpDOM(doc));
{
DOM tree should be:
HTML
BODY
#text: "Hello, world!"
BR
#comment: "Comment"
#text: "More text."
IMG
}
CheckEquals(1, doc.ChildNodes.Length);
end;
procedure THtmlParserTests.TestParseString_TrailingTextAddedToBody;
var
szHtml: string;
doc: TDocument;
begin
{
Text added after the body needs to be retroactively added to the end of the body node.
If the last child node of the body is a #text node, then the text is appended to that node's text
}
szHtml :=
'<HTML>'+#13#10+
'<BODY>'+#13#10+
'Hello, world!'+#13#10+
'</BODY>'+#13#10+
'</HTML>'+#13#10+#13#10+
'http://sourceforge.net/projects/htmlp?arg=0';
Status(szHtml);
doc := THtmlParser.Parse(szHtml);
CheckTrue(doc <> nil);
Status(#13#10+
'DOM tree'+#13#10+
'----------'+#13#10+
DumpDOM(doc));
{
HTML
BODY
#text: "Hello, world! http://sourceforge.net/projects/htmlp?arg=0&arg2=0"
}
CheckEquals(1, doc.ChildNodes.Length, 'Document should have only one top level element: html. Known bug that HTML Parser does not move nodes after body to be a child of body');
end;
procedure THtmlParserTests.TestParseString_TrailingTextAddedToBodyNewTextNode;
var
szHtml: string;
doc: TDocument;
begin
{
Text added after the body needs to be retroactively added to the end of the body node.
If the last child node of the body is a #text node, then the text is appended to that node's text
}
szHtml :=
'<HTML>'+#13#10+
'<BODY>'+#13#10+
'Hello, world!<BR>'+#13#10+
'</BODY>'+#13#10+
'</HTML>'+#13#10+#13#10+
'http://sourceforge.net/projects/htmlp?arg=0';
Status(szHtml);
doc := THtmlParser.Parse(szHtml);
CheckTrue(doc <> nil);
Status(#13#10+'DOM tree'+#13#10+'----------'+DumpDOM(doc));
{
HTML
BODY
#text: "Hello, world!"
BR
#text: "http://sourceforge.net/projects/htmlp?arg=0&arg2=0"
}
CheckEquals(1, doc.ChildNodes.Length, 'Document should have only one top level element: html. Known bug that HTML Parser does not add elements after body to the end of body (nor does it consolidate text nodes');
end;
procedure THtmlParserTests.TestParseString_TrailingText_Fails;
var
szHtml: string;
doc: TDocument;
begin
{
From: https://sourceforge.net/p/htmlp/bugs/5/
If a document has plaintext outside html markup,
and that plaintext is a url with args passed to it,
then the doc isn't parsed.
For example, if the plaintext part is sometyhing like this:
http://sourceforge.net/projects/htmlp?arg=0
it works fine. But if it's like this:
http://sourceforge.net/projects/htmlp?arg=0&arg2=0
then it doesn't parse at all.
}
szHtml :=
'<HTML>'+#13#10+
'<BODY>'+#13#10+
'Hello, world!'+#13#10+
'</BODY>'+#13#10+
'</HTML>'+#13#10+#13#10+
'http://sourceforge.net/projects/htmlp?arg=0';
Status(szHtml);
doc := THtmlParser.Parse(szHtml);
CheckTrue(doc <> nil);
Status(#13#10+'DOM tree'+#13#10+'----------'+DumpDOM(doc));
{
HTML
BODY
#text: "Hello, world! http://sourceforge.net/projects/htmlp?arg=0'
}
CheckEquals(1, doc.ChildNodes.Length, 'Document should have only one top level elements: html. Known bug that HTML Parser does not move nodes after body to the end of body');
end;
{ THtmlFormatterTests }
procedure THtmlFormatterTests.TestAmpersandNotAlwaysEscaped;
var
szHtml: string;
doc: TDocument;
const
ExpectedHTML =
'<html>'+#13#10+
'<head></head>'+#13#10+
'<body>'+#13#10+
' <a href="?bill&ted">Bill and Ted</a>'+#13#10+
'</body>'+#13#10+
'</html>';
begin
{
Start: <A href="?bill&ted">Bill and Ted</A>
It is not an error to leave the & unescaped, because &ted; is not a named character reference.
If we parse it, the value of the href attribute is "?bill&ted".
If we get the HTML back, then it should also realize that it doesn't need to escape it:
Bad: <a href="?bill&ted">Bill and Ted</a>
Good: <a href="?bill&ted">Bill and Ted</a>
Correct HTML5
=============
#document
- HTML
- HEAD
- BODY
- A href="?bill&ted"
- #text: "Bill and Ted"
}
szHtml := '<A href="?bill&ted">Bill and Ted</A>';
Status(
'Original HTML'+#13#10+
'-------------'+#13#10+
szHtml);
doc := THtmlParser.Parse(szHtml);
CheckTrue(doc <> nil);
Status(#13#10+
'DOM'+#13#10+
'----------------'+#13#10+
DumpDOM(doc));
//doc/body/a.href
CheckEquals('?bill&ted', TElement(doc.Body.ChildNodes[0]).getAttribute('href'));
CheckEquals('Bill and Ted', doc.Body.ChildNodes[0].ChildNodes[0].NodeValue);
end;
procedure THtmlFormatterTests.TestCrashParser;
var
s: string;
doc: TDocument;
begin
s := '<D';
Status('Original HTML'+#13#10+
'=============');
{
The correct DOM tree for '<D' is:
#document
head
body
And that's it.
Except this exposes a bug in our parser. At the time of parsing the <D, is before
the HTML element.
Line 1: <D
So omit invalid tags if they're before HTML?
Except them if hte 2nd line is <html>:
Line 1: <D
Line 2: <HTML>
then the DOM retroactively does add it to body:
#document
- HEAD
- BODY
- D <html=""
}
doc := THtmlParser.Parse(s);
CheckTrue(doc <> nil);
doc.Free;
end;
procedure THtmlFormatterTests.TestGetHtml;
var
s: string;
doc: TDocument;
begin
s :=
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'+#13#10+
'<html lang="en">'+#13#10+
' <head>'+#13#10+
' <title>Sample page</title>'+#13#10+
' </head>'+#13#10+
' <body>'+#13#10+
' <h1>Sample page</h1>'+#13#10+
' <p>This is a <a href="demo.html">simple</a> sample.</p>'+#13#10+
' <!-- this is a comment -->'+#13#10+
' </body>'+#13#10+
'</html>';
doc := THtmlParser.Parse(s);
try
s := THtmlFormatter.GetHtml(doc);
finally
doc.Free;
end;
Status('Recovered HTML: '+#13#10+s);
CheckTrue(s <> '');
end;
procedure THtmlFormatterTests.TestGetHtml_IncludesDocType;
var
s: string;
doc: TDocument;
begin
s :=
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'+#13#10+
'<html lang="en">'+#13#10+
' <head>'+#13#10+
' <title>Sample page</title>'+#13#10+
' </head>'+#13#10+
' <body>'+#13#10+
' <h1>Sample page</h1>'+#13#10+
' <p>This is a <a href="demo.html">simple</a> sample.</p>'+#13#10+
' <!-- this is a comment -->'+#13#10+
' </body>'+#13#10+
'</html>';
doc := THtmlParser.Parse(s);
try
s := THtmlFormatter.GetHtml(doc);
finally
doc.Free;
end;
Status('Recovered HTML: '+#13#10+s);
CheckTrue(s <> '');
CheckEquals('<!DOCTYPE', Copy(s, 1, 9));
end;
procedure THtmlParserTests.TestCustomElement;
var
html: string;
doc: TDocument;
begin
html := '<oofy>adsfadf</oofy>';
doc := THtmlParser.Parse(html);
CheckTrue(doc <> nil);
AutoFree(doc);
end;
{ TObjectHolder }
constructor TObjectHolder.Create(AObject: TObject);
begin
inherited Create;
FValue := AObject;
end;
destructor TObjectHolder.Destroy;
begin
FValue.Free;
FValue := nil;
inherited;
end;
initialization
TestFramework.RegisterTest('HTMLParser\THtmlParser', THtmlParserTests.Suite);
TestFramework.RegisterTest('HTMLParser\THtmlFormatter', THtmlFormatterTests.Suite);
end.
|
unit UPizzariaControllerImpl;
interface
{$I dmvcframework.inc}
uses MVCFramework,
MVCFramework.Logger,
MVCFramework.Commons,
Web.HTTPApp, UPizzaTamanhoEnum, UPizzaSaborEnum, UEfetuarPedidoDTOImpl;
type
[MVCDoc('Pizzaria backend')]
[MVCPath('/')]
TPizzariaBackendController = class(TMVCController)
public
[MVCDoc('Criar novo pedido "201: Created"')]
[MVCPath('/efetuarPedido')]
[MVCHTTPMethod([httpPOST])]
procedure efetuarPedido(const AContext: TWebContext);
[MVCPath('/consultarpedido/($documento)')]
[MVCHTTPMethod([httpPOST])]
procedure consultarPedido(const AContext: TWebContext);
end;
implementation
uses
System.SysUtils,
Rest.json,
MVCFramework.SystemJSONUtils,
UPedidoServiceIntf,
UPedidoServiceImpl, UPedidoRetornoDTOImpl;
{ TApp1MainController }
procedure TPizzariaBackendController.consultarPedido(const AContext
: TWebContext);
var
oPedidoService: IPedidoService;
oRetornoPedido: TPedidoRetornoDTO;
begin
oPedidoService := TPedidoService.Create;
if Context.Request.Params['documento'].IsEmpty then
raise Exception.Create('Pedido inexistente');
oRetornoPedido := oPedidoService.constultarPedido
(Context.Request.Params['documento']);
end;
procedure TPizzariaBackendController.efetuarPedido(const AContext: TWebContext);
var
oEfetuarPedidoDTO: TEfetuarPedidoDTO;
oPedidoRetornoDTO: TPedidoRetornoDTO;
begin
oEfetuarPedidoDTO := AContext.Request.BodyAs<TEfetuarPedidoDTO>;
try
with TPedidoService.Create do
try
oPedidoRetornoDTO := efetuarPedido(oEfetuarPedidoDTO.PizzaTamanho,
oEfetuarPedidoDTO.PizzaSabor, oEfetuarPedidoDTO.DocumentoCliente);
Render(TJson.ObjectToJsonString(oPedidoRetornoDTO));
finally
oPedidoRetornoDTO.Free
end;
finally
oEfetuarPedidoDTO.Free;
end;
Log.Info('==>Executou o método ', 'efetuarPedido');
end;
end.
|
unit tpStatus; {defines customized panels within a status bar.}
(*
Permission is hereby granted, on 18-Feb-2005, free of charge, to any person
obtaining a copy of this file (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Author of original version of this file: Michael Ax
TtpStatusBar renamed to TtpStatusBar1995 18-Feb-2005
TtpStatusBar2 renamed to TtpStatusBarDateTime1995 18-Feb-2005
*)
interface
uses Forms, Windows, SysUtils, Graphics, TypInfo, ComCtrls, Dialogs, Classes,
Controls, Buttons, ExtCtrls,
utIPCObj, utThread, ucInteg, ucString;
type
TtpNextStatus = Class(TtpThread)
private
fOwner: TStatusBar;
fStrings: TStringList;
ev:TtpEvent;
cs:TtpCriticalSection;
procedure SetStatus(const Value:String);
function GetStatus:String;
Protected
procedure Execute; override;
procedure Synchronized;
public
constructor Create(CreateSuspended:Boolean;aOwner:TStatusBar);
destructor Destroy; override;
property NewStatus:String write SetStatus;
End;
type
TtpStatusBar1995 = class(TStatusBar)
private
fIsHint:boolean;
ftpNextStatus: TtpNextStatus;
function GetStatus:String;
procedure SetStatus(const Value:String);
procedure SetUniqueName(const Value:String);
protected
public
constructor Create(aOwner:TComponent); Override;
destructor Destroy; override;
procedure Loaded; Override;
procedure Flash;
procedure SetTheHint(const Value:String);
procedure SetObjectStatus(Sender:TObject;const Value:String);
property UniqueName:String write SetUniqueName stored false;
published
property Status:String read GetStatus write SetStatus stored false;
end;
type
TMpModes=(mpTime,mpDate);
TtpStatusBarDateTime1995 = class(TtpStatusBar1995)
private
fmpMode: TmpModes;
fTimer: TTimer;
protected
procedure UpdatePanel(Sender: TObject);
procedure SetMpMode(Value:TmpModes);
function GetTimeSlot:String;
procedure SetTimeSlot(const Value:String);
public
constructor Create(aOwner:TComponent); Override;
destructor Destroy; Override;
procedure Click; Override;
published
property TimeSlot:String read GetTimeSlot write SetTimeSlot stored false;
property mpMode: TmpModes read fmpMode write SetMpMode;
end;
procedure Register;
implementation
{---------------------------------------------------------------}
procedure Register;
begin
RegisterComponents('TPack', [TtpStatusBar1995, TtpStatusBarDateTime1995]);
end;
Constructor TtpNextStatus.Create(CreateSuspended: Boolean;aOwner:TStatusBar);
begin
inherited Create(true);
fOwner:=aOwner;
fStrings:=TStringList.Create;
cs:=TtpCriticalSection.Create;
ev:=TtpEvent.CreateNamed('',False); //autoreset
FreeOnTerminate:=True; //this thread will not be destroyed here, it will
//be cleared when it's done running.
if not CreateSuspended then
Resume;
end;
destructor TtpNextStatus.Destroy;
begin
cs.Free;
cs := nil;
ev.Free;
ev := nil;
fStrings.Free;
fStrings := nil;
inherited Destroy;
end;
procedure TtpNextStatus.SetStatus(const Value:String);
begin
with cs,fStrings do try
lock;
Text:=Value; //do not use a buffer right in this rev.
// Add(Value);
finally
unlock;
ev.signal;
end;
//Log('SetNewMail '+inttostr(fMail.count));
end;
function TtpNextStatus.GetStatus:String;
begin
//Log('GetNextMailText');
with cs,fStrings do try
lock;
if Count=0 then
Result:=''
else begin
Result:=Strings[0];
Delete(0);
end;
finally
unlock;
end;
end;
procedure TtpNextStatus.Synchronized;
var
a1:string;
begin //tthread //classes
if terminated
or not assigned(application) //in an app
or application.terminated //app is running
then
exit;
a1:='';
if assigned(fOwner)
then
with fOwner do
if (componentState=[]) //not destroying, reading or writing
or (componentState=[csDesigning]) then
a1:=GetStatus;
if (a1<>'') and (a1[1]='!') then begin
SysUtils.beep;
delete(a1,1,1);
end;
// if a1<>'' then
with fOwner do
if Panels.Count>0 then
Panels[pred(Panels.Count)].Text:=a1;
// Update;
// end;
// else
// SysUtils.beep;
end;
procedure TtpNextStatus.Execute;
var
b: Boolean;
begin
while not terminated do
begin
if assigned(application) //in an app
and (not application.terminated) //app is running
and assigned(fOwner)
and ((fOwner.componentState=[]) //not destroying, reading or writing
or (fOwner.componentState=[csDesigning])) then
b:=true//(fStrings.Count>0)
else
b:=false;
if b then
Self.Synchronize(Synchronized);
if not terminated then
ev.wait(INFINITE);
end;
end;
{----------------------------------------------------------------------}
{----------------------------------------------------------------------}
constructor TtpStatusBar1995.Create(aOwner:TComponent);
begin
inherited Create(aOwner); {sleuth}
ControlStyle:= ControlStyle + [csAcceptsControls];
ShowHint:=True;
if not (csLoading in aOwner.ComponentState) then
UniqueName:='tpStatusBar';
ftpNextStatus:=TtpNextStatus.Create(False,Self);
end;
destructor TtpStatusBar1995.Destroy;
begin
if assigned(fTpNextStatus) then
begin
ftpNextStatus.Terminate;
ftpNextStatus.ev.signal;
{ftpNextStatus.WaitFor is not appropriate here because this is a TtpThread,
not a Delphi TThread. 28-May-2003 AML}
ftpNextStatus:=nil;
end;
inherited Destroy;
end;
procedure TtpStatusBar1995.Loaded;
begin
inherited Loaded;
if Panels.Count=0 then
Panels.Add;
if not (csdesigning in owner.componentstate)
and not assigned(fTpNextStatus) then
begin
ftpNextStatus:=TtpNextStatus.Create(False,Self);
end;
end;
//
procedure TtpStatusBar1995.SetUniqueName(const Value:String);
var
i:integer;
a:string[4];
begin
a:='1';
i:=1;
while true do
if owner.findcomponent(Value+a)=nil then begin
name:= Value+a;
break;
end
else begin
inc(i);
a:=inttostr(i);
end;
end;
function TtpStatusBar1995.GetStatus:String;
begin
if Panels.Count>0 then
Result:=Panels[pred(Panels.Count)].Text
else
Result:='';
end;
procedure TtpStatusBar1995.SetTheHint(const Value:String);
begin
if not fIsHint and (Value='') then
exit;
SetStatus(Value);
fIsHint:=True;
end;
procedure TtpStatusBar1995.SetStatus(const Value:String);
begin
if self=nil then
exit;
fIsHint:=False;
if assigned(fTpNextStatus) then
ftpNextStatus.NewStatus:=Value
else
if Panels.Count>0 then
Panels[pred(Panels.Count)].Text:=Value;
end;
procedure TtpStatusBar1995.Flash;
var
i:integer;
c:tColor;
begin
c:=Color;
for i:=0 to 1 do begin
Color:=tColor(not Color);
Update;
Sleep(16);
end;
Color:=tColor($FFFFFF);
Update;
Sleep(7);
Color:=tColor(random($FFFF) shl 8);
Update;
Sleep(52);
for i:=0 to 1 do begin
Color:=tColor(not Color);
Update;
Sleep(21);
end;
Color:=c;
Update;
end;
procedure TtpStatusBar1995.SetObjectStatus(Sender:TObject;const Value:String);
begin
if not Visible then
exit;
if Sender=nil then
Status:=Value
else
if Sender is tComponent then
Status:=tComponent(Sender).Name+': '+Value
else
Status:=Sender.ClassName+': '+Value;
end;
{}
constructor TtpStatusBarDateTime1995.Create(aOwner:TComponent);
begin
inherited Create(aOwner);
Panels.Add;
fmpMode:=mpTime;
fTimer:=TTimer.Create(self);
with fTimer do
begin
Enabled:=True;
OnTimer:=UpdatePanel;
Interval:=1000;
end;
end;
destructor TtpStatusBarDateTime1995.Destroy;
begin
fTimer.Enabled:=false;
fTimer.Free;
fTimer := nil;
inherited Destroy;
end;
procedure TtpStatusBarDateTime1995.SetMpMode(Value:TMpModes);
begin
if Value<>fmpMode then
begin
fmpMode:=Value;
fTimer.Enabled:=(Value=mpTime);
updatePanel(self);
end;
end;
procedure TtpStatusBarDateTime1995.Click;
begin
if fmpmode<high(tmpmodes) then
mpMode:=succ(fMpMode)
else
mpmode:=low(tmpmodes);
inherited Click;
end;
procedure TtpStatusBarDateTime1995.UpdatePanel(Sender: TObject);
begin
case fmpMode of
mpTime: TimeSlot:= TimeToStr(Time);
mpDate: TimeSlot:= DateToStr(Now);
end;
end;
function TtpStatusBarDateTime1995.GetTimeSlot:String;
begin
if Panels.Count>1 then
Result:=Panels[pred(pred(Panels.Count))].Text
else
Result:='';
end;
procedure TtpStatusBarDateTime1995.SetTimeSlot(const Value:String);
begin
if Panels.Count>1 then
Panels[pred(pred(Panels.Count))].Text:=Value;
end;
end.
|
unit UxlExtDlgs;
interface
uses UxlWinControl, UxlDialog;
function InputBox (const s_caption, s_prompt: widestring; var s_text: widestring; i_icon: cardinal = 0; const s_ok: widestring = ''; const s_cancel: widestring = ''): boolean;
implementation
uses Windows, UxlConst;
//const
// Input_Box = 1017;
// sle_inputtext = 1020;
// st_prompt = 1021;
type TInputBox = class (TxlDialog)
private
FCaption, FPrompt, FInputText, FOK, FCancel: widestring;
FIcon: cardinal;
protected
procedure OnInitialize (); override;
procedure OnOpen (); override;
procedure OnCommand (ctrlID: integer); override;
public
property Caption: widestring write Fcaption;
property Prompt: widestring write FPrompt;
property OK: widestring write FOK;
property Cancel: widestring write FCancel;
property Icon: cardinal write FIcon;
property InputText: widestring read FInputText write FInputText;
end;
procedure TInputBox.OnInitialize ();
begin
SetTemplate (Input_Box);
FIcon := 0;
end;
procedure TInputBox.OnOpen ();
begin
inherited;
if FIcon > 0 then SetIcon (FIcon);
self.text := FCaption;
ItemText[st_prompt] := FPrompt;
ItemText[sle_inputtext] := FInputText;
if FOK <> '' then ItemText[IDOK] := FOK;
if FCancel <> '' then ItemText[IDCANCEL] := FCancel;
FocusControl (sle_inputtext);
end;
procedure TInputBox.OnCommand (ctrlID: integer);
begin
case CtrlID of
IDOK:
begin
FInputText := ItemText[sle_inputtext];
close (true);
end;
IDCancel:
close (false);
end;
end;
function InputBox (const s_caption, s_prompt: widestring; var s_text: widestring; i_icon: cardinal = 0; const s_ok: widestring = ''; const s_cancel: widestring = ''): boolean;
begin
with TInputBox.create () do
begin
Caption := s_caption;
Prompt := s_prompt;
InputText := s_text;
OK := s_ok;
Cancel := s_cancel;
Icon := i_icon;
result := Execute ();
if result then s_text := InputText;
free;
end;
end;
end.
|
unit uAutorizacion;
interface
uses System.SysUtils, System.Classes, System.Hash;
var
CodigoUsuario: String;
function GenerarToken: String; overload;
function GenerarToken(pValue: String): String; overload;
function ValidarTokenUsuario(pAuthorization: String): Boolean;
function ValidarTokenGeneral(pAuthorization: String): Boolean;
function EncriptarContrasena (pPassword : String ) : String;
implementation
uses uDBModulo;
function GenerarToken: String;
var
sKey: String;
begin
try
sKey := DateTimeToStr(date) + 'Examanes';
Result := THashSHA2.GetHMAC(DateTimeToStr(date), sKey, SHA256);
except
on E: Exception do
raise Exception.Create(E.Message);
end;
end;
function GenerarToken(pValue: String): String;
var
sKey: String;
begin
try
sKey := DateTimeToStr(date) + pValue;
Result := THashSHA2.GetHMAC(pValue, sKey, SHA256);
except
on E: Exception do
raise Exception.Create(E.Message);
end;
end;
function ValidarTokenUsuario(pAuthorization: String): Boolean;
begin
Result := False;
try
if DBModulo.Conexion then
begin
try
DBModulo.sqlQuery.Close;
DBModulo.sqlQuery.SQL.Clear;
DBModulo.sqlQuery.SQL.Add
('Select codigousuario from usuario where token=:token');
DBModulo.sqlQuery.ParamByName('token').AsString := pAuthorization;
DBModulo.sqlQuery.Open;
if not DBModulo.sqlQuery.IsEmpty then
begin
Result := True;
CodigoUsuario := DBModulo.sqlQuery.FieldByName
('codigousuario').AsString;
end;
except
on E: Exception do
begin
Result := False;
raise Exception.Create
('No hay autorización para realizar la acción.');
end;
end;
end;
finally
DBModulo.cerrarConexion;
end;
end;
function ValidarTokenGeneral(pAuthorization: String): Boolean;
begin
Result := False;
if GenerarToken = pAuthorization then
Result := True;
end;
function EncriptarContrasena (pPassword : String ) : String;
begin
Result := GenerarToken(pPassword);
end;
end.
|
unit HTTPCallback;
interface
uses
HTTPURI,
HTTPRequest,
HTTPResponse;
type
THTTPRequestCallback = reference to function(const RouteURI: IURI; const Request: IHTTPRequest): IHTTPResponse;
IHTTPCallback = interface
['{7B2BA9CF-C2B3-4394-9702-170FC5372D39}']
function Execute(const RouteURI: IURI; const Request: IHTTPRequest): IHTTPResponse;
end;
THTTPCallback = class sealed(TInterfacedObject, IHTTPCallback)
strict private
_Callback: THTTPRequestCallback;
public
function Execute(const RouteURI: IURI; const Request: IHTTPRequest): IHTTPResponse;
constructor Create(const Callback: THTTPRequestCallback);
class function New(const Callback: THTTPRequestCallback): IHTTPCallback;
end;
implementation
function THTTPCallback.Execute(const RouteURI: IURI; const Request: IHTTPRequest): IHTTPResponse;
begin
if Assigned(_Callback) then
Result := _Callback(RouteURI, Request)
else
Result := nil;
end;
constructor THTTPCallback.Create(const Callback: THTTPRequestCallback);
begin
_Callback := Callback;
end;
class function THTTPCallback.New(const Callback: THTTPRequestCallback): IHTTPCallback;
begin
Result := THTTPCallback.Create(Callback);
end;
end.
|
(* ***************************************************************************
This example program interlaces two bitmap files included in "./data" folder
You can run it like this: ./interlace
Resulting file is saved in same folder.
*************************************************************************** *)
program interlace;
uses
SysUtils, bitmap;
const
{$IFDEF LINUX, UNIX, MACOS}
DIR_BAR = '/';
{$ELSE}
DIR_BAR = '\';
{$ENDIF}
var
fd0 : file of byte;
files: array[0..1] of string = ('data'+DIR_BAR+'fire.bmp', 'data'+DIR_BAR+'fire2.bmp');
tmp : array[0..255] of byte;
lp0 : integer;
procedure do_interlace(const file0, file1: string);
var
bmp0, bmp1: PBitmap;
lpp0, lpp1: integer;
begin
bmp0 := bitmap_load_from_file(file0);
bmp1 := bitmap_load_from_file(file1);
// check if loaded OK
if (bmp0 = nil) or
(bmp1 = nil) then
begin
WriteLn('Could not load bitmap file(s).');
exit;
end;
// input must be 24bpp, and width and height must be the same
if (bmp0^.bpp <> 24) or
(bmp1^.bpp <> 24) or
(bmp0^.width <> bmp1^.width) or
(bmp0^.height <> bmp1^.height) then
begin
WriteLn('Bitmap must be 24 bits per pixel, and dimensions of bitmaps must be the same.');
bitmap_free(bmp0);
bitmap_free(bmp1);
halt(-1);
end;
// interlace bmp1 into bmp0
for lpp0 := 0 to bmp0^.height-1 do
begin
for lpp1 := 0 to (bmp0^.row_len div 4)-1 do // to "scanline size in bytes" div "4"-1
begin
// copy odd rows of bmp1 to odd rows of bmp0
if (lpp0 and $01) = 0 then
break
else
pdword(bmp0^.pixels)[(lpp0*(bmp0^.row_len div 4))+lpp1] := pdword(bmp1^.pixels)[(lpp0*(bmp0^.row_len div 4))+lpp1];
end;
end;
bitmap_free(bmp1);
if bitmap_save_to_file('data'+DIR_BAR+'interlaced.bmp', bmp0) then
WriteLn('Saved to: '+'data'+DIR_BAR+'interlaced.bmp');
bitmap_free(bmp0);
end;
begin
// check if bitmap files are OK
for lp0 := 0 to Length(files)-1 do
begin
if not FileExists(files[lp0]) then
begin
WriteLn('File not found: ',files[lp0]);
halt(-1);
end;
{$i-}
Assign(fd0, files[lp0]);
Reset(fd0);
BlockRead(fd0, tmp, sizeof(tmp));
Close(fd0);
{$i+}
if not bitmap_check(@tmp) then
begin
WriteLn('One of the files is not valid.');
halt(-1);
end;
end;
do_interlace(files[0], files[1]);
end.
|
{******************************************************************************}
{ }
{ SVG Shell Extensions: Shell extensions for SVG files }
{ (Preview Panel, Thumbnail Icon, SVG Editor) }
{ }
{ Copyright (c) 2021 (Ethea S.r.l.) }
{ Author: Carlo Barazzetta }
{ }
{ https://github.com/EtheaDev/SVGShellExtensions }
{ }
{******************************************************************************}
{ }
{ 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. }
{ }
{ The Original Code is: }
{ Delphi Preview Handler https://github.com/RRUZ/delphi-preview-handler }
{ }
{ The Initial Developer of the Original Code is Rodrigo Ruz V. }
{ Portions created by Rodrigo Ruz V. are Copyright 2011-2021 Rodrigo Ruz V. }
{ All Rights Reserved. }
{******************************************************************************}
unit uSVGSettings;
interface
uses
System.SysUtils;
type
TSettings = class
private
FSplitterPos: Integer;
FFontSize: Integer;
FStyleName: string;
FUseDarkStyle: boolean;
FFontName: string;
FShowEditor: Boolean;
FPreferD2D: Boolean;
class function GetSettingsPath: string; static;
class function GetSettingsFileName: string; static;
function GetUseDarkStyle: Boolean;
procedure SetPreferD2D(const Value: Boolean);
public
constructor Create;
class property SettingsFileName: string read GetSettingsFileName;
class property SettingsPath: string read GetSettingsPath;
procedure UpdateSettings(const AFontName: string;
AFontSize: Integer; AEditorVisible: Boolean);
procedure ReadSettings;
procedure WriteSettings;
property UseDarkStyle: Boolean read GetUseDarkStyle;
property FontSize: Integer read FFontSize write FFontSize;
property FontName: string read FFontName write FFontName;
property StyleName: string read FStyleName write FStyleName;
property ShowEditor: Boolean read FShowEditor write FShowEditor;
property SplitterPos: Integer read FSplitterPos write FSplitterPos;
property PreferD2D: Boolean read FPreferD2D write SetPreferD2D;
end;
implementation
uses
IniFiles,
//SVGIconImageList
SVGInterfaces,
PasSVGFactory,
D2DSVGFactory,
System.Types,
System.TypInfo,
System.Rtti,
System.StrUtils,
System.IOUtils,
Winapi.ShlObj,
Winapi.Windows,
Vcl.Themes,
uLogExcept,
uRegistry,
uMisc
;
{ TSettings }
constructor TSettings.Create;
begin
inherited;
ReadSettings;
end;
class function TSettings.GetSettingsFileName: string;
begin
Result := IncludeTrailingPathDelimiter(GetSettingsPath) + 'Settings.ini';
end;
class function TSettings.GetSettingsPath: string;
begin
Result := IncludeTrailingPathDelimiter(GetSpecialFolder(CSIDL_APPDATA)) + 'SVGPreviewHandler\';
System.SysUtils.ForceDirectories(Result);
end;
function TSettings.GetUseDarkStyle: Boolean;
begin
Result := FUseDarkStyle;
end;
procedure TSettings.ReadSettings;
var
Settings: TIniFile;
LIsLightTheme: Boolean;
begin
try
TLogPreview.Add('ReadSettings '+SettingsFileName);
Settings := TIniFile.Create(SettingsFileName);
try
FFontSize := Settings.ReadInteger('Global', 'FontSize', 10);
FFontName := Settings.ReadString('Global', 'FontName', 'Consolas');
FShowEditor := Settings.ReadInteger('Global', 'ShowEditor', 1) = 1;
FSplitterPos := Settings.ReadInteger('Global', 'SplitterPos', 33);
FPreferD2D := Boolean(Settings.ReadInteger('Global', 'PreferD2D', 0));
//Select Style based on Actual Windows Theme
LIsLightTheme := IsWindowsAppThemeLight;
if LIsLightTheme then
begin
FUseDarkStyle := False;
FStyleName := 'Windows10';
//FStyleName := 'Windows';
end
else
begin
FUseDarkStyle := True;
FStyleName := 'Glow';
//FStyleName := 'Windows10 SlateGray';
//FStyleName := 'Windows10 Dark';
//FStyleName := 'Windows';
end;
finally
Settings.Free;
end;
except
on E: Exception do
TLogPreview.Add(Format('Error in TSettings.ReadSettings - Message: %s: Trace %s', [E.Message, E.StackTrace]));
end;
end;
procedure TSettings.SetPreferD2D(const Value: Boolean);
begin
FPreferD2D := Value;
if FPreferD2D then
SetGlobalSvgFactory(GetPasSVGFactory)
else
SetGlobalSvgFactory(GetD2DSVGFactory);
end;
procedure TSettings.UpdateSettings(const AFontName: string;
AFontSize: Integer; AEditorVisible: Boolean);
begin
FontSize := AFontSize;
FontName := AFontName;
StyleName := TStyleManager.ActiveStyle.Name;
ShowEditor := AEditorVisible;
end;
procedure TSettings.WriteSettings;
var
Settings: TIniFile;
begin
try
TLogPreview.Add('WriteSettings '+SettingsFileName);
Settings := TIniFile.Create(SettingsFileName);
try
Settings.WriteInteger('Global', 'FontSize', FFontSize);
Settings.WriteString('Global', 'FontName', FFontName);
Settings.WriteString('Global', 'StyleName', FStyleName);
Settings.WriteInteger('Global', 'ShowEditor', Ord(FShowEditor));
Settings.WriteInteger('Global', 'SplitterPos', FSplitterPos);
Settings.WriteInteger('Global', 'PreferD2D', Ord(FPreferD2D));
finally
Settings.Free;
end;
except
on E: Exception do
TLogPreview.Add(Format('Error in TSettings.WriteSettings - Message: %s: Trace %s', [E.Message, E.StackTrace]));
end;
end;
end.
|
unit Classes.Utils.Consts;
interface
const
// Tabelas
TAB_DEN: string = 'DENUNCIAS';
TAB_DEN_DET: string = 'DENUNCIAS_DETALHE';
TAB_DEN_AT: string = 'DENUNCIAS_ATEND';
TAB_DEN_PROCED: string = 'DENUNCIAS_PROCED';
TAB_DEN_TIP: string = 'TIPODENUNCIA';
TAB_VWDEN: string = 'VW_DENUNCIAS';
TAB_VWHIST: string = 'VW_HISTORICO_DENUNCIA';
TAB_CAMINHO: string = 'CAMINHOBD';
TAB_ARTIGO: string = 'ARTIGOS';
TAB_UNIDADE: string = 'UNIDADES';
TAB_TIPRECEITA: string = 'TIPO_RECEITUARIO';
TAB_RECEITA: string = 'CONTROLE_RECEITUARIOS';
TAB_BAIXA: string = 'BAIXA_RECEITUARIO';
TAB_VWRECEITA: string = 'VW_RECEITAS';
// Campos Individuais
// TABELA DENUNCIAS
TAB_DEN_F1: string = 'COD_DENUNCIA';
TAB_DEN_F2: string = 'ENDERECO';
// -------------------------------------------------
// TABELA DENUNCIAS_DETALHE
TAB_DET_F1: string = 'COD_DETALHE';
TAB_DET_F2: STRING = 'COD_DENUNCIA';
TAB_DET_F3: string = 'COD_TIPDENUNCIA';
TAB_DET_F4: string = 'DATA';
TAB_DET_F5: string = 'OBS';
// -------------------------------------------------
// TABELA DENUNCIAS_ATEND
TAB_AT_F1: string = 'COD_ATEND';
TAB_AT_F2: string = 'COD_DETALHE';
TAB_AT_F3: string = 'DATA';
TAB_AT_F4: string = 'PRAZO';
TAB_AT_F5: string = 'DATA_RET';
TAB_AT_F6: string = 'NUM_INFRACAO';
TAB_AT_F7: string = 'COD_PROCED';
TAB_AT_F8: string = 'OBS';
// -------------------------------------------------
// TABELA DENUNCIAS_PROCED
TAB_PROC_F1: string = 'COD_PROCED';
TAB_PROC_F2: string = 'DESCRICAO';
// -------------------------------------------------
// TABELA TIPODENUNCIA
TAB_TIP_F1: string = 'COD_TIPDENUNCIA';
TAB_TIP_F2: string = 'DESCRICAO';
// -------------------------------------------------
// VIEW VW_DENUNCIAS
VW_DEN_F1: string = 'CODIGO_DETALHE';
VW_DEN_F2: string = 'CODIGO_DENUNCIA';
VW_DEN_F3: string = 'ENDERECO';
VW_DEN_F4: string = 'CODIGO_TIPODENUNCIA';
VW_DEN_F5: string = 'TIPDENUNCIA';
VW_DEN_F6: string = 'DATALANC';
VW_DEN_F7: string = 'OBS';
// -------------------------------------------------
// VIEW VW_HISTORICO_DENUNCIA
VW_HIST_F1: string = 'CODIGO_ATENDIMENTO';
VW_HIST_F2: string = 'CODIGO_TIPODENUNCIA';
VW_HIST_F3: string = 'TIPDENUNCIA';
VW_HIST_F4: string = 'ENDERECO';
VW_HIST_F5: string = 'DATA_ATEND';
VW_HIST_F6: string = 'PRAZO';
VW_HIST_F7: string = 'DATA_RETORNO';
VW_HIST_F8: string = 'PROCEDIMENTO';
// -------------------------------------------------
VW_REC_F6: string = 'COD_RECEITA';
VW_REC_F7: string = 'DATA_LANC';
VW_REC_F9: string = 'NUM_BLOCO';
VW_REC_F10: string = 'NUM_INICIAL';
VW_REC_F11: string = 'NUM_FINAL';
// -------------------------------------------------
// TABELA CAMINHOBD
TAB_CAM_F1: string = 'COD_CAMINHOBD';
TAB_CAM_F2: string = 'DESCRICAO';
TAB_CAM_F3: string = 'CAMINHO_BD';
// -------------------------------------------------
// TABELA ARTIGOS
TAB_ART_F1: string = 'COD_ARTIGO';
TAB_ART_F2: string = 'NUM_ARTIGO';
TAB_ART_F3: string = 'PARAGRAFO';
TAB_ART_F4: string = 'INCISO';
TAB_ART_F5: string = 'DESCRICAO';
// -------------------------------------------------
// TABELA TIPO RECEITAS
TAB_TPREC_F1: string = 'ID_TIPO_RECEITA';
TAB_TPREC_F2: string = 'TIPO_RECEITA';
// -------------------------------------------------
// TABELA UNIDADES
TAB_UNI_F1: string = 'ID_UNIDADE_SAUDE';
TAB_UNI_F2: string = 'UNIDADE_SAUDE';
TAB_UNI_F3: string = 'ENDERECO';
TAB_UNI_F4: string = 'BAIRRO';
TAB_UNI_F5: string = 'TELEFONE';
TAB_UNI_F6: string = 'MEDICO_RESPONSAVEL';
// -------------------------------------------------
TAB_REC_F1: string = 'ID_C_RECEITUARIO';
// Fields
FD_TAB_DEN: string = '(endereco)';
FD_TAB_DET: string = '(cod_denuncia, cod_tipdenuncia, data, obs)';
FD_TAB_AT: string =
'(cod_detalhe, data, prazo, data_ret, num_infracao, cod_proced, obs)';
FD_TAB_PROC: string = '(descricao)';
FD_TAB_TIP: string = '(descricao)';
FD_VWDEN: string = 'codigo_detalhe, endereco, tipdenuncia, datalanc';
FD_TAB_CAMINHO: string = '(descricao, caminho_bd)';
FD_TAB_ART: string = '(num_artigo, paragrafo, inciso, descricao)';
FD_TAB_CTRLREC
: string =
'(id_unidade, medico, id_tipo, qtd_blocos, num_bloco, num_inicial, num_final, data, status, responsavel)';
FD_TAB_BAIXAREC: string = '(id_controle, data, num_bloco, num_inicial, num_final, resp_devolucao)';
// Mensagens
MSG_ATEND: string = 'ATENDIMENTO A DENÚNCIAS';
MSG_ATEND_SUCESSO: string = 'DENÚNCIA ATENDIDA COM SUCESSO!!!';
MSG_ATEND_PRAZO: string = 'CAMPO PRAZO PRECISA RECEBER UM VALOR';
MSG_EXCLUIR: string = 'EXCLUSÃO DE CADASTRO';
MSG_EXCLUIDO: string = 'EXCLUÍDO COM SUCESSO!!!';
MSG_SUCESSO: string = 'SALVO COM SUCESSO!!!';
MSG_INSERIR: string = 'INSERIR REGISTRO NOVO';
MSG_ALTERAR: string = 'ATUALIZAR REGISTRO';
MSG_BAIXADO: string = 'RECEITAS BAIXADAS COM SUCESSO';
// Outros
LISTA: string = ' - LISTA DE DENUNCIAS ';
PROCED: string = ' - LISTA DE PROCEDIMENTOS EM DENÚNCIA';
TIP: string = ' - TIPO DENUNCIA';
AUTOINFRACAO: string = 'AUTO DE INFRAÇÃO';
NOTIFICACAO: string = 'NOTIFICAÇÃO';
LBL: string = 'CONFIGURAÇÕES GERAIS DO SISTEMA';
ARTIGO: string = 'ARTIGOS COD. SANITÁRIO';
BD: string = 'BANCO DE DADOS';
DEN: string = 'CADASTRO DE DENUNCIAS';
PROC: string = 'CADASTRO DE PROCEDIMENTO EM DENÚNCIAS';
REC: string = 'LANÇAMENTO DE RECEITAS';
IMPRIME_REC: string = ' - RECEITAS';
IMPRIME_DEN: string = ' - DENÚNCIAS';
TIPDEN: string = 'TIPOS DE DENÚNCIAS';
TIPREC: string = 'TIPOS DE RECEITAS';
CADNOVO: string = ' -> INSERIR NOVO';
CADALTERA: string = '-> ALTERAR REGISTRO';
ST_ABERTO: string = 'EM ABERTO';
ST_BAIXADO: string = 'BAIXADO';
BAIXA: string = 'BAIXA DE RECEITUÁRIO';
IMPRIMIR: string = 'IMPRESSÃO DE DADOS';
implementation
end.
|
unit SRGrad;
{ TSRGradient (C)opyright 2000 Version 1.21
Autor : Simon Reinhardt
eMail : reinhardt@picsoft.de
Internet : http://www.picsoft.de
Diese Komponente erzeugt einen Farbverlauf. Sie ist abgeleitet
von TGraphicControl und ist Public Domain, das Urheberrecht liegt
aber beim Autor. }
interface
{$I SRDefine.inc}
uses
{$IFDEF SR_Win32} Windows, {$ELSE} WinTypes, WinProcs, {$ENDIF} SysUtils, Messages,
Classes, Graphics, Controls, Forms;
type
TGradDirection = (gdDownRight, gdUpLeft);
TGradStyle = (gsEllipse, gsHorizontal, gsPyramid, gsVertical);
TEndColor = (ecBlack, ecWhite);
TStartColor = (scAqua, scBlue, scFuchsia, scGray, scGreen, scLime, scMaroon,
scNavy, scOlive, scPurple, scRed, scTeal, scWhite, scYellow);
TStepWidth = 1..10;
TSRGradient = class(TGraphicControl)
private
FBC : array[0..255] of Longint;
FBitmap : TBitmap;
FBuffered : boolean;
FDirection : TGradDirection;
FEndColor : TEndColor;
FOldWidth,
FOldHeight : integer;
FStartColor : TStartColor;
FStepWidth : TStepWidth;
FStyle : TGradStyle;
procedure LoadColors;
procedure DrawGradient(ACanvas: TCanvas);
procedure SetBuffered(newValue: boolean);
procedure SetDirection(newValue: TGradDirection);
procedure SetEndColor(newValue: TEndColor);
procedure SetStartColor(newValue: TStartColor);
procedure SetStepWidth(newValue: TStepWidth);
procedure SetStyle(newValue: TGradStyle);
procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_EraseBkgnd;
protected
procedure Paint; override;
public
constructor Create(AComponent: TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
published
property Align;
{$IFDEF SR_Delphi5_Up}
property Anchors;
{$ENDIF}
property Buffered : boolean read FBuffered write SetBuffered;
property Direction : TGradDirection read FDirection write SetDirection;
property EndColor : TEndColor read FEndColor write SetEndColor;
property StartColor : TStartColor read FStartColor write SetStartColor;
property StepWidth : TStepWidth read FStepWidth write SetStepWidth;
property Style : TGradStyle read FStyle write SetStyle;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
procedure Register;
implementation
{$IFDEF SR_Delphi2_Up}
{$R *.D32}
{$ELSE}
{$R *.D16}
{$ENDIF}
procedure TSRGradient.Loaded;
begin
inherited Loaded;
end;
procedure TSRGradient.LoadColors;
var X, Y: Integer;
begin
if ((FDirection = gdDownRight) and (FEndColor=ecBlack)) or
((FDirection = gdUpLeft) and (FEndColor=ecWhite)) then
Y := $FF
else
Y := 0;
if FEndColor=ecBlack then begin
for X := 0 to 255 do begin
case FStartColor of
scAqua : FBC[X] := RGB( 0, Y, Y);
scBlue : FBC[X] := RGB( 0, 0, Y);
scPurple : FBC[X] := RGB( Y div 2, 0, Y div 2);
scGray : FBC[X] := RGB( Y div 2, Y div 2, Y div 2);
scGreen : FBC[X] := RGB( 0, Y div 2, 0);
scLime : FBC[X] := RGB( 0, Y, 0);
scMaroon : FBC[X] := RGB( Y div 2, 0, 0);
scNavy : FBC[X] := RGB( 0, 0, Y div 2);
scOlive : FBC[X] := RGB( Y div 2, Y div 2, 0);
scFuchsia : FBC[X] := RGB( Y, 0, Y);
scRed : FBC[X] := RGB( Y, 0, 0);
scTeal : FBC[X] := RGB( 0, Y div 2, Y div 2);
scWhite : FBC[X] := RGB( Y, Y, Y);
scYellow : FBC[X] := RGB( Y, Y, 0);
end;
if FDirection = gdDownRight then
Dec(Y)
else
Inc(Y);
end;
end
else begin
for X := 0 to 255 do begin
case FStartColor of
scAqua : FBC[X] := RGB( Y, $FF, $FF);
scBlue : FBC[X] := RGB( Y, Y, $FF);
scFuchsia : FBC[X] := RGB( $FF, Y, $FF);
scGray : FBC[X] := RGB( $80+(Y div 2), $80+(Y div 2), $80+(Y div 2));
scGreen : FBC[X] := RGB( Y, $80+(Y div 2), Y);
scLime : FBC[X] := RGB( Y, $FF, Y);
scMaroon : FBC[X] := RGB( $80+(Y div 2), Y, Y);
scNavy : FBC[X] := RGB( Y, Y, $80+(Y div 2));
scOlive : FBC[X] := RGB( $80+(Y div 2), $80+(Y div 2), Y);
scPurple : FBC[X] := RGB( $80+(Y div 2), Y, $80+(Y div 2));
scRed : FBC[X] := RGB( $FF, Y, Y);
scTeal : FBC[X] := RGB( Y, $80+(Y div 2), $80+(Y div 2));
scWhite : FBC[X] := RGB( $FF, $FF, $FF);
scYellow : FBC[X] := RGB( $FF, $FF, Y);
end;
if FDirection = gdDownRight then
Inc(Y)
else
Dec(Y);
end;
end;
end;
procedure TSRGradient.DrawGradient(ACanvas: TCanvas);
var
TempRect : TRect;
TempStepV : Single;
TempStepH : Single;
ColorCode,
TempLeft,
TempTop,
TempHeight,
TempWidth,
ECount,i : integer;
begin
if FBuffered and (FStyle=gsEllipse) then begin
TempRect:=Rect(0,0,Width,Height);
with ACanvas do begin
Brush.Color:=clSilver;
FillRect(TempRect);
end;
end;
if (FStyle=gsHorizontal) or (FStyle=gsVertical) then begin
if FStyle=gsVertical then begin
TempStepH := 1;
TempStepV := Height / 255;
TempHeight := Trunc(TempStepV + 1);
TempWidth := 1;
end
else begin
TempStepH := Width / 255;
TempStepV := 1;
TempHeight := 1;
TempWidth := Trunc(TempStepH + 1);
end;
with ACanvas do begin
TempTop := 0;
TempLeft := 0;
TempRect.Top := 0;
TempRect.Bottom:= Height;
TempRect.Left := 0;
TempRect.Right:= Width;
for ColorCode := 0 to 255 do begin
Brush.Color := FBC[ColorCode];
if FStyle = gsVertical then begin
TempRect.Top := TempTop;
TempRect.Bottom := TempTop + TempHeight;
end
else begin
TempRect.Left := TempLeft;
TempRect.Right:= TempLeft + TempWidth;
end;
FillRect(TempRect);
if FStyle = gsVertical then
TempTop := Trunc(TempStepV * ColorCode)
else
TempLeft := Trunc(TempStepH * ColorCode)
end;
end;
end;
if FStyle=gsEllipse then begin
with ACanvas do begin
TempTop := 1;
TempLeft := 1;
Pen.Width:=1;
ECount:=(Width div 2)-2;
TempStepV:=Height/Width;
TempStepH:=255/ECount;
i:=2;
while i<ECount do begin
ColorCode:=trunc(TempStepH*i);
Pen.Color := FBC[ColorCode];
Brush.Color:=Pen.Color;
Ellipse(TempLeft, TempTop, Width-TempLeft, Height-TempTop);
TempTop := Trunc(TempStepV * i);
TempLeft := i;
i:=i+FStepWidth;
end;
end;
end;
if FStyle=gsPyramid then begin
with ACanvas do begin
TempLeft := Width div 2;
TempTop := Height div 2;
Pen.Width:=FStepWidth;
ECount:=Width+Height;
TempStepH:=255/ECount;
i:=0;
while i<=Width do begin
ColorCode:=trunc(TempStepH*i);
Pen.Color := FBC[ColorCode];
MoveTo(i,0);
LineTo(TempLeft,TempTop);
ColorCode:=trunc(TempStepH*(i+Height));
Pen.Color := FBC[ColorCode];
LineTo(i,Height);
i:=i+FStepWidth;
end;
i:=0;
while i<=Height do begin
ColorCode:=trunc(TempStepH*(i+Width));
Pen.Color := FBC[ColorCode];
MoveTo(Width,i);
LineTo(TempLeft,TempTop);
ColorCode:=trunc(TempStepH*i);
Pen.Color := FBC[ColorCode];
LineTo(0,i);
i:=i+FStepWidth;
end;
end;
end;
end;
procedure TSRGradient.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
Message.Result := 1;
end;
constructor TSRGradient.Create(AComponent: TComponent);
begin
inherited Create(AComponent);
FBuffered := true;
FEndColor := ecBlack;
FDirection := gdDownRight;
FStartColor := scBlue;
FStepWidth := 1;
FStyle := gsVertical;
Width:=100;
Height:=80;
FOldWidth := 0;
FOldHeight := 0;
FBitmap := TBitmap.Create;
LoadColors;
end;
destructor TSRGradient.Destroy;
begin
if FBuffered and assigned(FBitmap) then begin
FBitmap.Free;
FBitmap:=nil;
end;
inherited Destroy;
end;
procedure TSRGradient.SetBuffered(newValue: boolean);
begin
if FBuffered<>newValue then begin
FBuffered:=newValue;
if FBuffered then
FBitmap:=TBitmap.Create;
if not FBuffered and assigned(FBitmap) then begin
FBitmap.Free;
FBitmap:=nil;
end;
FOldWidth:=0;
Invalidate;
end;
end;
procedure TSRGradient.SetDirection(newValue: TGradDirection);
begin
if FDirection<>newValue then begin
FDirection:=newValue;
FOldWidth:=0;
LoadColors;
Invalidate;
end;
end;
procedure TSRGradient.SetEndColor(newValue: TEndColor);
begin
if FEndColor<>newValue then begin
FEndColor:=newValue;
FOldWidth:=0;
LoadColors;
Invalidate;
end;
end;
procedure TSRGradient.SetStartColor(newValue: TStartColor);
begin
if FStartColor<>newValue then begin
FStartColor:=newValue;
FOldWidth:=0;
LoadColors;
Invalidate;
end;
end;
procedure TSRGradient.SetStepWidth(newValue: TStepWidth);
begin
if (FStepWidth<>newValue) and (newValue>=1) and (newValue<=10) then begin
FStepWidth:=newValue;
FOldWidth:=0;
Invalidate;
end;
end;
procedure TSRGradient.SetStyle(newValue: TGradStyle);
begin
if FStyle<>newValue then begin
FStyle:=newValue;
FOldWidth:=0;
Invalidate;
end;
end;
procedure TSRGradient.Paint;
var BmpRect : TRect;
begin
if FBuffered and assigned(FBitmap) then begin
if (FOldWidth<>Width) or (FOldHeight<>Height) then begin
FOldWidth:=Width;
FOldHeight:=Height;
FBitmap.Width:=Width;
FBitmap.Height:=Height;
DrawGradient(FBitmap.Canvas);
end;
if FStyle=gsEllipse then begin
BmpRect:=Rect(0,0,Self.Width-1,Self.Height-1);
with Self.Canvas do begin
Brush.Style:=bsClear;
FillRect(BmpRect);
BrushCopy(BmpRect,FBitmap,BmpRect,clSilver);
end;
end
else
BitBlT(Self.Canvas.Handle,
0,0,Width,Height,
FBitmap.Canvas.Handle,
0,0,SrcCopy);
end
else
DrawGradient(Self.Canvas);
end;
procedure Register;
begin
RegisterComponents('Simon', [TSRGradient]);
end;
end.
|
unit uDM;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, Data.DB, Datasnap.DBClient,
uJsonClass
;
type
TDM = class(TDataModule)
cdsConn: TClientDataSet;
dsConn: TDataSource;
cdsConnDetail: TClientDataSet;
dsConnDetail: TDataSource;
cdsOrder: TClientDataSet;
dsOrder: TDataSource;
cdsOrderDetail: TClientDataSet;
dsOrderDetail: TDataSource;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function DispatchOrder: Boolean;
function EndOrder(AConnID: DWORD; AStatusItem: TStatusItem): Boolean;
function LogOrder(AConnID: DWORD; ALogItem: TLogItem): Boolean;
function AddOrder(AOrderJson: string): Boolean;
function SuspendOrder(AConnID: DWORD): Boolean;
function GetOrder(AConnID: DWORD): string;
function AddSendMachine(AConnID: DWORD; AGroupName: string): Boolean;
function DelSendMachine(AConnID: DWORD): Boolean;
end;
var
DM: TDM;
implementation
uses
System.Variants,
uGlobal;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TDM.DataModuleCreate(Sender: TObject);
begin
cdsConn.Close;
cdsConn.CreateDataSet;
cdsOrder.Close;
cdsOrder.CreateDataSet;
cdsOrderDetail.Close;
cdsOrderDetail.CreateDataSet;
cdsConnDetail.Close;
cdsConnDetail.CreateDataSet;
end;
function TDM.DelSendMachine(AConnID: DWORD): Boolean;
var
dwConnID: Integer;
bFinished: Boolean;
begin
EnterCriticalSection(CS_OP_CDS);
try
try
if not cdsConnDetail.Locate('ConnID', VarArrayOf([AConnID]), []) then Exit;
cdsConn.Delete;
except
end;
finally
LeaveCriticalSection(CS_OP_CDS);
end;
end;
function TDM.AddSendMachine(AConnID: DWORD; AGroupName: string): Boolean;
var
dwConnID: Integer;
bFinished: Boolean;
begin
EnterCriticalSection(CS_OP_CDS);
try
try
cdsConn.DisableControls;
if cdsConn.Locate('ConnID;GroupName', VarArrayOf([AConnID, AGroupName]), []) then Exit;
cdsConn.Append;
cdsConn['ConnID'] := AConnID;
cdsConn['GroupName'] := AGroupName;
cdsConn['OrderNo'] := '';
cdsConn['GameArea'] := '';
cdsConn['GameSvr'] := '';
cdsConn['Account'] := '';
cdsConn['SendMachineState'] := Integer(sms空闲);
cdsConn['TaskState'] := tsNormal;
cdsConn['LogText'] := '';
cdsConn['Interval'] := 0;
cdsConn.Post;
cdsConn.EnableControls;
except
end;
finally
LeaveCriticalSection(CS_OP_CDS);
end;
end;
function TDM.AddOrder(AOrderJson: string): Boolean;
var
iPos: Integer;
Orders: TArray<TOrderItem>;
vRole: TRoleItem;
I: Integer;
bm: TBookmark;
begin
try
if AOrderJson = '' then Exit;
if not TSerizalizes.AsType<TArray<TOrderItem>>(AOrderJson, Orders) then Exit;
if Length(Orders) = 0 then Exit;
EnterCriticalSection(CS_OP_CDS);
try
DM.cdsOrder.DisableControls;
DM.cdsOrderDetail.DisableControls;
for I := Low(Orders) to High(Orders) do
begin
if Length(Orders[i].Roles) = 0 then Continue;
bm := cdsOrder.GetBookmark;
if DM.cdsOrder.Locate('OrderNo;Account', VarArrayOf([Orders[i].OrderNo, Orders[i].Account]), []) then Continue;
//if DM.cdsConn.Locate('OrderNo;Account', VarArrayOf([Orders[i].OrderNo, Orders[i].Account]), []) then Continue;
DM.cdsOrder.Append;
DM.cdsOrder['TaskType'] := Orders[i].TaskType;
DM.cdsOrder['OrderNo'] := Orders[i].OrderNo;
DM.cdsOrder['GameArea'] := Orders[i].GameArea;
DM.cdsOrder['GameSvr'] := Orders[i].GameSvr;
DM.cdsOrder['Account'] := Orders[i].Account;
DM.cdsOrder['PassWord'] := Orders[i].PassWord;
DM.cdsOrder['ConsoleID'] := Orders[i].ConsoleId;
DM.cdsOrder['ReceiptRole'] := Orders[i].ReceiptRole;
DM.cdsOrder['ReceiptRoleLevel'] := Orders[i].receiptLevel;
DM.cdsOrder['CheckLevel'] := Orders[i].CheckLevel;
DM.cdsOrder['SafeWay'] := Orders[i].SafetyWay;
DM.cdsOrder['SaleNum'] := Orders[i].SaleNum;
DM.cdsOrder['Json'] := TSerizalizes.AsJSON<TOrderItem>(Orders[i]);
DM.cdsOrder['IsDoing'] := False;
DM.cdsOrder.Post;
//---
for vRole in Orders[i].Roles do
begin
DM.cdsOrderDetail.Append;
DM.cdsOrderDetail['Account'] := Orders[i].account;
DM.cdsOrderDetail['RowID'] := vRole.RowId;
DM.cdsOrderDetail['IsMain'] := vRole.IsMain;
DM.cdsOrderDetail['RoleID'] := vRole.RoleId;
DM.cdsOrderDetail['RoleName'] := vRole.Role;
DM.cdsOrderDetail['Stock'] := vRole.Stock;
DM.cdsOrderDetail['SendNum'] := vRole.SendNum;
DM.cdsOrderDetail['EachNum'] := vRole.EachNum;
DM.cdsOrderDetail.Post;
end;
end;
finally
cdsOrder.GotoBookmark(bm);
cdsOrder.FreeBookmark(bm);
cdsOrder.EnableControls;
cdsOrderDetail.EnableControls;
LeaveCriticalSection(CS_OP_CDS);
end;
except
AddLogMsg('订单数据处理错误...', [], True);
end;
end;
function TDM.DispatchOrder: Boolean;
var
dwConnID: Integer;
sOrderNo, sAccount, sJson: string;
vOrderItem: TOrderItem;
vRoleItem: TRoleItem;
bm: TBookmark;
begin
if DM.cdsOrder.RecordCount = 0 then Exit;
EnterCriticalSection(CS_OP_CDS);
try
cdsConn.DisableControls;
cdsConnDetail.DisableControls;
try
bm := cdsConn.GetBookmark;
if not DM.cdsConn.Locate('SendMachineState', Integer(sms空闲), []) then Exit;
dwConnID := DM.cdsConn.FieldByName('ConnID').AsInteger;
DM.cdsOrder.First;
while not cdsOrder.Eof do
begin
if not cdsOrder['IsDoing'] then
begin
sJson := DM.cdsOrder.FieldByName('Json').AsString;
if sJson = '' then Exit;
if not TSerizalizes.AsType<TOrderItem>(sJson, vOrderItem) then Exit;
if vOrderItem = nil then Exit;
if Length(vOrderItem.roles) = 0 then Exit;
DM.cdsConn.Edit;
DM.cdsConn['OrderNo'] := vOrderItem.orderNo;
DM.cdsConn['GameArea'] := vOrderItem.gameArea;
DM.cdsConn['GameSvr'] := vOrderItem.gameSvr;
DM.cdsConn['Account'] := vOrderItem.account;
DM.cdsConn['Json'] := sJson;
DM.cdsConn['SendMachineState'] := sms繁忙;
DM.cdsConn['TaskState'] := tsNormal;
DM.cdsConn['LogText'] := '';
DM.cdsConn['Interval'] := GetTickCount;
DM.cdsConn.Post;
for vRoleItem in vOrderItem.roles do
begin
cdsConnDetail.Append;
cdsConnDetail['ConnID'] := dwConnID;
cdsConnDetail['RowID'] := vRoleItem.rowId;
cdsConnDetail['Role'] := vRoleItem.role;
cdsConnDetail['Num'] := vRoleItem.sendNum;
cdsConnDetail['Stock'] := vRoleItem.stock;
cdsConnDetail['LogText'] := '';
cdsConnDetail['State'] := 0;
cdsConnDetail.Post;
end;
//--分配完成后删除订单
cdsOrder.Edit;
cdsOrder['IsDoing'] := True;
cdsOrder.Post;
Break;
end;
cdsOrder.Next;
end;
except
AddLogMsg('分配订单处理错误...', [], True);
end;
finally
cdsConn.GotoBookmark(bm);
cdsConn.FreeBookmark(bm);
cdsConnDetail.EnableControls;
cdsConn.EnableControls;
LeaveCriticalSection(CS_OP_CDS);
end;
end;
//--订单处理完成后, 更新发货机的显示
function TDM.EndOrder(AConnID: DWORD; AStatusItem: TStatusItem): Boolean;
var
dwConnID: Integer;
bFinished: Boolean;
sOrderNo, sAccount: string;
begin
EnterCriticalSection(CS_OP_CDS);
try
try
if not cdsConnDetail.Locate('RowID', AStatusItem.rowId, []) then Exit;
cdsConnDetail['State'] := AStatusItem.state;
cdsConnDetail.First;
bFinished := True;
while not cdsConnDetail.Eof do
begin
if cdsConnDetail['ConnID'] = AConnID then
begin
bFinished := cdsConnDetail['State'] >= 50;
end;
if not bFinished then Break;
cdsConn.Next;
end;
if not bFinished then Exit;
while True do
begin
if not cdsConnDetail.Locate('ConnID', AConnID, []) then
begin
Break;
end;
cdsConnDetail.Delete;
end;
if not cdsConn.Locate('ConnID', AConnID, []) then Exit;
//--删除订单里边的数据
sOrderNo := cdsConn['OrderNo'];
sAccount := cdsConn['Account'];
cdsOrderDetail.First;
while True do
begin
if not cdsOrderDetail.Locate('Account', sAccount, []) then
begin
Break;
end;
cdsOrderDetail.Delete;
end;
cdsOrder.Delete;
DM.cdsConn.Edit;
DM.cdsConn['OrderNo'] := '';
DM.cdsConn['GameArea'] := '';
DM.cdsConn['GameSvr'] := '';
DM.cdsConn['Account'] := '';
DM.cdsConn['SendMachineState'] := sms空闲;
DM.cdsConn['TaskState'] := tsNormal;
DM.cdsConn['LogText'] := '';
DM.cdsConn['Interval'] := 0;
DM.cdsConn['Json'] := '';
DM.cdsConn.Post;
except
end;
finally
LeaveCriticalSection(CS_OP_CDS);
end;
end;
function TDM.GetOrder(AConnID: DWORD): string;
var
dwConnID: Integer;
bFinished: Boolean;
begin
Result := '';
EnterCriticalSection(CS_OP_CDS);
try
try
if not cdsConn.Locate('ConnID', AConnID, []) then Exit;
Result := cdsConn['Json'];
except
end;
finally
LeaveCriticalSection(CS_OP_CDS);
end;
end;
//--订单处理完成后, 更新发货机的显示
function TDM.LogOrder(AConnID: DWORD; ALogItem: TLogItem): Boolean;
var
dwConnID: Integer;
bFinished: Boolean;
begin
EnterCriticalSection(CS_OP_CDS);
try
try
if not cdsConnDetail.Locate('RowID', ALogItem.DetailNo, []) then Exit;
cdsConnDetail['LogText'] := ALogItem.content;
if not cdsConnDetail.Locate('ConnID', AConnID, []) then Exit;
DM.cdsConn.Edit;
DM.cdsConn['LogText'] := ALogItem.content;
DM.cdsConn.Post;
except
end;
finally
LeaveCriticalSection(CS_OP_CDS);
end;
end;
function TDM.SuspendOrder(AConnID: DWORD): Boolean;
var
dwConnID: Integer;
bFinished: Boolean;
begin
EnterCriticalSection(CS_OP_CDS);
try
try
if not cdsConn.Locate('ConnID', AConnID, []) then Exit;
DM.cdsConn.Edit;
cdsConn['ConnID'] := tsSuspend;
DM.cdsConn.Post;
except
end;
finally
LeaveCriticalSection(CS_OP_CDS);
end;
end;
end.
|
unit FusedLayer;
{
Definuje vrstvu, která je spojená z více jiných. Neco jako dynamická mozaika.
}
interface
uses
capabilities_1_1_1, DataDirSupport, TeraWMSTools,
Classes;
type
TFusedLayerBuilder = class
private
procedure ProcessLayerProc(l : IXMLLayerType);
public
FusedLayerList : TStringList;
constructor Create;
destructor Destroy; override;
procedure ProcessCapabilities(c : IXMLWMT_MS_CapabilitiesType);
function IsLayerFused(l : IXMLLayerType) : boolean;
end;
function FusedLayerConfigFileName(LayerName : string) : String;
implementation
uses SysUtils;
const
LAYERFUSIONLIST_FILENAME = 'LayerFusion.txt';
function FusedLayerConfigFileName(LayerName : string) : String;
begin
Result := LayerName + '.txt';
end;
// **************************************************************
// TFusedLayerBuilder
// **************************************************************
constructor TFusedLayerBuilder.Create;
var
s : string;
begin
inherited;
FusedLayerList := TStringList.Create;
FusedLayerList.CaseSensitive := false;
FusedLayerList.Sorted := true;
FusedLayerList.Duplicates := dupIgnore;
s := DataDir + '\' + LAYERFUSIONLIST_FILENAME;
if FileExists(s)
then FusedLayerList.LoadFromFile(s);
end;
destructor TFusedLayerBuilder.Destroy;
begin
FusedLayerList.Free;
inherited;
end;
procedure TFusedLayerBuilder.ProcessCapabilities(c : IXMLWMT_MS_CapabilitiesType);
begin
ProcessLayers(c, ProcessLayerProc);
end;
procedure TFusedLayerBuilder.ProcessLayerProc(l : IXMLLayerType);
var
f : TextFile;
i : integer;
begin
if IsLayerFused(l) then begin
AssignFile(f, DataDir + FusedLayerConfigFileName(l.Name));
try
Rewrite(f);
for i := 0 to l.Layer.Count - 1 do
WriteLn(f, l.Layer.Items[i].Name);
l.Layer.Clear;
l.KeywordList.Add(REPLayerTypeCaptions[rlt_FusedLayer]);
finally
CloseFile(f);
end;
end;
end;
function TFusedLayerBuilder.IsLayerFused(l : IXMLLayerType) : boolean;
var
s : string;
begin
s := GetPath(l) + '\' + l.Title;
Result := FusedLayerList.IndexOf(s) >= 0;
end;
end.
|
unit FormatUtils;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
interface
uses Classes;
{ Converts a file-size in bytes into a string with either decimal or binary
conversion and prefix, maximum is TB or TiB }
function SizeToStr(const Size : Int64; const Binary : Boolean = false) : String;
{ Split a string into multiple parts at the specified delimiters }
procedure Tokenize(const S : String; const Delimiter : String; var List : TStrings);
implementation
uses SysUtils, StrUtils, Math;
function SizeToStr(const Size : Int64; const Binary : Boolean = false) : String;
const
OVERHANG : Real = 0.10;
SYMBOLSDEC : Array [1..5] of String = ('Byte','kB','MB','GB','TB');
SYMBOLSBIN : Array [1..5] of String = ('Byte','KiB','MiB','GiB','TiB');
var
Factor : Integer;
Count : Integer;
Temp : Extended;
begin
if Binary then
Factor := 1024
else
Factor := 1000;
Count := 1;
Temp := Size;
while (Temp > Factor * (1 - OVERHANG)) AND (Count <= High(SYMBOLSDEC)) do
begin
Temp := Temp / Factor;
Inc(Count);
end;
if Count = 1 then
Result := IntToStr(Size)
else
Result := Format('%.2f',[Temp]);
if Binary then
Result := Result + ' ' + SYMBOLSBIN[Count]
else
Result := Result + ' ' + SYMBOLSDEC[Count];
end;
procedure Tokenize(const S : String; const Delimiter : String; var List : TStrings);
var
pre, post : Integer;
begin
pre := 1;
post := Pos(Delimiter,S);
while post > 0 do
begin
List.Add(MidStr(S,pre,post-pre));
pre := post+1;
post := PosEx(Delimiter,S,pre);
end;
List.Add(MidStr(S,pre,Length(S)-pre+1));
end;
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit ormbr.mapping.rttiutils;
interface
uses
Classes,
SysUtils,
Rtti,
DB,
TypInfo,
Math,
StrUtils,
Types,
Variants,
Generics.Collections,
/// orm
ormbr.mapping.attributes,
ormbr.mapping.classes,
ormbr.types.mapping;
type
IRttiSingleton = interface
['{AF40524E-2027-46C3-AAAE-5F4267689CD8}']
function GetRttiType(AClass: TClass): TRttiType;
// function RunValidade(AClass: TClass): Boolean;
function MethodCall(AObject: TObject; AMethodName: string; const AParameters: array of TValue): TValue;
function Clone(AObject: TObject): TObject;
function CreateObject(ARttiType: TRttiType): TObject;
procedure CopyObject(ASourceObject, ATargetObject: TObject);
end;
TRttiSingleton = class(TInterfacedObject, IRttiSingleton)
private
class var
FInstance: IRttiSingleton;
private
FContext: TRttiContext;
constructor CreatePrivate;
public
{ Public declarations }
constructor Create;
destructor Destroy; override;
class function GetInstance: IRttiSingleton;
function GetRttiType(AClass: TClass): TRttiType;
// function RunValidade(AClass: TClass): Boolean;
function MethodCall(AObject: TObject; AMethodName: string; const AParameters: array of TValue): TValue;
function Clone(AObject: TObject): TObject;
function CreateObject(ARttiType: TRttiType): TObject;
procedure CopyObject(ASourceObject, ATargetObject: TObject);
end;
implementation
uses
ormbr.mapping.explorer,
ormbr.rtti.helper;
{ TRttiSingleton }
function TRttiSingleton.Clone(AObject: TObject): TObject;
var
_ARttiType: TRttiType;
Field: TRttiField;
master, cloned: TObject;
Src: TObject;
sourceStream: TStream;
SavedPosition: Int64;
targetStream: TStream;
targetCollection: TObjectList<TObject>;
sourceCollection: TObjectList<TObject>;
I: Integer;
sourceObject: TObject;
targetObject: TObject;
begin
Result := nil;
if not Assigned(AObject) then
Exit;
_ARttiType := FContext.GetType(AObject.ClassType);
cloned := CreateObject(_ARttiType);
master := AObject;
for Field in _ARttiType.GetFields do
begin
if not Field.FieldType.IsInstance then
Field.SetValue(cloned, Field.GetValue(master))
else
begin
Src := Field.GetValue(AObject).AsObject;
if Src is TStream then
begin
sourceStream := TStream(Src);
SavedPosition := sourceStream.Position;
sourceStream.Position := 0;
// if Field.GetValue(cloned).IsEmpty then
if Field.GetValue(cloned).AsType<Variant> = Null then
begin
targetStream := TMemoryStream.Create;
Field.SetValue(cloned, targetStream);
end
else
targetStream := Field.GetValue(cloned).AsObject as TStream;
targetStream.Position := 0;
targetStream.CopyFrom(sourceStream, sourceStream.Size);
targetStream.Position := SavedPosition;
sourceStream.Position := SavedPosition;
end
else if Src is TObjectList<TObject> then
begin
sourceCollection := TObjectList<TObject>(Src);
// if Field.GetValue(cloned).IsEmpty then
if Field.GetValue(cloned).AsType<Variant> = Null then
begin
targetCollection := TObjectList<TObject>.Create;
Field.SetValue(cloned, targetCollection);
end
else
targetCollection := Field.GetValue(cloned).AsObject as TObjectList<TObject>;
for I := 0 to sourceCollection.Count - 1 do
begin
targetCollection.Add(Clone(sourceCollection[I]));
end;
end
else
begin
sourceObject := Src;
// if Field.GetValue(cloned).IsEmpty then
if Field.GetValue(cloned).AsType<Variant> = Null then
begin
targetObject := Clone(sourceObject);
Field.SetValue(cloned, targetObject);
end
else
begin
targetObject := Field.GetValue(cloned).AsObject;
CopyObject(sourceObject, targetObject);
end;
Field.SetValue(cloned, targetObject);
end;
end;
end;
Result := cloned;
end;
procedure TRttiSingleton.CopyObject(ASourceObject, ATargetObject: TObject);
var
_ARttiType: TRttiType;
Field: TRttiField;
master, cloned: TObject;
Src: TObject;
sourceStream: TStream;
SavedPosition: Int64;
targetStream: TStream;
// targetCollection: IWrappedList;
// sourceCollection: IWrappedList;
I: Integer;
sourceObject: TObject;
targetObject: TObject;
Tar: TObject;
begin
if not Assigned(ATargetObject) then
Exit;
_ARttiType := FContext.GetType(ASourceObject.ClassType);
cloned := ATargetObject;
master := ASourceObject;
for Field in _ARttiType.GetFields do
begin
if not Field.FieldType.IsInstance then
Field.SetValue(cloned, Field.GetValue(master))
else
begin
Src := Field.GetValue(ASourceObject).AsObject;
if Src is TStream then
begin
sourceStream := TStream(Src);
SavedPosition := sourceStream.Position;
sourceStream.Position := 0;
// if Field.GetValue(cloned).IsEmpty then
if Field.GetValue(cloned).AsType<Variant> = Null then
begin
targetStream := TMemoryStream.Create;
Field.SetValue(cloned, targetStream);
end
else
targetStream := Field.GetValue(cloned).AsObject as TStream;
targetStream.Position := 0;
targetStream.CopyFrom(sourceStream, sourceStream.Size);
targetStream.Position := SavedPosition;
sourceStream.Position := SavedPosition;
end
// else if TDuckTypedList.CanBeWrappedAsList(Src) then
// begin
// sourceCollection := WrapAsList(Src);
// Tar := Field.GetValue(cloned).AsObject;
// if Assigned(Tar) then
// begin
// targetCollection := WrapAsList(Tar);
// targetCollection.Clear;
// for I := 0 to sourceCollection.Count - 1 do
// targetCollection.Add(TRTTIUtils.Clone(sourceCollection.GetItem(I)));
// end;
// end
else
begin
sourceObject := Src;
// if Field.GetValue(cloned).IsEmpty then
if Field.GetValue(cloned).AsType<Variant> = Null then
begin
targetObject := Clone(sourceObject);
Field.SetValue(cloned, targetObject);
end
else
begin
targetObject := Field.GetValue(cloned).AsObject;
CopyObject(sourceObject, targetObject);
end;
end;
end;
end;
end;
function TRttiSingleton.CreateObject(ARttiType: TRttiType): TObject;
var
Method: TRttiMethod;
metaClass: TClass;
begin
{ First solution, clear and slow }
metaClass := nil;
Method := nil;
for Method in ARttiType.GetMethods do
if Method.HasExtendedInfo and Method.IsConstructor then
if Length(Method.GetParameters) = 0 then
begin
metaClass := ARttiType.AsInstance.MetaclassType;
Break;
end;
if Assigned(metaClass) then
Result := Method.Invoke(metaClass, []).AsObject
else
raise Exception.Create('Cannot find a propert constructor for ' + ARttiType.ToString);
{ Second solution, dirty and fast }
// Result := TObject(ARttiType.GetMethod('Create')
// .Invoke(ARttiType.AsInstance.MetaclassType, []).AsObject);
end;
constructor TRttiSingleton.Create;
begin
raise Exception.Create('Para usar o MappingEntity use o método TRttiSingleton.GetInstance()');
end;
constructor TRttiSingleton.CreatePrivate;
begin
inherited;
FContext := TRttiContext.Create;
end;
destructor TRttiSingleton.Destroy;
begin
FContext.Free;
inherited;
end;
function TRttiSingleton.GetRttiType(AClass: TClass): TRttiType;
begin
Result := FContext.GetType(AClass);
end;
class function TRttiSingleton.GetInstance: IRttiSingleton;
begin
if not Assigned(FInstance) then
FInstance := TRttiSingleton.CreatePrivate;
Result := FInstance;
end;
//function TRttiSingleton.RunValidade(AClass: TClass): Boolean;
//var
// LColumn: TColumnMapping;
// LColumns: TColumnMappingList;
// LAttribute: TCustomAttribute;
//begin
// Result := False;
// LColumns := TMappingExplorer.GetInstance.GetMappingColumn(AClass);
// for LColumn in LColumns do
// begin
// /// <summary>
// /// Valida se o valor é NULO
// /// </summary>
// LAttribute := LColumn.PropertyRtti.GetNotNullConstraint;
// if LAttribute <> nil then
// NotNullConstraint(LAttribute).Validate(LColumn.ColumnName, LColumn.PropertyRtti.GetNullableValue(AClass));
//
// /// <summary>
// /// Valida se o valor é menor que ZERO
// /// </summary>
// LAttribute := LColumn.PropertyRtti.GetZeroConstraint;
// if LAttribute <> nil then
// ZeroConstraint(LAttribute).Validate(LColumn.ColumnName, LColumn.PropertyRtti.GetNullableValue(AClass));
// end;
// Result := True;
//end;
function TRttiSingleton.MethodCall(AObject: TObject; AMethodName: string;
const AParameters: array of TValue): TValue;
var
LRttiType: TRttiType;
LMethod: TRttiMethod;
begin
LRttiType := GetRttiType(AObject.ClassType);
LMethod := LRttiType.GetMethod(AMethodName);
if Assigned(LMethod) then
Result := LMethod.Invoke(AObject, AParameters)
else
raise Exception.CreateFmt('Cannot find method "%s" in the object',[AMethodName]);
end;
end.
|
program _14_27_v;
type
SmallLetters = set of 'a'..'z';
var
lettersEnc, lettersTwice: SmallLetters;
c: Char;
CorrectInput: Boolean;
begin
lettersEnc:= []; lettersTwice:= [];
CorrectInput:= true;
read(c);
while CorrectInput AND (c<>'.') do begin
if (c<'a') OR (c>'z') then CorrectInput:= false
else if c in lettersEnc then Include(lettersTwice,c)
else Include(lettersEnc, c);
read(c);
end;
if CorrectInput then begin
lettersEnc:= lettersEnc-lettersTwice;
for c:='a' to 'z' do
if (c in lettersEnc) then write(c)
end
else write('Error')
end. |
unit HbXMLUtils;
interface
uses
HbTypes,
DOM, XMLRead, sysutils;
function FormatXML(XMLDoc: TXMLDocument): String;
implementation
function FormatXML(XMLDoc: TXMLDocument): String;
function RenderAttributes(pNode: TDOMNode): String;
var
Indice: integer;
begin
Result := '';
if pNode.HasAttributes then begin
for Indice := 0 to pNode.Attributes.Length -1 do begin
with pNode.Attributes[Indice] do begin
Result := Result + Format(' %s="%s"', [NodeName, NodeValue]);
end;
end;
end;
Result := Trim(Result);
end;
function RenderOpenTagWithAttributes(pNode: TDOMNode): String;
begin
Result := '<' + Trim(pNode.NodeName) + RenderAttributes(pNode) + '>';
end;
function RenderCloseTag(pNode: TDOMNode): String;
begin
Result := '<' + Trim(pNode.NodeName) + '/>';
end;
function RenderIndent(IndentLevel: Integer): String;
begin
Result := StringOfChar(' ', IndentLevel * 2);
end;
function ParseXML(XML: String; Node: TDOMNode; Nivel: Integer): String;
function ParseChildNodes(ChildNode: TDOMNode; pNivel: Integer): String;
begin
Result := '';
while ChildNode <> Nil do begin
Result := ParseXML(Result, ChildNode, pNivel);
ChildNode := ChildNode.NextSibling;
end;
end;
function RenderWithChildren(pNode: TDOMNode; pNivel: Integer): String;
function GetNodeValue(NodeValue: String): String;
begin
if Trim(NodeValue) = '' then begin
Result := '';
Exit;
end;
Result := RenderIndent(pNivel + 1) + NodeValue + NEW_LINE;
end;
begin
Result := RenderIndent(pNivel) + RenderOpenTagWithAttributes(pNode) + NEW_LINE +
GetNodeValue(pNode.NodeValue) +
ParseChildNodes(pNode.FirstChild, pNivel + 1) +
RenderIndent(pNivel) + RenderCloseTag(pNode) + NEW_LINE;
end;
function RenderWithoutChildren(pNode: TDOMNode; pNivel: Integer): String;
function GetNodeValue: String;
begin
if pNode.FirstChild <> Nil then begin
Result := pNode.FirstChild.NodeValue;
end else begin
Result := pNode.NodeValue;
end;
end;
begin
Result := RenderIndent(pNivel) + RenderOpenTagWithAttributes(pNode) +
GetNodeValue + RenderCloseTag(pNode) + NEW_LINE;
end;
function NodeHasChildren(pNode: TDOMNode): Boolean;
begin
Result := False;
if pNode.FirstChild <> Nil then begin
if pNode.FirstChild.NodeName[1] <> '#' then begin
Result := True;
end;
end;
end;
function RenderNode(pNode: TDOMNode; pNivel: Integer): String;
begin
if pNode.NodeName[1] = '#' then begin
Result := pNode.NodeValue;
Exit;
end;
if NodeHasChildren(pNode) then begin
Result := RenderWithChildren(pNode, pNivel);
end else begin
Result := RenderWithoutChildren(pNode, pNivel);
end;
end;
begin
Result := XML;
if Node = nil then begin
Exit;
end;
Result := XML + RenderNode(Node, Nivel);
end;
begin
Result := ParseXML('', XMLDoc.DocumentElement, 0);
end;
end.
|
{
Copy Version Control Info inside Record Header between plugins.
Apply script to destination records, then select the source plugin.
Both plugins must have the same masters list, records are matched by FormIDs.
}
unit CopyVCInfo;
var
fromPlugin: IInterface;
//==================================================================================
// list of masters of a plugin
function MastersList(aFile: IInterface): string;
var
masters: IInterface;
i: integer;
begin
masters := ElementByName(ElementByIndex(aFile, 0), 'Master Files');
for i := 0 to Pred(ElementCount(masters)) do
Result := Result + GetElementEditValues(ElementByIndex(masters, i), 'MAST') + #13#10;
end;
//==================================================================================
function Process(e: IInterface): integer;
var
frm: TForm;
clb: TCheckListBox;
i: integer;
r: IInterface;
begin
// plugins selection window for the source plugin to copy from
if not Assigned(fromPlugin) then begin
frm := frmFileSelect;
try
frm.Caption := 'Select plugin to copy from';
frm.Width := 420;
clb := TCheckListBox(frm.FindComponent('CheckListBox1'));
// add files except the current one
for i := 0 to Pred(FileCount) do
if not SameText(GetFileName(e), GetFileName(FileByIndex(i))) then begin
clb.Items.AddObject(GetFileName(FileByIndex(i)), FileByIndex(i));
Inc(i);
end;
// get the first checked file
if frm.ShowModal = mrOk then
for i := 0 to Pred(clb.Items.Count) do
if clb.Checked[i] then begin
fromPlugin := ObjectToElement(clb.Items.Objects[i]);
if not SameText(MastersList(GetFile(e)), MastersList(fromPlugin)) then begin
AddMessage('Masters do not match between plugins!');
fromPlugin := nil;
end;
Break;
end;
// if nothing is checked then abort
if not Assigned(fromPlugin) then begin
Result := 1;
Exit;
end;
finally
frm.Free;
end;
end;
// copy VC info
r := RecordByFormID(fromPlugin, FixedFormID(e), False);
if Assigned(r) then begin
SetFormVCS1(e, GetFormVCS1(r));
SetFormVCS2(e, GetFormVCS2(r));
end;
end;
end.
|
program sieve;
{ Eratos sieve. }
const
VAR_TYPE_SIZE = 16;
SIZE = 1073741823{268435455};
{The array is too long. Need to split, and make something with a hash
like thingie, of pure awesome.
Use the type thingie.. or record?
Create a structure where a amount of arrays is created
and a meta table containg a pointer to the start of the array.
Needed pointer to array
Array where from the key can the start value be calculated
Array of pointers
}
var
x : array[0..SIZE-1] of Int64;
function getbit(e : Int64):Int64;
begin
getbit := (((x[e div VAR_TYPE_SIZE] shr (e mod VAR_TYPE_SIZE)) and 1));
end; { getbit }
procedure setbit(e : Int64);
begin
x[e div VAR_TYPE_SIZE] := x[e div VAR_TYPE_SIZE] or (1 shl (e mod VAR_TYPE_SIZE));
end; { setbit }
procedure clrbit(e : Int64);
begin
x[e div VAR_TYPE_SIZE] := x[e div VAR_TYPE_SIZE] and (not(1 shl (e mod VAR_TYPE_SIZE)));
end; { clrbit }
procedure setall(length : Int64);
var
stoping,k,l : Int64;
begin
stoping := length div VAR_TYPE_SIZE;
k := 0;
while (k < stoping) do
begin
l := 0;
while (l < VAR_TYPE_SIZE) do
begin
x[k] := x[k] or (1 shl l);
inc(l);
end;
inc(k);
end;
end; { setall }
procedure remove_non_primes;
var
i,step,j: Int64;
begin
setall(SIZE);
i := 0;
while ( i < SIZE) do
begin
if getbit(i) = 1 then
begin
step := 2*i+3;
j := ((step*step-3) div 2);
while j < SIZE-1 do
begin
clrbit(j);
j := j + step;
end;
end;
inc(i);
end;
end; { remove_non_primes }
procedure print_primes;
var
i : Int64;
begin
writeln('2 ');
i := 0;
while ( i < SIZE) do
begin
if getbit(i) = 1 then
writeln(2*i+3, ' ');
inc(i);
end;
writeln();
end; { print_primes }
begin
remove_non_primes;
print_primes;
end.
|
unit orm.attributes.types;
interface
type TModeSQL = (msInsert, msUpdate, msDelete, msSelect, msRefresh);
type TFieldType = (ftPrimaryKey, ftAuto, ftNotNull, ftReadOnly, ftInsertOnly, ftUpdateOnly);
type TFieldTypes = Set Of TFieldType;
type TParamType = (ptNone, ptInPut, ptOutPut);
type TParamTypes = Set Of TParamType;
type TObjectType = (otField, otParam, otTable, otForeign, otStoredProc, otFunction, otView);
type TJoin = (jLeft, jInner, jRight);
type TLoad = (lLazy, lEazy);
type TModify = (mNone, mInsert, mUpdate, mDelete);
type TModifys = Set Of TModify;
type TParentType = (ptUnknow, ptField, ptProperty);
implementation
end.
|
unit Utilities;
interface
uses ComCtrls,DB,Classes,SysUtils,Math, ADODB, DBTables,
DBITypes, Definitions, Forms, IniFiles,
xpEdit, xpCheckBox, xpCombo, xpGroupBox, Controls, ExtCtrls,
MAPI, Windows, Dialogs, StdCtrls, Checklst;
{Math utilities}
Function Roundoff(Number : Double;
NumPlaces : Integer) : Double;
{Conversion utilities}
Function BoolToStr(Bool : Boolean) : String;
Function BoolToStr_Blank_Y(Bool : Boolean) : String;
Function VarRecToStr(VarRec : TVarRec) : String;
Function StringToBoolean(sTemp : String) : Boolean;
Function GetAcres(Acres, Frontage, Depth : Double) : Double;
{List view utilities}
Procedure FillInListView( ListView : TListView;
Dataset : TDataset;
const FieldNames : Array of const;
SelectLastItem : Boolean;
ReverseOrder : Boolean); overload;
Procedure FillInListView( ListView : TListView;
Dataset : TDataset;
const FieldNames : Array of const;
const DisplayFormats : Array of String;
SelectLastItem : Boolean;
ReverseOrder : Boolean); overload;
Procedure FillInListViewRow( ListView : TListView;
const Values : Array of const;
SelectLastItem : Boolean;
bChecked : Boolean);
Procedure ChangeListViewRow( ListView : TListView;
const Values : Array of const;
Index : Integer);
Function GetColumnValueForItem(ListView : TListView;
ColumnNumber : Integer;
Index : Integer) : String; {-1 means selected}
Procedure GetColumnValuesForItem(ListView : TListView;
ValuesList : TStringList;
Index : Integer); {-1 means selected}
Procedure SelectListViewItem(ListView : TListView;
RowNumber : Integer);
Procedure DeleteSelectedListViewRow(ListView : TListView);
Procedure FillOneListBox(ListBox : TCustomListBox;
dataSet : TDataSet;
sCodeField,
sDescriptionField : String;
iDescriptionLen : Integer;
bSelectAll,
bIncludeDescription : Boolean);
{String utilities}
Function ForceLength(StringLength : Integer;
SourceString : String): String;
Function _Compare(String1,
String2 : String;
Comparison : Integer) : Boolean; overload;
Function _Compare(Char1,
Char2 : Char;
Comparison : Integer) : Boolean; overload;
Function _Compare( String1 : String;
const ComparisonValues : Array of const;
Comparison : Integer) : Boolean; overload;
Function _Compare(String1 : String;
Comparison : Integer) : Boolean; overload;
Function _Compare(Int1,
Int2 : LongInt;
Comparison : Integer) : Boolean; overload;
Function _Compare( Int1 : LongInt;
const ComparisonValues : Array of const;
Comparison : Integer) : Boolean; overload;
Function _Compare(Real1,
Real2 : Extended;
Comparison : Integer) : Boolean; overload;
Function _Compare(Logical1 : Boolean;
Logical2String : String;
Comparison : Integer) : Boolean; overload;
Function _Compare(DateTime1,
DateTime2 : TDateTime;
Comparison : Integer) : Boolean; overload;
Function StripLeadingAndEndingDuplicateChar(TempStr : String;
CharToStrip : Char) : String;
Procedure ParseCommaDelimitedStringIntoFields(TempStr : String;
FieldList : TStringList;
CapitalizeStrings : Boolean);
Procedure ParseTabDelimitedStringIntoFields(TempStr : String;
FieldList : TStringList;
CapitalizeStrings : Boolean);
Function FormatSQLString(TempStr : String) : String;
Function ShiftRightAddZeroes(SourceStr : String) : String; overload;
Function ShiftRightAddZeroes(SourceStr : String;
StrLength : Integer) : String; overload;
Function IncrementNumericString(sNumericStr : String;
iIncrement : LongInt) : String;
Function StripDescription(sValue : String) : String;
Function AddDescription(sValue : String;
sDescription : String) : String;
Function GetDataInParenthesis(sValue : String) : String;
{ADO utilities}
Procedure _Query( Query : TADOQuery;
const Expression : Array of String);
Procedure _QueryExec( Query : TADOQuery;
const Expression : Array of String);
{Windows utilities}
{I\O utilities}
Function FormatExtractField(TempStr : String) : String;
Procedure WriteCommaDelimitedLine(var ExtractFile : TextFile;
Fields : Array of const);
Procedure WritelnCommaDelimitedLine(var ExtractFile : TextFile;
Fields : Array of const);
Procedure CopyDBaseTable(SourceTable : TTable;
FileName : String);
{DBase table routines}
Function _Locate( Table : TTable;
const KeyFieldValues : Array of const;
IndexName : String;
LocateOptions : TLocateOptions) : Boolean;
Function _SetRange( Table : TTable;
const StartKeyFieldValues : Array of const;
const EndKeyFieldValues : Array of const;
IndexName : String;
LocateOptions : TLocateOptions) : Boolean;
Procedure InitializeFieldsForRecord(Table : TDataset);
Function _InsertRecord( Table : TTable;
const _FieldNames : Array of const;
const _FieldValues : Array of const;
InsertRecordOptions : TInsertRecordOptions) : Boolean;
Function _UpdateRecord( Table : TTable;
const _FieldNames : Array of const;
const _FieldValues : Array of const;
UpdateRecordOptions : TInsertRecordOptions) : Boolean;
Function _SetFilter(Table : TTable;
_Filter : String) : Boolean;
Function _OpenTable(Table : TTable;
_TableName : String;
_DatabaseName : String; {Blank means PASSystem.}
_IndexName : String;
TableOpenOptions : TTableOpenOptions) : Boolean;
Function _OpenTablesForForm(Form : TForm;
TableOpenOptions : TTableOpenOptions) : Boolean;
Procedure _CloseTablesForForm(Form : TForm);
Function SumTableColumn(Table : TTable;
FieldName : String) : Double; overload;
Function SumTableColumn( Table : TTable;
FieldName : String;
const ConditionalFieldNames : Array of String;
const ConditionalValues : Array of const) : Double; overload;
{Ini file routines}
Function LoadIniFile(Form : TForm;
FileName : String;
CreateFileOnNotExist : Boolean) : Boolean;
Function LoadIniFileToStringList(FileName : String;
slComponentNames : TStringList;
slComponentValues : TStringList) : Boolean;
Function SaveIniFile(Form : TForm;
FileName : String;
CreateFileOnNotExist : Boolean) : Boolean;
{General utilities}
Function GetDateTime : String;
Function SendMail(Subject,
Body,
FileName,
SenderName,
SenderEMail,
RecepientName,
RecepientEMail : String;
DisplayError : Boolean) : Integer;
implementation
type
TFindKeyFunction = Function( Table : TTable;
IndexFieldNameList : TStringList;
const Values : Array of const) : Boolean;
{==============================================================================
{Math functions}
{===========================================}
Function Power10(Places : Byte):Double;
{DS: Raise 10 to the indicated power (limited to 0,1,2,3,4,or 5) }
Var
Res : Double;
begin
Res := 0;
{ensure argument is in range...}
If Places > 5 then Places := 5;
Case Places of
0: Res := 1.0;
1: Res := 10.0;
2: Res := 100.0;
3: Res := 1000.0;
4: Res := 10000.0;
5: Res := 100000.0;
end; {case}
Power10 := Res;
end; { Function Power10}
{==================================================================}
Function Roundoff(Number : Double;
NumPlaces : Integer) : Double;
var
I, FirstPlaceAfterDecimalPos, Pos,
DeterminingDigit, DigitInt, ReturnCode : Integer;
Digit : Real;
Answer : Double;
AnswerStr, NumString : String;
AddOne : Boolean;
DigitStr : String;
begin
{They can only round off up to 5 places.}
If (NumPlaces > 6)
then NumPlaces := 6;
Str(Number:14:6, NumString);
NumString := Trim(NumString);
{Find the decimal point.}
Pos := 1;
while ((Pos <= Length(NumString)) and (NumString[Pos] <> '.')) do
Pos := Pos + 1;
FirstPlaceAfterDecimalPos := Pos + 1;
{Now let's look at the place that we need to in order to determine
whether to round up or round down.}
DeterminingDigit := FirstPlaceAfterDecimalPos + NumPlaces;
Val(NumString[DeterminingDigit], DigitInt, ReturnCode);
(*DigitInt := Trunc(Digit);*)
{If the determining digit is >= 5, then round up. Otherwise, round
down.}
If (DigitInt >= 5)
then
begin
AnswerStr := '';
AddOne := True;
{We are rounding up, so first let's add one to the digit to
the left of the determining digit. If it takes us to ten,
continue working to the left until we don't roll over a
digit to ten.}
For I := (DeterminingDigit - 1) downto 1 do
begin
If (NumString[I] = '.')
then AnswerStr := '.' + AnswerStr
else
begin {The character is a digit.}
{FXX05261998-1: Not leaving the negative sign if
this is a negative number.}
If (NumString[I] = '-')
then AnswerStr := '-' + AnswerStr
else
begin
Val(NumString[I], Digit, ReturnCode);
DigitInt := Trunc(Digit);
If AddOne
then DigitInt := DigitInt + 1;
If (DigitInt = 10)
then AnswerStr := '0' + AnswerStr
else
begin
AddOne := False;
Str(DigitInt:1, DigitStr);
AnswerStr := DigitStr + AnswerStr;
end; {else of If (((DigitInt + 1) = 10) and AddOne)}
end; {else of If (NumString[I] = '-')}
end; {else of If (NumString[I] = '.')}
end; {For I := Pos to 1 do}
If AddOne
then AnswerStr := '1' + AnswerStr;
end {If (DigitInt >= 5)}
else AnswerStr := Copy(NumString, 1, (DeterminingDigit - 1));
Val(AnswerStr, Answer, ReturnCode);
Roundoff := Answer;
end; { Function Roundoff....}
{==============================================================================
Conversion utilities
BoolToStr
BoolToStr_Blank_Y
VarRecToStr
==============================================================================}
Function BoolToStr(Bool : Boolean) : String;
begin
If Bool
then Result := 'True'
else Result := 'False';
end; {BoolToStr}
{====================================================}
Function BoolToStr_Blank_Y(Bool : Boolean) : String;
{Return blank for false and Y for true.}
begin
If Bool
then Result := 'Y'
else Result := ' ';
end; {BoolToStr_Blank_Y}
{==============================================================================}
Function VarRecToStr(VarRec : TVarRec) : String;
const
BoolChars : Array[Boolean] of Char = ('F', 'T');
begin
Result := '';
with VarRec do
case VType of
vtInteger : Result := IntToStr(VInteger);
vtBoolean : Result := BoolChars[VBoolean];
vtChar : Result := VChar;
vtExtended : Result := FloatToStr(VExtended^);
vtString : Result := VString^;
vtPChar : Result := VPChar;
vtObject : Result := VObject.ClassName;
vtClass : Result := VClass.ClassName;
vtAnsiString : Result := string(VANSIString);
vtCurrency : Result := CurrToStr(VCurrency^);
vtVariant : Result := string(VVariant^);
vtInt64 : Result := IntToStr(VInt64^);
vtWideString : Result := string(VWideString);
end; {VarRec.VType}
end; {VarRecToStr}
{==============================================================================}
Function StringToBoolean(sTemp : String) : Boolean;
begin
Result := _Compare(sTemp, ['T', 'True', 'Y', '1', 'Yes'], coEqual);
end; {StringToBoolean}
{===========================================================================}
Function GetAcres(Acres, Frontage, Depth : Double) : Double;
begin
If (Acres > 0)
then Result := Roundoff(Acres, 3)
else Result := Roundoff(((Frontage * Depth) / 43560), 3);
end; {GetAcres}
{==============================================================================
List view utilities
FillInListView
FillInListViewRow
ChangeListViewRow
GetColumnValueForItem
GetColumnValuesForItem
SelectListViewItem
DeleteSelectedListViewRow
===============================================================================}
Procedure FillInListView( ListView : TListView;
Dataset : TDataset;
const FieldNames : Array of const;
SelectLastItem : Boolean;
ReverseOrder : Boolean); overload;
{Fill in a TListView from a table using the values of the fields in the order they are passed in.
Note that any select or filter needs to be done prior to calling this procedure.}
var
I : Integer;
Item : TListItem;
Value, FieldName : String;
Done, FirstTimeThrough : Boolean;
begin
FirstTimeThrough := True;
If ReverseOrder
then Dataset.Last
else Dataset.First;
ListView.Enabled := False;
ListView.Items.Clear;
with Dataset do
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else
If ReverseOrder
then Prior
else Next;
If ReverseOrder
then Done := BOF
else Done := EOF;
If not Done
then
begin
with ListView do
Item := Items.Insert(Items.Count);
For I := 0 to High(FieldNames) do
try
FieldName := VarRecToStr(FieldNames[I]);
try
Value := Dataset.FieldByName(FieldName).AsString;
except
Value := '';
end;
case Dataset.FieldByName(FieldName).DataType of
ftDate : If _Compare(Value, coNotBlank)
then
try
Value := FormatDateTime(DateFormat, FieldByName(FieldName).AsDateTime);
except
Value := '';
end;
ftDateTime : If _Compare(FieldName, 'Time', coContains)
then
try
Value := FormatDateTime(TimeFormat, FieldByName(FieldName).AsDateTime);
except
Value := '';
end;
ftBoolean : try
Value := BoolToStr_Blank_Y(Dataset.FieldByName(FieldName).AsBoolean);
except
Value := '';
end;
end; {case Dataset.FieldByName(FieldName).DataType of}
If _Compare(I, 0, coEqual)
then Item.Caption := Value
else Item.SubItems.Add(Value);
except
end;
end; {If not Done}
until Done;
ListView.Enabled := True;
with ListView do
begin
If SelectLastItem
then
try
Selected := Items[SelCount - 1];
except
end;
Refresh;
end; {with ListView do}
end; {FillInListView}
{==============================================================================}
Procedure FillInListView( ListView : TListView;
Dataset : TDataset;
const FieldNames : Array of const;
const DisplayFormats : Array of String;
SelectLastItem : Boolean;
ReverseOrder : Boolean); overload;
{Fill in a TListView from a table using the values of the fields in the order they are passed in.
Note that any select or filter needs to be done prior to calling this procedure.}
var
I : Integer;
Item : TListItem;
Value, FieldName : String;
Done, FirstTimeThrough : Boolean;
begin
FirstTimeThrough := True;
If ReverseOrder
then Dataset.Last
else Dataset.First;
ListView.Enabled := False;
ListView.Items.Clear;
with Dataset do
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else
If ReverseOrder
then Prior
else Next;
If ReverseOrder
then Done := BOF
else Done := EOF;
If not Done
then
begin
with ListView do
Item := Items.Insert(Items.Count);
For I := 0 to High(FieldNames) do
try
FieldName := VarRecToStr(FieldNames[I]);
try
Value := Dataset.FieldByName(FieldName).AsString;
except
Value := '';
end;
case Dataset.FieldByName(FieldName).DataType of
ftDate : If _Compare(Value, coNotBlank)
then
try
Value := FormatDateTime(DateFormat, FieldByName(FieldName).AsDateTime);
except
Value := '';
end;
ftDateTime : If _Compare(FieldName, 'Time', coContains)
then
try
Value := FormatDateTime(TimeFormat, FieldByName(FieldName).AsDateTime);
except
Value := '';
end;
ftBoolean : try
Value := BoolToStr_Blank_Y(Dataset.FieldByName(FieldName).AsBoolean);
except
Value := '';
end;
ftFloat,
ftInteger : try
Value := FormatFloat(DisplayFormats[I], Dataset.FieldByName(FieldName).AsFloat);
except
Value := '';
end;
end; {case Dataset.FieldByName(FieldName).DataType of}
If _Compare(I, 0, coEqual)
then Item.Caption := Value
else Item.SubItems.Add(Value);
except
end;
end; {If not Done}
until Done;
ListView.Enabled := True;
with ListView do
begin
If SelectLastItem
then
try
Selected := Items[SelCount - 1];
except
end;
Refresh;
end; {with ListView do}
end; {FillInListView}
{==============================================================================}
Procedure FillInListViewRow( ListView : TListView;
const Values : Array of const;
SelectLastItem : Boolean;
bChecked : Boolean);
{Fill in a TListView from an array of values in the order they are passed in.}
var
Item : TListItem;
Value : String;
I : Integer;
begin
with ListView do
Item := Items.Insert(Items.Count);
For I := 0 to High(Values) do
try
Value := VarRecToStr(Values[I]);
If _Compare(I, 0, coEqual)
then Item.Caption := Value
else Item.SubItems.Add(Value);
except
end;
Item.Checked := bChecked;
with ListView do
begin
If SelectLastItem
then
try
Selected := Items[SelCount - 1];
except
end;
Refresh;
end; {with ListView do}
end; {FillInListViewRow}
{==============================================================================}
Procedure ChangeListViewRow( ListView : TListView;
const Values : Array of const;
Index : Integer);
{Fill in a TListView from an array of values in the order they are passed in.}
var
Item : TListItem;
Value : String;
I : Integer;
begin
Item := ListView.Items[Index];
For I := 0 to High(Values) do
try
Value := VarRecToStr(Values[I]);
If _Compare(I, 0, coEqual)
then Item.Caption := Value
else Item.SubItems.Add(Value);
except
end;
ListView.Refresh;
end; {FillInListViewRow}
{==============================================================================}
Function GetColumnValueForItem(ListView : TListView;
ColumnNumber : Integer;
Index : Integer) : String; {-1 for selected item}
var
TempItem : TListItem;
begin
Result := '';
If _Compare(Index, -1, coEqual)
then TempItem := ListView.Selected
else
try
TempItem := ListView.Items[Index];
except
TempItem := nil;
end;
If (TempItem <> nil)
then
begin
If _Compare(ColumnNumber, 0, coEqual)
then
try
Result := TempItem.Caption;
except
end
else
try
Result := TempItem.SubItems[ColumnNumber - 1];
except
end;
end; {If (TempItem <> nil)}
end; {GetColumnValueForItem}
{==============================================================================}
Procedure GetColumnValuesForItem(ListView : TListView;
ValuesList : TStringList;
Index : Integer); {-1 means selected}
var
I : Integer;
TempItem : TListItem;
begin
ValuesList.Clear;
If _Compare(Index, -1, coEqual)
then TempItem := ListView.Selected
else
try
TempItem := ListView.Items[Index];
except
TempItem := nil;
end;
with ListView do
For I := 0 to (Columns.Count - 1) do
If _Compare(I, 0, coEqual)
then ValuesList.Add(TempItem.Caption)
else ValuesList.Add(TempItem.SubItems[I - 1]);
end; {GetColumnValuesForItem}
{==============================================================================}
Procedure SelectListViewItem(ListView : TListView;
RowNumber : Integer);
begin
with ListView do
If _Compare(RowNumber, (Items.Count - 1), coLessThanOrEqual)
then
begin
Selected := Items[RowNumber];
Refresh;
end;
end; {SelectListViewItem}
{==============================================================================}
Procedure DeleteSelectedListViewRow(ListView : TListView);
var
Index : Integer;
SelectedItem : TListItem;
ItemDeleted : Boolean;
begin
Index := 0;
ItemDeleted := False;
SelectedItem := ListView.Selected;
with ListView do
while ((not ItemDeleted) and
_Compare(Index, (Items.Count - 1), coLessThanOrEqual)) do
begin
If (Items[Index] = SelectedItem)
then
try
ItemDeleted := True;
Items.Delete(Index);
except
end;
Inc(Index);
end; {while ((not Deleted) and ...}
end; {DeleteSelectedListViewRow}
{==================================================================}
Procedure SelectItemsInCheckListBox(CheckListBox : TCheckListBox);
var
I : Integer;
begin
with CheckListBox do
If (Items.Count > 0)
then
For I := 0 to (Items.Count - 1) do
Checked[I] := True;
end; {SelectItemsInCheckListBox}
{==================================================================}
Procedure SelectItemsInListBox(ListBox : TListBox);
var
I : Integer;
begin
with ListBox do
begin
If (Items.Count > 0)
then
For I := 0 to (Items.Count - 1) do
try
Selected[I] := True;
except
end;
try
TopIndex := 0;
except
end;
end; {with ListBox do}
end; {SelectItemsInListBox}
{==============================================================}
Procedure FillOneListBox(ListBox : TCustomListBox;
dataSet : TDataSet;
sCodeField,
sDescriptionField : String;
iDescriptionLen : Integer;
bSelectAll,
bIncludeDescription : Boolean);
var
sValue : String;
begin
ListBox.Items.Clear;
with dataSet do
begin
First;
while not EOF do
begin
sValue := FieldByName(sCodeField).AsString;
If (bIncludeDescription and
_Compare(FieldByName(sDescriptionField).AsString, coNotBlank))
then sValue := sValue + ' (' +
Copy(FieldByName(sDescriptionField).AsString, 1, iDescriptionLen) + ')';
ListBox.Items.Add(sValue);
Next;
end; {while not EOF do}
end; {with dataSet do}
If bSelectAll
then
begin
If (ListBox is TListBox)
then SelectItemsInListBox(TListBox(ListBox));
If (ListBox is TCheckListBox)
then SelectItemsInCheckListBox(TCheckListBox(ListBox));
end; {If SelectAll}
try
ListBox.TopIndex := 0;
except
end;
end; {FillOneListBox}
{==============================================================================
String functions
ForceLength
_Compare (many versions overloaded)
StripLeadingAndEndingDuplicateChar
ParseCommaDelimitedStringIntoFields
ParseTabDelimitedStringIntoFields
FormatSQLString
ShiftRightAddZeroes
{==============================================================================}
Function ForceLength(StringLength : Integer;
SourceString : String): String;
begin
Result := Copy(SourceString, 1, StringLength);
while (Length(Result) < StringLength) do
Result := Result + ' ';
end; {ForceLength}
{============================================================================}
Function _Compare(String1,
String2 : String;
Comparison : Integer) : Boolean; overload;
{String compare}
var
SubstrLen : Integer;
begin
Result := False;
String1 := ANSIUpperCase(Trim(String1));
String2 := ANSIUpperCase(Trim(String2));
case Comparison of
coEqual : Result := (String1 = String2);
coGreaterThan : Result := (String1 > String2);
coLessThan : Result := (String1 < String2);
coGreaterThanOrEqual : Result := (String1 >= String2);
coLessThanOrEqual : Result := (String1 <= String2);
coNotEqual : Result := (String1 <> String2);
{CHG11251997-2: Allow for selection on blank or not blank.}
coBlank : Result := (Trim(String1) = '');
coNotBlank : Result := (Trim(String1) <> '');
coContains : Result := (Pos(Trim(String2), String1) > 0);
{CHG09111999-1: Add starts with.}
coStartsWith :
begin
String2 := Trim(String2);
SubstrLen := Length(String2);
Result := (ForceLength(SubstrLen, String1) = ForceLength(SubstrLen, String2));
end;
coDoesNotStartWith :
begin
String2 := Trim(String2);
SubstrLen := Length(String2);
Result := (ForceLength(SubstrLen, String1) <> ForceLength(SubstrLen, String2));
end;
coMatchesOrFirstItemBlank :
begin
If _Compare(String1, coBlank)
then Result := True
else Result := _Compare(String1, String2, coEqual);
end; {coMatchesOrFirstItemBlank}
coMatchesPartialOrFirstItemBlank :
begin
If _Compare(String1, coBlank)
then Result := True
else
If (Length(String1) > Length(String2))
then Result := _Compare(String1, String2, coStartsWith)
else Result := _Compare(String2, String1, coStartsWith);
end; {coMatchesPartialOrBlank}
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare(Char1,
Char2 : Char;
Comparison : Integer) : Boolean; overload;
{Character compare}
begin
Result := False;
Char1 := UpCase(Char1);
Char2 := UpCase(Char2);
case Comparison of
coEqual : Result := (Char1 = Char2);
coGreaterThan : Result := (Char1 > Char2);
coLessThan : Result := (Char1 < Char2);
coGreaterThanOrEqual : Result := (Char1 >= Char2);
coLessThanOrEqual : Result := (Char1 <= Char2);
coNotEqual : Result := (Char1 <> Char2);
coBlank : Result := (Char1 = ' ');
coNotBlank : Result := (Char1 <> ' ');
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare( String1 : String;
const ComparisonValues : Array of const;
Comparison : Integer) : Boolean; overload;
{String compare - multiple values}
var
I : Integer;
String2 : String;
begin
Result := False;
String1 := ANSIUpperCase(Trim(String1));
For I := 0 to High(ComparisonValues) do
try
String2 := ANSIUpperCase(Trim(VarRecToStr(ComparisonValues[I])));
Result := Result or _Compare(String1, String2, Comparison);
except
end;
end; {_Compare}
{============================================================================}
Function _Compare(String1 : String;
Comparison : Integer) : Boolean; overload;
{Special string version for blank \ non blank compare.
Note that the regular string _Compare can be used too if the 2nd string is blank.}
begin
Result := False;
String1 := ANSIUpperCase(Trim(String1));
case Comparison of
coBlank : Result := (Trim(String1) = '');
coNotBlank : Result := (Trim(String1) <> '');
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare(Int1,
Int2 : LongInt;
Comparison : Integer) : Boolean; overload;
{Integer version}
begin
Result := False;
case Comparison of
coEqual : Result := (Int1 = Int2);
coGreaterThan : Result := (Int1 > Int2);
coLessThan : Result := (Int1 < Int2);
coGreaterThanOrEqual : Result := (Int1 >= Int2);
coLessThanOrEqual : Result := (Int1 <= Int2);
coNotEqual : Result := (Int1 <> Int2);
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare( Int1 : LongInt;
const ComparisonValues : Array of const;
Comparison : Integer) : Boolean; overload;
{Integer version}
var
I : Integer;
Int2 : LongInt;
begin
Result := False;
For I := 0 to High(ComparisonValues) do
try
Int2 := StrToInt(VarRecToStr(ComparisonValues[I]));
Result := Result or _Compare(Int1, Int2, Comparison);
except
end;
end; {_Compare}
{============================================================================}
Function _Compare(Real1,
Real2 : Extended;
Comparison : Integer) : Boolean; overload;
{Float version}
begin
Result := False;
case Comparison of
coEqual : Result := (RoundTo(Real1, -4) = RoundTo(Real2, -4));
coGreaterThan : Result := (RoundTo(Real1, -4) > RoundTo(Real2, -4));
coLessThan : Result := (RoundTo(Real1, -4) < RoundTo(Real2, -4));
coGreaterThanOrEqual : Result := (RoundTo(Real1, -4) >= RoundTo(Real2, -4));
coLessThanOrEqual : Result := (RoundTo(Real1, -4) <= RoundTo(Real2, -4));
coNotEqual : Result := (RoundTo(Real1, -4) <> RoundTo(Real2, -4));
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare(Logical1 : Boolean;
Logical2String : String;
Comparison : Integer) : Boolean; overload;
{For booleans only coEqual and coNotEqual apply.}
var
Logical2 : Boolean;
begin
Result := False;
{CHG04102003-3(2.06r): Allow for Yes/No in boolean fields.}
Logical2 := False;
Logical2String := Trim(ANSIUpperCase(Logical2String));
{FXX04292003-1(2.07): Added Yes and Y, but made it so that True and T did not work.}
If ((Logical2String = 'YES') or
(Logical2String = 'Y') or
(Logical2String = 'NO') or
(Logical2String = 'N') or
(Logical2String = 'TRUE') or
(Logical2String = 'T'))
then Logical2 := True;
case Comparison of
coEqual : Result := (Logical1 = Logical2);
coNotEqual : Result := (Logical1 <> Logical2);
end; {case Comparison of}
end; {_Compare}
{============================================================================}
Function _Compare(DateTime1,
DateTime2 : TDateTime;
Comparison : Integer) : Boolean; overload;
{Date \ time version}
begin
Result := False;
case Comparison of
coEqual : Result := (DateTime1 = DateTime2);
coGreaterThan : Result := (DateTime1 > DateTime2);
coLessThan : Result := (DateTime1 < DateTime2);
coGreaterThanOrEqual : Result := (DateTime1 >= DateTime2);
coLessThanOrEqual : Result := (DateTime1 <= DateTime2);
coNotEqual : Result := (DateTime1 <> DateTime2);
end; {case Comparison of}
end; {_Compare}
{===========================================================================}
Function StripLeadingAndEndingDuplicateChar(TempStr : String;
CharToStrip : Char) : String;
begin
Result := TempStr;
If ((Length(Result) > 1) and
(Result[1] = CharToStrip) and
(Result[Length(Result)] = CharToStrip))
then
begin
Delete(Result, Length(Result), 1);
Delete(Result, 1, 1);
end;
end; {StripLeadingAndEndingDuplicateChar}
{===========================================================================}
Procedure ParseCommaDelimitedStringIntoFields(TempStr : String;
FieldList : TStringList;
CapitalizeStrings : Boolean);
var
InEmbeddedQuote : Boolean;
CurrentField : String;
I : Integer;
begin
FieldList.Clear;
InEmbeddedQuote := False;
CurrentField := '';
For I := 1 to Length(TempStr) do
begin
If (TempStr[I] = '"')
then InEmbeddedQuote := not InEmbeddedQuote;
{New field if we have found comma and we are not in an embedded quote.}
If ((TempStr[I] = ',') and
(not InEmbeddedQuote))
then
begin
{If the field starts and ends with a double quote, strip it.}
CurrentField := StripLeadingAndEndingDuplicateChar(CurrentField, '"');
If CapitalizeStrings
then CurrentField := ANSIUpperCase(CurrentField);
FieldList.Add(CurrentField);
CurrentField := StringReplace(CurrentField, #255, '', [rfReplaceAll]);
CurrentField := '';
end
else CurrentField := CurrentField + TempStr[I];
end; {For I := 1 to Length(TempStr) do}
CurrentField := StripLeadingAndEndingDuplicateChar(CurrentField, '"');
If CapitalizeStrings
then CurrentField := ANSIUpperCase(Trim(CurrentField));
CurrentField := StringReplace(CurrentField, #255, '', [rfReplaceAll]);
FieldList.Add(Trim(CurrentField));
end; {ParseCommaDelimitedStringIntoFields}
{===========================================================================}
Procedure ParseTabDelimitedStringIntoFields(TempStr : String;
FieldList : TStringList;
CapitalizeStrings : Boolean);
var
CurrentField : String;
TabPos : Integer;
Done : Boolean;
begin
FieldList.Clear;
CurrentField := '';
Done := False;
while ((not Done) and
(SysUtils.Trim(TempStr) <> '')) do
begin
TabPos := Pos(Chr(9), TempStr);
If (TabPos = 0)
then
begin
Done := True;
CurrentField := TempStr;
end
else
begin
CurrentField := Copy(TempStr, 1, (TabPos - 1));
Delete(TempStr, 1, TabPos);
end;
CurrentField := StripLeadingAndEndingDuplicateChar(CurrentField, '"');
If CapitalizeStrings
then CurrentField := ANSIUpperCase(CurrentField);
CurrentField := StringReplace(CurrentField, #255, '', [rfReplaceAll]);
FieldList.Add(Trim(CurrentField));
CurrentField := '';
end; {while ((not Done) and ...}
end; {ParseTabDelimitedStringIntoFields}
{=======================================================================}
Function FormatSQLString(TempStr : String) : String;
begin
Result := '''' + TempStr + '''';
end;
{===================================================================}
Function Take(len:integer;vec:String): String;
begin
vec:=copy(vec,1,len);
while length(vec)<len do vec:=concat(vec,' ');
take:=vec;
end;
{============================================================================}
Function ShiftRightAddZeroes(SourceStr : String) : String; overload;
var
TempLen : Integer;
begin
TempLen := Length(SourceStr);
Result := SourceStr;
If _Compare(Result, coBlank)
then Result := StringOfChar('0', TempLen)
else
while (Result[TempLen] = ' ') do
begin
Delete(Result, TempLen, 1);
Result := '0' + Result;
end;
end; {ShiftRightAddZeroes}
{============================================================================}
Function ShiftRightAddZeroes(SourceStr : String;
StrLength : Integer) : String; overload;
var
TempLen : Integer;
begin
SourceStr := Take(StrLength, Trim(SourceStr));
TempLen := Length(SourceStr);
If _Compare(SourceStr, coBlank)
then SourceStr := StringOfChar('0', TempLen)
else
while (SourceStr[TempLen] = ' ') do
begin
Delete(SourceStr, TempLen, 1);
SourceStr := '0' + SourceStr;
end;
Result := SourceStr;
end; {ShiftRightAddZeroes}
{===================================================================}
Function IncrementNumericString(sNumericStr : String;
iIncrement : LongInt) : String;
begin
try
Result := IntToStr(StrToInt(sNumericStr) + iIncrement);
except
Result := '';
end;
end; {IncrementNumericString}
{========================================================================}
Function StripDescription(sValue : String) : String;
var
iPos : Integer;
begin
Result := sValue;
iPos := Pos('(', sValue);
If _Compare(iPos, 0, coGreaterThan)
then Result := Trim(Copy(sValue, 1, (iPos - 1)));
end; {StripDescription}
{========================================================================}
Function AddDescription(sValue : String;
sDescription : String) : String;
begin
Result := Trim(sValue);
If _Compare(sDescription, coNotBlank)
then Result := Result + ' (' + Trim(sDescription) + ')';
end; {AddDescription}
{======================================================================== }
Function GetDataInParenthesis(sValue : String) : String;
var
iStartPos, iEndPos : Integer;
begin
Result := '';
iStartPos := Pos('(', sValue);
iEndPos := Pos(')', sValue);
Result := Copy(sValue, (iStartPos + 1), (iEndPos - iStartPos - 1));
end; {GetDataInParenthesis}
{========================================================================
ADO routines.
_Query
_QueryExec
=========================================================================}
Procedure _Query( Query : TADOQuery;
const Expression : Array of String);
var
I : Integer;
begin
with Query.SQL do
begin
Clear;
For I := 0 to High(Expression) do
Add(Expression[I]);
end;
//Query.SQL.SaveToFile('c:\temp2\sql.txt');
try
Query.Open;
except
end;
end; {_Query}
{========================================================================}
Procedure _QueryExec( Query : TADOQuery;
const Expression : Array of String);
var
I : Integer;
begin
with Query.SQL do
begin
Clear;
For I := 0 to High(Expression) do
Add(Expression[I]);
end;
try
Query.ExecSQL;
except
end;
end; {_QueryExec}
{========================================================================
I/O routines.
FormatExtractField
WriteCommaDelimitedLine
WritelnCommaDelimitedLine
CopyDBaseTable
=========================================================================}
Function FormatExtractField(TempStr : String) : String;
begin
{If there is an embedded quote, surrond the field in double quotes.}
If (Pos(',', TempStr) > 0)
then TempStr := '"' + TempStr + '"';
Result := ',' + TempStr;
end; {FormatExtractField}
{==================================================================}
Procedure WriteCommaDelimitedLine(var ExtractFile : TextFile;
Fields : Array of const);
var
I : Integer;
TempStr : String;
begin
For I := 0 to High(Fields) do
begin
GlblCurrentCommaDelimitedField := GlblCurrentCommaDelimitedField + 1;
TempStr := VarRecToStr(Fields[I]);
If (GlblCurrentCommaDelimitedField = 1)
then Write(ExtractFile, TempStr)
else Write(ExtractFile, FormatExtractField(TempStr));
end; {For I := 0 to High(Fields) do}
end; {WriteCommaDelimitedLine}
{==================================================================}
Procedure WritelnCommaDelimitedLine(var ExtractFile : TextFile;
Fields : Array of const);
begin
If (High(Fields) > 0)
then WriteCommaDelimitedLine(ExtractFile, Fields);
Writeln(ExtractFile);
GlblCurrentCommaDelimitedField := 0;
end; {WritelnCommaDelimitedLine}
{=============================================================
DBase Table Routines
=============================================================}
Procedure CopyDBaseTable(SourceTable : TTable;
FileName : String);
{Copy a sort file template to a temporary sort file using BatchMove.}
var
TblDesc: CRTblDesc;
PtrFldDesc, PtrIdxDesc: Pointer;
CursorProp: CURProps;
begin
SourceTable.Open;
Check(DbiGetCursorProps(SourceTable.Handle, CursorProp));
// Allocate memory for field descriptors
PtrFldDesc := AllocMem(SizeOf(FLDDesc) * CursorProp.iFields);
PtrIdxDesc := AllocMem(SizeOf(IDXDesc) * CursorProp.iIndexes);
try
Check(DbiGetFieldDescs(SourceTable.Handle, PtrFldDesc));
Check(DbiGetIndexDescs(SourceTable.Handle, PtrIdxDesc));
FillChar(TblDesc, SizeOf(TblDesc), #0);
with TblDesc do
begin
StrPCopy(szTblName, FileName);
StrCopy(szTblType, CursorProp.szTableType);
iFldCount := CursorProp.iFields;
pfldDesc := PtrFldDesc;
iIdxCount := CursorProp.iIndexes;
pIdxDesc := PtrIdxDesc;
end;
Check(DbiCreateTable(SourceTable.DBHandle, True, TblDesc));
finally
FreeMem(PtrFldDesc);
FreeMem(PtrIdxDesc);
end;
SourceTable.Close;
end; {CopyDBaseTable}
{===================================================}
Function FindKeyDBase( Table : TTable;
IndexFieldNameList : TStringList;
const Values : Array of const) : Boolean;
var
I : Integer;
TempValue : String;
begin
with Table do
begin
SetKey;
For I := 0 to High(Values) do
try
TempValue := VarRecToStr(Values[I]);
FieldByName(IndexFieldNameList[I]).Text := TempValue;
except
end;
Result := GotoKey;
end; {with Table do}
end; {FindKeyDBase}
{===================================================}
Function FindNearestDBase( Table : TTable;
IndexFieldNameList : TStringList;
const Values : Array of const) : Boolean;
var
I : Integer;
begin
Result := True;
with Table do
begin
SetKey;
For I := 0 to High(Values) do
try
FieldByName(IndexFieldNameList[I]).Text := VarRecToStr(Values[I]);
except
end;
GotoNearest;
end; {with Table do}
end; {FindNearestDBase}
{==========================================================================}
Procedure ParseIndexExpressionIntoFields(Table : TTable;
IndexFieldNameList : TStringList);
var
IndexPosition, PlusPos : Integer;
IndexExpression, TempFieldName : String;
begin
IndexFieldNameList.Clear;
IndexPosition := Table.IndexDefs.IndexOf(Table.IndexName);
IndexExpression := Table.IndexDefs[IndexPosition].FieldExpression;
{Strip out the ')', 'DTOS(', 'STR('.}
IndexExpression := StringReplace(IndexExpression, ')', '', [rfReplaceAll, rfIgnoreCase]);
IndexExpression := StringReplace(IndexExpression, 'DTOS(', '', [rfReplaceAll, rfIgnoreCase]);
IndexExpression := StringReplace(IndexExpression, 'TTOS(', '', [rfReplaceAll, rfIgnoreCase]);
IndexExpression := StringReplace(IndexExpression, 'STR(', '', [rfReplaceAll, rfIgnoreCase]);
repeat
PlusPos := Pos('+', IndexExpression);
If (PlusPos > 0)
then TempFieldName := Copy(IndexExpression, 1, (PlusPos - 1))
else TempFieldName := IndexExpression;
IndexFieldNameList.Add(TempFieldName);
If (PlusPos > 0)
then Delete(IndexExpression, 1, PlusPos)
else IndexExpression := '';
until (IndexExpression = '');
end; {ParseIndexExpressionIntoFields}
{==========================================================================}
Function _Locate( Table : TTable;
const KeyFieldValues : Array of const;
IndexName : String;
LocateOptions : TLocateOptions) : Boolean;
{Note that IndexName can be blank if you want to use the current index.}
var
LocateFunction : TFindKeyFunction;
IndexFieldNameList : TStringList;
begin
Table.First;
IndexFieldNameList := TStringList.Create;
LocateFunction := FindKeyDBase;
If (loPartialKey in LocateOptions)
then LocateFunction := FindNearestDBase;
If ((loChangeIndex in LocateOptions) and
(Trim(IndexName) <> ''))
then Table.IndexName := IndexName;
ParseIndexExpressionIntoFields(Table, IndexFieldNameList);
Result := LocateFunction(Table, IndexFieldNameList, KeyFieldValues);
IndexFieldNameList.Free;
end; {_Locate}
{==========================================================================}
Function _SetRange( Table : TTable;
const StartKeyFieldValues : Array of const;
const EndKeyFieldValues : Array of const;
IndexName : String;
LocateOptions : TLocateOptions) : Boolean;
{Note that IndexName can be blank if you want to use the current index.}
var
IndexFieldNameList : TStringList;
TempValue : String;
I : Integer;
begin
Result := True;
IndexFieldNameList := TStringList.Create;
If ((loChangeIndex in LocateOptions) and
(Trim(IndexName) <> ''))
then Table.IndexName := IndexName;
ParseIndexExpressionIntoFields(Table, IndexFieldNameList);
{Now do the set range.}
with Table do
try
CancelRange;
SetRangeStart;
For I := 0 to (IndexFieldNameList.Count - 1) do
FieldByName(IndexFieldNameList[I]).Text := VarRecToStr(StartKeyFieldValues[I]);
SetRangeEnd;
For I := 0 to (IndexFieldNameList.Count - 1) do
begin
If (loSameEndingRange in LocateOptions)
then TempValue := VarRecToStr(StartKeyFieldValues[I])
else TempValue := VarRecToStr(EndKeyFieldValues[I]);
FieldByName(IndexFieldNameList[I]).Text := TempValue;
end; {For I := 0 to (IndexFieldNameList.Count - 1) do}
ApplyRange;
except
Result := False;
end; {with Table do}
IndexFieldNameList.Free;
end; {_SetRange}
{====================================================================}
Procedure InitializeFieldsForRecord(Table : TDataset);
var
I : Integer;
begin
with Table do
For I := 0 to (Fields.Count - 1) do
begin
If (Fields[I].DataType in [ftString])
then
try
Fields[I].Value := '';
except
end;
If (Fields[I].DataType in [ftSmallInt, ftInteger, ftWord,
ftFloat, ftCurrency, ftLargeInt, ftBCD])
then
try
Fields[I].Value := 0;
except
end;
If (Fields[I].DataType = ftBoolean)
then
try
Fields[I].AsBoolean := False;
except
end;
end; {For I := 0 to (Fields.Count) do}
end; {InitializeFieldsForRecord}
{===============================================================}
Function _InsertRecord( Table : TTable;
const _FieldNames : Array of const;
const _FieldValues : Array of const;
InsertRecordOptions : TInsertRecordOptions) : Boolean;
var
I : Integer;
begin
Result := True;
with Table do
try
Insert;
If not (irSuppressInitializeFields in InsertRecordOptions)
then InitializeFieldsForRecord(Table);
For I := 0 to High(_FieldNames) do
try
FieldByName(VarRecToStr(_FieldNames[I])).AsString := VarRecToStr(_FieldValues[I]);
except
end;
If not (irSuppressPost in InsertRecordOptions)
then Post;
except
Cancel;
Result := False;
end;
end; {_InsertRecord}
{===============================================================}
Function _UpdateRecord( Table : TTable;
const _FieldNames : Array of const;
const _FieldValues : Array of const;
UpdateRecordOptions : TInsertRecordOptions) : Boolean;
var
I : Integer;
begin
Result := True;
with Table do
try
Edit;
For I := 0 to High(_FieldNames) do
try
FieldByName(VarRecToStr(_FieldNames[I])).AsString := VarRecToStr(_FieldValues[I]);
except
end;
If not (irSuppressPost in UpdateRecordOptions)
then Post;
except
Cancel;
Result := False;
end;
end; {_UpdateRecord}
{=========================================================================}
Function _SetFilter(Table : TTable;
_Filter : String) : Boolean;
begin
Result := True;
with Table do
try
Filtered := False;
Filter := _Filter;
Filtered := True;
except
Result := False;
end;
end; {_SetFilter}
{==============================================================================}
Function _OpenTable(Table : TTable;
_TableName : String;
_DatabaseName : String; {Blank means PASSystem.}
_IndexName : String;
TableOpenOptions : TTableOpenOptions) : Boolean;
begin
Result := True;
with Table do
try
Close;
TableType := ttDBase;
If not (toOpenAsIs in TableOpenOptions)
then
begin
If _Compare(_DatabaseName, coBlank)
then DatabaseName := 'PASSystem'
else DatabaseName := _DatabaseName;
If _Compare(_IndexName, coNotBlank)
then IndexName := _IndexName;
Exclusive := (toExclusive in TableOpenOptions);
ReadOnly := (toReadOnly in TableOpenOptions);
end; {If not (toOpenAsIs in TableOpenOptions)}
Open;
except
Result := False;
end;
end; {_OpenTable}
{=======================================================================}
Function _OpenTablesForForm(Form : TForm;
TableOpenOptions : TTableOpenOptions) : Boolean;
var
I : Integer;
TableName : String;
begin
Result := True;
with Form do
begin
For I := 1 to (ComponentCount - 1) do
If ((Components[I] is TTable) and
_Compare(TTable(Components[I]).TableName, coNotBlank) and
((not (toNoReOpen in TableOpenOptions)) or
(not TTable(Components[I]).Active)))
then
begin
TableName := TTable(Components[I]).TableName;
If not _OpenTable(TTable(Components[I]), TableName, '', '', TableOpenOptions)
then Result := False;
end; {If ((Components[I] is TTable) and ...}
end; {with Form do}
end; {_OpenTablesForForm}
{================================================================================}
Procedure _CloseTablesForForm(Form : TForm);
{Close all the tables on the form.}
var
I : Integer;
begin
with Form do
For I := 1 to (ComponentCount - 1) do
If (Components[I] is TTable)
then
try
with Components[I] as TTable do
If Active
then Close;
except
end;
end; {CloseTablesForForm}
{===========================================================================}
Function SumTableColumn(Table : TTable;
FieldName : String) : Double; overload;
var
Done, FirstTimeThrough : Boolean;
begin
Done := False;
FirstTimeThrough := True;
Result := 0;
Table.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else Table.Next;
If Table.EOF
then Done := True;
If not Done
then
try
Result := Result + Table.FieldByName(FieldName).AsFloat;
except
end;
until Done;
end; {SumTableColumn}
{===========================================================================}
Function SumTableColumn( Table : TTable;
FieldName : String;
const ConditionalFieldNames : Array of String;
const ConditionalValues : Array of const) : Double; overload;
var
Done, FirstTimeThrough, MeetsConditions : Boolean;
I : Integer;
begin
FirstTimeThrough := True;
Result := 0;
Table.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else Table.Next;
Done := Table.EOF;
If not Done
then
begin
MeetsConditions := True;
For I := 0 to High(ConditionalFieldNames) do
try
If _Compare(Table.FieldByName(ConditionalFieldNames[I]).Text, VarRecToStr(ConditionalValues[I]), coNotEqual)
then MeetsConditions := False;
except
end;
If MeetsConditions
then
try
Result := Result + Table.FieldByName(FieldName).AsFloat;
except
end;
end; {If not Done}
until Done;
end; {SumTableColumn}
{==============================================================================
Ini file routines
LoadIniFile
LoadIniFileToStringList
SaveIniFile
==============================================================================}
Function LoadIniFile(Form : TForm;
FileName : String;
CreateFileOnNotExist : Boolean) : Boolean;
var
_FileExists : Boolean;
I, EqualsPos : Integer;
ComponentName, ComponentValue : String;
IniFile : TIniFile;
SectionValues : TStringList;
Component : TComponent;
begin
Result := True;
_FileExists := FileExists(FileName);
If (_FileExists or
((not _FileExists) and
CreateFileOnNotExist))
then
begin
IniFile := TIniFile.Create(FileName);
SectionValues := TStringList.Create;
IniFile.ReadSectionValues(sct_Components, SectionValues);
For I := 0 to (SectionValues.Count - 1) do
begin
EqualsPos := Pos('=', SectionValues[I]);
ComponentName := Copy(SectionValues[I], 1, (EqualsPos - 1));
ComponentValue := Copy(SectionValues[I], (EqualsPos + 1), 255);
Component := Form.FindComponent(ComponentName);
If (Component <> nil)
then
begin
If (Component is TPanel)
then
try
TPanel(Component).Caption := ComponentValue;
except
end;
If (Component is TXPEdit)
then
try
TXPEdit(Component).Text := ComponentValue;
except
end;
If (Component is TXPComboBox)
then
try
TXPComboBox(Component).Text := ComponentValue;
except
end;
If (Component is TXPCheckBox)
then
try
TXPCheckBox(Component).Checked := _Compare(ComponentValue, 'TRUE', coEqual);
except
end;
end; {If (Component <> nil)}
end; {For I := 0 to (SectionValues.Count - 1) do}
IniFile.Free;
SectionValues.Free;
end {If FileExists(IniFileName)}
else Result := False;
end; {LoadIniFile}
{==============================================================================}
Function LoadIniFileToStringList(FileName : String;
slComponentNames : TStringList;
slComponentValues : TStringList) : Boolean;
var
I, iEqualsPos : Integer;
IniFile : TIniFile;
slSectionValues : TStringList;
begin
Result := True;
slComponentNames.Clear;
slComponentValues.Clear;
If FileExists(FileName)
then
begin
IniFile := TIniFile.Create(FileName);
slSectionValues := TStringList.Create;
IniFile.ReadSectionValues(sct_Components, slSectionValues);
For I := 0 to (slSectionValues.Count - 1) do
begin
iEqualsPos := Pos('=', slSectionValues[I]);
slComponentNames.Add(Copy(slSectionValues[I], 1, (iEqualsPos - 1)));
slComponentValues.Add(Copy(slSectionValues[I], (iEqualsPos + 1), 255));
end; {For I := 0 to (SectionValues.Count - 1) do}
IniFile.Free;
slSectionValues.Free;
end {If FileExists(IniFileName)}
else Result := False;
end; {LoadIniFileToStringList}
{============================================================================}
Function SaveIniFile(Form : TForm;
FileName : String;
CreateFileOnNotExist : Boolean) : Boolean;
var
_FileExists, SaveValue : Boolean;
I : Integer;
ComponentName, ComponentValue : String;
IniFile : TIniFile;
Component : TComponent;
begin
Result := True;
_FileExists := FileExists(FileName);
If (_FileExists or
((not _FileExists) and
CreateFileOnNotExist))
then
begin
IniFile := TIniFile.Create(FileName);
For I := 0 to (Form.ComponentCount - 1) do
begin
Component := Form.Components[I];
ComponentName := TControl(Component).Name;
ComponentValue := '';
SaveValue := False;
If (Component is TPanel)
then
begin
ComponentValue := TPanel(Component).Caption;
SaveValue := True;
end;
If (Component is TXPEdit)
then
begin
ComponentValue := TXPEdit(Component).Text;
SaveValue := True;
end;
If (Component is TXPComboBox)
then
begin
ComponentValue := TXPComboBox(Component).Text;
SaveValue := True;
end;
If (Component is TXPCheckBox)
then
begin
ComponentValue := BoolToStr(TXPCheckBox(Component).Checked);
SaveValue := True;
end;
If SaveValue
then IniFile.WriteString(sct_Components, ComponentName, ComponentValue);
end; {For I := 0 to (Form.ComponentCount - 1) do}
IniFile.Free;
end {If FileExists(IniFileName)}
else Result := False;
end; {SaveIniFile}
{==========================================================}
Function GetDateTime : String;
begin
Result := 'Date: ' + FormatDateTime(DateFormat, Date) +
' Time: ' + FormatDateTime(TimeFormat, Now);
end; {GetDateTime}
{================================================}
Function SendMail(Subject,
Body,
FileName,
SenderName,
SenderEMail,
RecepientName,
RecepientEMail : String;
DisplayError : Boolean) : Integer;
var
Message: TMapiMessage;
lpSender, lpRecepient: TMapiRecipDesc;
FileAttach: TMapiFileDesc;
SM: TFNMapiSendMail;
MAPIModule: HModule;
begin
FillChar(Message, SizeOf(Message), 0);
with Message do
begin
If (Subject <> '')
then lpszSubject := PChar(Subject);
If (Body <> '')
then lpszNoteText := PChar(Body);
If (SenderEmail <> '')
then
begin
lpSender.ulRecipClass := MAPI_ORIG;
If (SenderName = '')
then lpSender.lpszName := PChar(SenderEMail)
else lpSender.lpszName := PChar(SenderName);
lpSender.lpszAddress := PChar('SMTP:' + SenderEMail);
lpSender.ulReserved := 0;
lpSender.ulEIDSize := 0;
lpSender.lpEntryID := nil;
lpOriginator := @lpSender;
end; {If (SenderEmail <> '')}
If (RecepientEmail <> '')
then
begin
lpRecepient.ulRecipClass := MAPI_TO;
If (RecepientName = '')
then lpRecepient.lpszName := PChar(RecepientEMail)
else lpRecepient.lpszName := PChar(RecepientName);
lpRecepient.lpszAddress := PChar('SMTP:' + RecepientEMail);
lpRecepient.ulReserved := 0;
lpRecepient.ulEIDSize := 0;
lpRecepient.lpEntryID := nil;
nRecipCount := 1;
lpRecips := @lpRecepient;
end
else lpRecips := nil;
If (FileName = '')
then
begin
nFileCount := 0;
lpFiles := nil;
end
else
begin
FillChar(FileAttach, SizeOf(FileAttach), 0);
FileAttach.nPosition := Cardinal($FFFFFFFF);
FileAttach.lpszPathName := PChar(FileName);
nFileCount := 1;
lpFiles := @FileAttach;
end; {else of If (FileName = '')}
end; {with Message do}
MAPIModule := LoadLibrary(PChar(MAPIDLL));
If (MAPIModule = 0)
then Result := -1
else
try
@SM := GetProcAddress(MAPIModule, 'MAPISendMail');
If (@SM <> nil)
then Result := SM(0, 0, Message, MAPI_DIALOG or MAPI_LOGON_UI, 0)
else Result := 1;
finally
FreeLibrary(MAPIModule);
end;
If (DisplayError and
(Result <> 0))
then MessageDlg('There was an error connecting to your e-mail program.' + #13 +
'Please attach the file to an e-mail manually.',
mtError, [mbOK], 0);
end; {SendMail}
end.
|
//Copyright Cheat Engine. All rights reserved
unit CECustomButton; //more customizable button (not theme friendly)
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, graphics, controls, ExtCtrls, betterControls;
type
TCECustomButtonState=(sbsHighlighted, sbsDown, sbsHasFocus);
TCECustomButtonStates=set of TCECustomButtonState;
TCECustomButton=class(TCustomControl)
private
//state: T
fAlignment : TAlignment;
fScaled: boolean;
fDrawFocusRect: boolean;
fFocusElipseColor: TColor;
hasSetRounding: boolean;
froundingX: integer;
froundingY: integer;
fCustomDrawn: boolean;
fgrowFont: boolean;
fShowPrefix: boolean;
fButtonColor: Tcolor;
fButtonHighlightedColor: TColor;
fButtonDownColor: TColor;
fDrawBorder: boolean;
fBorderColor: Tcolor;
fbordersize: integer;
fFocusedSize: integer;
fbuttonAnimationSpeed: dword;
btnstate: TCECustomButtonStates;
autofontsize: integer;
//animated
timer: TTimer;
//default button animation fields
animationStart: qword;
animationLength: integer; //in milliseconds
animationStartColor: TColor;
animationStopColor: TColor;
lastanimationcolor: TColor;
fFramesPerSecond: integer;
{ fimagelist: Tpicture;
fCurrentFrame: integer;
fOnLastFrame: TNotifyEvent; }
procedure setRoundingX(x: integer);
procedure setRoundingY(y: integer);
procedure setCustomDrawn(state: boolean);
procedure setShowPrefix(state: boolean);
procedure setGrowFont(state: boolean);
procedure setDrawBorder(state: boolean);
procedure setFramesPerSecond(fps: integer);
procedure timertimer(sender: TObject);
procedure setBorderColor(c: Tcolor);
procedure setBorderSize(size: integer);
procedure setFocusedSize(size: integer);
procedure setButtonColor(c: TColor);
procedure setDrawFocusRect(state: boolean);
protected
procedure ChildHandlesCreated; override;
procedure Paint; override;
procedure MouseEnter; override;
procedure MouseLeave; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure CalculatePreferredSize(var PreferredWidth, PreferredHeight: integer; WithThemeSpace: Boolean); override;
function getCaption: string; virtual;
procedure setCaption(c: string); virtual;
public
procedure SetFocus; override;
procedure startAnimatorTimer; //starts the timer based on the current fps. note: does not stop if CustomDrawnn is true
procedure stopAnimatorTimer;
constructor Create(AOwner: TComponent); override;
destructor destroy; override;
published
property ShowPrefix: boolean read fShowPrefix write setShowPrefix;
property Alignment: TAlignment read fAlignment write fAlignment;
property DrawBorder: Boolean read fDrawBorder write setDrawBorder;
property BorderColor: TColor read fBorderColor write setBorderColor;
property BorderSize: integer read fBorderSize write setBorderSize;
property ButtonColor: TColor read fButtonColor write setButtonColor;
property ButtonHighlightedColor: TColor read fButtonHighlightedColor write fButtonHighlightedColor;
property ButtonDownColor: TColor read fButtonDownColor write fButtonDownColor;
property RoundingX: integer read froundingX write setRoundingX;
property RoundingY: integer read froundingY write setRoundingY;
property CustomDrawn: boolean read fCustomDrawn write setCustomDrawn;
property GrowFont: boolean read fGrowFont write setGrowFont;
property FramesPerSecond: integer read fFramesPerSecond write setFramesPerSecond;
property ButtonAnimationSpeed: dword read fbuttonAnimationSpeed write fbuttonAnimationSpeed;
property DrawFocusRect: boolean read fDrawFocusRect write setDrawFocusRect;
property FocusedSize: integer read fFocusedSize write setFocusedSize;
property FocusElipseColor: tcolor read fFocusElipseColor write fFocusElipseColor;
property Scaled: boolean read fScaled write fScaled default true;
property Align;
property Anchors;
property AutoSize;
property BidiMode;
property BorderSpacing;
//todo: property Cancel;
property Caption: string read getCaption write setCaption;
property Color;
property Constraints;
//todo: property Default;
property DoubleBuffered;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property ParentBidiMode;
//todo: property ModalResult;
property OnChangeBounds;
property OnClick;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnResize;
property OnStartDrag;
property OnUTF8KeyPress;
property ParentDoubleBuffered;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
{
property framelist: TList read fimagelist write fimagelist; //if set it's an animated button instead of a rounded button
property currentFrame: integer read fCurrentFrame write fCurrentFrame;
//0=no automated animation
property onLastFrame: TNotifyEvent read fOnLastFrame write fOnLastFrame; //when the last frame of the imagelist has been drawn. The user can then swap the imagelist, or leave it be , and/or change the currentframe back to 0
}
end;
implementation
uses forms;
procedure TCECustomButton.timertimer(sender: TObject);
begin
Invalidate;
end;
procedure TCECustomButton.stopAnimatorTimer;
begin
if timer<>nil then timer.enabled:=false;
end;
procedure TCECustomButton.startAnimatorTimer;
begin
if fFramesPerSecond>0 then
begin
if timer=nil then
timer:=TTimer.create(self);
timer.OnTimer:=@timertimer;
timer.interval:=1000 div fFramesPerSecond;
timer.enabled:=true;
end
else
if timer<>nil then freeandnil(timer);
end;
procedure TCECustomButton.setFramesPerSecond(fps: integer);
begin
fFramesPerSecond:=fps;
if (fFramesPerSecond<=0) and (timer<>nil) then
freeandnil(timer);
if timer<>nil then
timer.interval:=1000 div fps
end;
procedure TCECustomButton.setRoundingX(x: integer);
begin
if x>=0 then
begin
hasSetRounding:=true;
froundingX:=x;
if AutoSize then DoAutoSize;
invalidate;
end;
end;
procedure TCECustomButton.setRoundingY(y: integer);
begin
if y>=0 then
begin
hasSetRounding:=true;
froundingY:=y;
if AutoSize then DoAutoSize;
invalidate;
end;
end;
procedure TCECustomButton.setBorderColor(c: tcolor);
begin
fBorderColor:=c;
invalidate;
end;
procedure TCECustomButton.setBorderSize(size: integer);
begin
fBorderSize:=size;
invalidate;
end;
procedure TCECustomButton.setFocusedSize(size: integer);
begin
fFocusedSize:=size;
invalidate;
end;
procedure TCECustomButton.setButtonColor(c: tcolor);
begin
fButtonColor:=c;
Invalidate;
end;
procedure TCECustomButton.setCustomDrawn(state: boolean);
begin
fCustomDrawn:=state;
invalidate;
end;
procedure TCECustomButton.setGrowFont(state: boolean);
begin
fgrowFont:=state;
invalidate;
end;
procedure TCECustomButton.setDrawBorder(state: boolean);
begin
fDrawBorder:=state;
invalidate;;
end;
procedure TCECustomButton.setShowPrefix(state: boolean);
begin
fShowPrefix:=state;
invalidate;;
end;
procedure TCECustomButton.setDrawFocusRect(state: boolean);
begin
fDrawFocusRect:=state;
invalidate;
end;
procedure TCECustomButton.MouseEnter;
begin
btnstate:=btnstate+[sbsHighlighted];
animationStart:=GetTickCount64;
animationLength:=fbuttonAnimationSpeed;
if lastanimationcolor<>0 then
animationStartColor:=lastanimationcolor
else
animationStartColor:=ColorToRGB(fButtonColor);
animationStopColor:=ColorToRGB(fButtonHighlightedColor);
invalidate;
if animationLength>0 then
startAnimatorTimer;
inherited MouseEnter;
end;
procedure TCECustomButton.MouseLeave;
begin
btnstate:=btnstate-[sbsHighlighted];
animationStart:=GetTickCount64;
animationLength:=fbuttonAnimationSpeed;
if lastanimationcolor<>0 then
animationStartColor:=lastanimationcolor
else
animationStartColor:=ColorToRGB(fButtonHighlightedColor);
animationStopColor:=ColorToRGB(fButtonColor);
invalidate;
startAnimatorTimer;
inherited MouseLeave;
end;
procedure TCECustomButton.ChildHandlesCreated;
var
p: twincontrol;
f: TCustomForm absolute p;
begin
if scaled and hasSetRounding then
begin
p:=parent;
while (p<>nil) and (not (p is TCustomForm)) do
p:=p.Parent;
if p<>nil then
begin
fRoundingX:=scalex(froundingx, f.DesignTimePPI);
fRoundingY:=scaley(froundingy, f.DesignTimePPI);
end;
Invalidate;
end;
inherited ChildHandlesCreated;
end;
procedure TCECustomButton.SetFocus;
begin
inherited SetFocus;
invalidate;
end;
procedure TCECustomButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if button=mbLeft then
begin
SetFocus;
btnstate:=btnstate+[sbsDown];
invalidate;
end;
inherited mousedown(button, shift, x, y);
end;
procedure TCECustomButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if button=mbLeft then
begin
btnstate:=btnstate-[sbsDown];
invalidate;
end;
inherited MouseUp(button, shift, x, y);
end;
procedure TCECustomButton.setCaption(c: string);
begin
inherited caption:=c;
invalidate;
end;
function TCECustomButton.getCaption: string;
begin
result:=inherited caption;
end;
procedure TCECustomButton.CalculatePreferredSize(var PreferredWidth, PreferredHeight: integer; WithThemeSpace: Boolean);
begin
PreferredWidth:=0;
PreferredHeight:=0;
canvas.GetTextSize(Caption,PreferredWidth,PreferredHeight);
PreferredWidth:=4+PreferredWidth+2*canvas.GetTextWidth(' ');
PreferredHeight:=4+PreferredHeight;
end;
procedure TCECustomButton.Paint;
var
w,h: integer;
fs: integer;
borderc: tcolor;
buttonc: tcolor;
animpos: single;
startred, startgreen, startblue: byte;
endred, endgreen, endblue: byte;
newred, newgreen, newblue: byte;
currenttime: qword;
ts: TTextStyle;
p: TPenPattern;
begin
if CustomDrawn then
inherited Paint
else
begin
borderc:=bordercolor;
if (timer<>nil) and timer.enabled then
begin
currenttime:=gettickcount64();
if animationLength>0 then
animpos:=(currenttime-animationstart) / animationlength
else
animpos:=2;
if animpos>1 then
begin
timer.enabled:=false; //animation ended
animpos:=1;
lastanimationcolor:=0;
end;
RedGreenBlue(animationstartcolor, startred, startgreen, startblue);
RedGreenBlue(animationStopColor, endred, endgreen, endblue);
newred:=startred+trunc((integer(endred)-integer(startred))*animpos);
newgreen:=startgreen+trunc((integer(endgreen)-integer(startgreen))*animpos);
newblue:=startblue+trunc((integer(endblue)-integer(startblue))*animpos);
buttonc:=RGBToColor(newred,newgreen,newblue);
if timer.enabled then
lastanimationcolor:=buttonc;
end
else
begin
if sbsHighlighted in btnstate then
buttonc:=ButtonHighlightedColor
else
buttonc:=buttoncolor;
end;
if sbsDown in btnstate then
buttonc:=fButtonDownColor;
w:=0;
h:=0;
if growfont and (autofontsize=0) then
begin
fs:=0;
repeat
inc(fs);
canvas.font.size:=fs;
canvas.GetTextSize(Caption,w,h);
until (w>width-4) or (h>height-4);
if fs>1 then
autofontsize:=fs
else
autofontsize:=1;
end;
canvas.brush.color:=buttonc;
canvas.brush.Style:=bsSolid;
if fDrawBorder then
begin
canvas.Pen.Color:=borderc;
canvas.pen.Width:=fbordersize;
end
else
begin
canvas.Pen.Color:=buttonc;
canvas.pen.Width:=1;
end;
Canvas.RoundRect(0,0,width, height,froundingX,froundingY);
if Focused and drawfocusrect then
begin
canvas.pen.style:=psPattern;
setlength(p,2);
p[0]:=1;
p[1]:=3;
canvas.pen.SetPattern(p);
canvas.pen.color:=fFocusElipseColor;
canvas.pen.width:=fFocusedSize;
Canvas.RoundRect(1,1,width-1, height-1,froundingX,froundingY);
canvas.pen.style:=psSolid;
end;
canvas.pen.Width:=1;
canvas.brush.Style:=bsClear;
if growfont then
canvas.font.size:=autofontsize
else
canvas.font:=Font;
ts:=canvas.TextStyle;
ts.Alignment:=Alignment;
ts.Layout:=tlCenter;
ts.EndEllipsis:=true;
ts.ShowPrefix:=ShowPrefix;
canvas.TextRect(ClientRect,0,0,caption, ts);
end;
end;
destructor TCECustomButton.destroy;
begin
if timer<>nil then
freeandnil(timer);
inherited destroy;
end;
constructor TCECustomButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Alignment:=taCenter;
froundingY:=20; //scaley(20,96);
froundingX:=20; //scalex(20,96);
ControlStyle:=ControlStyle - [csOpaque] + [csParentBackground, csClickEvents];
fButtonColor:=clBtnFace;
fButtonHighlightedColor:=inccolor(fButtonColor,32);
fButtonDownColor:=deccolor(fbuttonColor,32);
fBorderColor:=clBtnBorder;
buttonAnimationSpeed:=200;
fFramesPerSecond:=24;
fDrawFocusRect:=true;
fDrawBorder:=true;
fFocusedSize:=1;
fbordersize:=1;
ffocusElipseColor:=clHighlight;
fscaled:=true;
TabStop:=true;
end;
initialization
RegisterClass(TCECustomButton);
end.
|
unit RRManagerEditHistoryFrame;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
RRManagerObjects, RRManagerBaseObjects, StdCtrls, CommonComplexCombo,
ComCtrls, Buttons, Mask, ToolEdit, RRManagerBaseGUI;
type
TfrmHistory = class(TBaseFrame)
// TfrmHistory = class(TFrame)
gbxAll: TGroupBox;
lblDisclaimer: TLabel;
cmplxActionType: TfrmComplexCombo;
cmplxActionReason: TfrmComplexCombo;
mmReason: TMemo;
lblDescription: TLabel;
sbtnShowHistory: TSpeedButton;
lwHistory: TListView;
dtedtActionDate: TDateEdit;
Label1: TLabel;
edtWhoWhen: TEdit;
procedure sbtnShowHistoryClick(Sender: TObject);
procedure lwHistoryChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
private
{ Private declarations }
FHistory: TOldStructureHistory;
FHistoryElement: TOldStructureHistoryElement;
FTheOnlyActionType: boolean;
function GetStructure: TOldStructure;
function GetHistory: TOldStructureHistory;
procedure ClearOnlyControls;
procedure SetHistoryElement(const Value: TOldStructureHistoryElement);
procedure SetTheOnlyActionType(const Value: boolean);
function GetRealHistoryElement: TOldStructureHistoryElement;
protected
procedure ClearControls; override;
procedure FillControls(ABaseObject: TBaseObject); override;
procedure RegisterInspector; override;
public
{ Public declarations }
property History: TOldStructureHistory read GetHistory;
property HistoryElement: TOldStructureHistoryElement read FHistoryElement write SetHistoryElement;
property Structure: TOldStructure read GetStructure;
property RealHistoryElement: TOldStructureHistoryElement read GetRealHistoryElement;
// можно ли менять тип действия
// по умолчанию нельзя
property TheOnlyActionType: boolean read FTheOnlyActionType write SetTheOnlyActionType;
procedure Save; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses RRManagerLoaderCommands;
const sDisclaimer = 'Вы %s. Это серьезное изменение, которое требует отдельной регистрации. Заполните, пожалуйста, регистрационную форму.';
type
TStructureHistoryLoadAction = class(TStructureHistoryBaseLoadAction)
public
function Execute(ABaseObject: TBaseObject): boolean; override;
end;
{$R *.DFM}
{ TfrmHistory }
procedure TfrmHistory.ClearControls;
begin
// FHistory.Free;
// FHistory := nil;
ClearOnlyControls;
end;
procedure TfrmHistory.ClearOnlyControls;
begin
lwHistory.Items.Clear;
cmplxActionReason.Clear;
mmReason.Lines.Clear;
sbtnShowHistory.Down := false;
lwHistory.Visible := sbtnShowHistory.Down;
end;
constructor TfrmHistory.Create(AOwner: TComponent);
begin
inherited;
cmplxActionType.Caption := 'Тип действия';
cmplxActionType.FullLoad := true;
cmplxActionType.DictName := 'TBL_ACTION_TYPE_DICT';
cmplxActionReason.Caption := 'Причина действия (общая)';
cmplxActionReason.FullLoad := true;
cmplxActionReason.DictName := 'TBL_ACTION_REASON_DICT';
TheOnlyActionType := false;
NeedCopyState := false;
end;
procedure TfrmHistory.FillControls(ABaseObject: TBaseObject);
var actn: TBaseAction;
RealElement, el: TOldStructureHistoryElement;
S: TOldStructure;
begin
s := nil;
if not Assigned(ABaseObject) then S := Structure
else if ABaseObject is TOldStructure then
S := ABaseObject as TOldStructure;
sbtnShowHistory.Down := false;
lwHistory.Visible := sbtnShowHistory.Down;
// сначала сохраняем элемент истории добавленный в прошлом фрэйме
// непосредственно при изменении
if Assigned(S) then
begin
RealElement := TOldStructureHistoryElement.Create(nil);
RealElement.Assign(S.LastHistoryElement);
// копируем историю - на случай, если не будем сохранять
actn := TStructureHistoryLoadAction.Create(Self);
actn.Execute(S);
actn.Free;
if Assigned(FHistory) then
begin
FHistory.Free;
FHistory := nil;
end;
// добавляем реальный последний элемент
el := History.Add;
el.Assign(RealElement);
// и загружаем его в интерфейс
HistoryElement := el;
// этот более не нужен
RealElement.Free;
end
else if Assigned(ABaseObject) and (ABaseObject is TOldStructureHistoryElement) then
begin
HistoryElement := ABaseObject as TOldStructureHistoryElement;
end
else if Assigned(RealHistoryElement) then
begin
HistoryElement := RealHistoryElement;
end;
Check;
{ if lwHistory.Items.Count > 0 then
lwHistory.Selected := lwHistory.Items[0];}
end;
function TfrmHistory.GetHistory: TOldStructureHistory;
begin
Result := nil;
if Assigned(FHistory) then Result := FHistory
else
if Assigned(Structure) then
begin
FHistory := TOldStructureHistory.Create(nil);
FHistory.Assign(Structure.History);
Result := FHistory;
end;
end;
function TfrmHistory.GetStructure: TOldStructure;
begin
if EditingObject is TOldStructure then
Result := EditingObject as TOldStructure
else
Result := nil;
end;
procedure TfrmHistory.Save;
begin
inherited;
FHistoryElement.ActionTypeID := cmplxActionType.SelectedElementID;
FHistoryElement.ActionType := cmplxActionType.SelectedElementName;
FHistoryElement.ActionReasonID := cmplxActionReason.SelectedElementID;
FHistoryElement.ActionReason := cmplxActionReason.SelectedElementName;
FHistoryElement.Comment := mmReason.Text;
if Assigned(Structure) and Assigned(History) then
begin
FHistoryElement.FundTypeID := Structure.StructureTypeID;
FHistoryElement.FundType := Structure.StructureType;
Structure.History.Assign(History)
end
else if Assigned(RealHistoryElement) then
RealHistoryElement.Assign(FHistoryElement);
end;
procedure TfrmHistory.sbtnShowHistoryClick(Sender: TObject);
begin
sbtnShowHistory.Down := not sbtnShowHistory.Down;
lwHistory.Visible := sbtnShowHistory.Down;
end;
procedure TfrmHistory.SetHistoryElement(
const Value: TOldStructureHistoryElement);
begin
FHistoryElement := Value;
if Assigned(FHistoryElement) then
begin
cmplxActionType.AddItem(FHistoryElement.ActionTypeID, FHistoryElement.ActionType);
cmplxActionReason.AddItem(FHistoryElement.ActionReasonID, FHistoryElement.ActionReason);
dtedtActionDate.Date := FHistoryElement.ActionDate;
mmReason.Text := FHistoryElement.Comment;
// в лэйбл пишем то, что отличает конкретный структурный элемент
lblDisclaimer.Caption := Format(sDisclaimer, [FHistoryElement.List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false)]);
edtWhoWhen.Text := 'Изменено: ' + DateTimeToStr(FHistoryElement.RealDate) + '; автор: ' + FHistoryElement.Employee;
end
else ClearOnlyControls;
end;
destructor TfrmHistory.Destroy;
begin
inherited;
FHistory.Free;
end;
procedure TfrmHistory.SetTheOnlyActionType(const Value: boolean);
begin
FTheOnlyActionType := Value;
cmplxActionType.Enabled := FTheOnlyActionType;
end;
procedure TfrmHistory.RegisterInspector;
begin
inherited;
Inspector.Add(cmplxActionType.cmbxName, nil, ptString, 'тип действия', false);
Inspector.Add(cmplxActionReason.cmbxName, nil, ptString, 'причина действия', false);
end;
function TfrmHistory.GetRealHistoryElement: TOldStructureHistoryElement;
begin
if EditingObject is TOldStructureHistoryElement then
Result := EditingObject as TOldStructureHistoryElement
else
Result := nil;
end;
{ TStructureHistoryLoadAction }
function TStructureHistoryLoadAction.Execute(
ABaseObject: TBaseObject): boolean;
var i: integer;
li: TListItem;
begin
LastCollection := (ABaseObject as TOldStructure).History;
if LastCollection.NeedsUpdate then
Result := inherited Execute(ABaseObject)
else Result := true;
if Result then
begin
// загружаем в интерфейс
if Assigned(LastCollection) then
with Owner as TfrmHistory do
begin
// получаем версии на форму
History;
lwHistory.Items.BeginUpdate;
lwHistory.Selected := nil;
// чистим
try
lwHistory.Items.Clear;
except
end;
// добавляем в дерево не реальные версии
// а их копии, чтобы потом сохранять изменения
for i := 0 to History.Count - 1 do
begin
li := lwHistory.Items.Add;
li.Caption := History.Items[i].List(AllOpts.Current.ListOption, AllOpts.Current.ShowUINs, false);
li.Data := History.Items[i];
end;
lwHistory.Items.EndUpdate;
end;
end;
end;
procedure TfrmHistory.lwHistoryChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
if Change = ctState then
begin
if Assigned(Item) then
begin
Item.Selected := true;
HistoryElement := TOldStructureHistoryElement(Item.Data);
end
else HistoryElement := nil;
end
end;
end.
|
unit GRRExcelImporter;
interface
uses ExcelImporter, Contnrs, Classes, GRRObligation, LicenseZone;
type
TStringTable = class(TObjectList)
private
FColCount: integer;
function GetRow(const Index: integer): TStringList;
public
property ColCount: integer read FColCount;
function AddRow: TStringList;
property Row[const Index: integer]: TStringList read GetRow;
constructor Create(AColCount: Integer);
end;
TGRRConditionsImporter = class(TExcelImporter)
private
FLicenseNumber: string;
FLicenseName: string;
FDrillingData: TStringTable; FSeismicData: TStringTable; FNirData: TStringTable;
FDrillingObligations: TDrillObligations;
FNIRObligations: TNIRObligations;
FSeismicObligations: TSeismicObligations;
FOnChangeActiveLicenseZone: TNotifyEvent;
FOnAfterImport: TNotifyEvent;
procedure ReadDrillingConditions;
procedure ReadSeismicConditions;
procedure ReadNIRConditions;
procedure ConvertDrillingConditions;
procedure ConvertSeismicConditions;
procedure ConvertNIRConditions;
protected
class function CreateInstance: TExcelImporter; override;
public
property LicenseNumber: string read FLicenseNumber;
property LicenseName: string read FLicenseName;
property DrillingData: TStringTable read FDrillingData;
property SeismicData: TStringTable read FSeismicData;
property NirData: TStringTable read FNirData;
property DrillingObligations: TDrillObligations read FDrillingObligations;
property SeismicObligations: TSeismicObligations read FSeismicObligations;
property NIRObligations: TNIRObligations read FNIRObligations;
property OnChangeActiveLicenseZone: TNotifyEvent read FOnChangeActiveLicenseZone write FOnChangeActiveLicenseZone;
property OnAfterImport: TNotifyEvent read FOnAfterImport write FOnAfterImport;
procedure Execute; override;
class function GetInstance(const AFileName: string): TGRRConditionsImporter;
end;
implementation
uses SysUtils, GRRImportingDataInterpreter, BaseObjects, Facade, State, Well, SeismworkType;
{ TGRRConditionsImporter }
procedure TGRRConditionsImporter.ConvertDrillingConditions;
var i, iOut: integer;
d: TDrillObligation;
interpreter: TDataInterpreter;
dOut: TDateTime;
oOut: TIDObject;
begin
FreeAndNil(FDrillingObligations);
FDrillingObligations := TDrillObligations.Create;
interpreter := TDataInterpreter.Create;
for i := 0 to DrillingData.Count - 1 do
begin
d := FDrillingObligations.Add as TDrillObligation;
if interpreter.ReadInteger(DrillingData.Row[i][0], iOut) then d.WellCount := iOut
else
begin
d.WellCount := 0;
d.WellCountIsUndefined := 1;
end;
if interpreter.ReadDate(DrillingData.Row[i][1], dOut) then d.StartDate := dOut
else d.StartDate := 0;
if interpreter.ReadDate(DrillingData.Row[i][2], dOut) then d.FinishDate := dOut
else d.FinishDate := 0;
if interpreter.ReadObject(DrillingData.Row[i][3], TMainFacade.GetInstance.AllWellStates, oOut) then d.WellState := oOut as TState
else d.WellState := nil;
if interpreter.ReadObject(DrillingData.Row[i][4], TMainFacade.GetInstance.AllWellCategories, oOut) then d.WellCategory := oOut as TWellCategory
else d.WellCategory := nil;
d.Comment := DrillingData.Row[i][5];
end;
FreeAndNil(interpreter);
end;
procedure TGRRConditionsImporter.ConvertNIRConditions;
var i: integer;
n: TNIRObligation;
interpreter: TDataInterpreter;
dOut: TDateTime;
begin
FreeAndNil(FNIRObligations);
FNIRObligations := TNIRObligations.Create;
interpreter := TDataInterpreter.Create;
for i := 0 to NirData.Count - 1 do
begin
n := FNIRObligations.Add as TNIRObligation;
n.Name := trim(NirData.Row[i][0]);
if interpreter.ReadDate(NirData.Row[i][1], dOut) then n.FinishDate := dOut
else n.FinishDate := 0;
n.Comment := trim(NirData.Row[i][2]);
end;
FreeAndNil(interpreter);
end;
procedure TGRRConditionsImporter.ConvertSeismicConditions;
var i: integer;
s: TSeismicObligation;
interpreter: TDataInterpreter;
dOut: TDateTime;
oOut: TIDObject;
fOut: single;
begin
FreeAndNil(FSeismicObligations);
FSeismicObligations := TSeismicObligations.Create;
interpreter := TDataInterpreter.Create;
for i := 0 to SeismicData.Count - 1 do
begin
s := FSeismicObligations.Add as TSeismicObligation;
if interpreter.ReadObject(SeismicData.Row[i][0], TMainFacade.GetInstance.AllSeisWorkTypes, oOut) then s.SeisWorkType := oOut as TSeismWorkType
else s.SeisWorkType := nil;
if interpreter.ReadFloat(SeismicData.Row[i][1], fOut) then s.Volume := fOut
else s.Volume := 0;
if interpreter.ReadDate(SeismicData.Row[i][3], dOut) then s.StartDate := dOut
else s.StartDate := 0;
if interpreter.ReadDate(SeismicData.Row[i][4], dOut) then s.FinishDate := dOut
else s.FinishDate := 0;
s.Comment := trim(SeismicData.Row[i][5]);
end;
FreeAndNil(interpreter);
end;
class function TGRRConditionsImporter.CreateInstance: TExcelImporter;
begin
Result := TGRRConditionsImporter.Create;
end;
procedure TGRRConditionsImporter.Execute;
var lic: TLicenseZone;
begin
inherited;
if FindCell('Номер лицензии') then FLicenseNumber := trim(Excel.Cells[ActiveRow + 1, ActiveColumn].Value) else raise ECellNotFound.Create('Номер лицензии');
if FindCell('Наименование лицензионного участка') then FLicenseName := Trim(Excel.Cells[ActiveRow + 1, ActiveColumn].Value) else raise ECellNotFound.Create('Наименование лицензионного участка');
lic := TMainFacade.GetInstance.AllLicenseZones.GetLicenseZoneByNumber(FLicenseNumber);
if lic <> TMainFacade.GetInstance.ActiveLicenseZone then
begin
TMainFacade.GetInstance.ActiveLicenseZone := lic;
if Assigned(OnChangeActiveLicenseZone) then OnChangeActiveLicenseZone(Self);
end;
// чтение данных
if FindCell('Бурение') then ReadDrillingConditions else raise ECellNotFound.Create('Бурение');
if FindCell('Сейсморазведочные работы') then ReadSeismicConditions else raise ECellNotFound.Create('Сейсморазведочные работы');
if FindCell('НИР') then ReadNIRConditions else raise ECellNotFound.Create('НИР');
// интерпретация
ConvertDrillingConditions;
ConvertSeismicConditions;
ConvertNIRConditions;
// копирование
if Assigned(TMainFacade.GetInstance.ActiveLicenseZone) then
begin
TMainFacade.GetInstance.ActiveLicenseZone.AllDrillObligations.Copy(DrillingObligations);
TMainFacade.GetInstance.ActiveLicenseZone.AllSeismicObligations.Copy(SeismicObligations);
TMainFacade.GetInstance.ActiveLicenseZone.AllNirObligations.Copy(NIRObligations);
end;
if Assigned(FOnAfterImport) then FOnAfterImport(Self);
end;
class function TGRRConditionsImporter.GetInstance(
const AFileName: string): TGRRConditionsImporter;
begin
Result := inherited GetInstance(AFileName) as TGRRConditionsImporter;
end;
procedure TGRRConditionsImporter.ReadDrillingConditions;
var FirstCell: OleVariant;
Region: OleVariant;
i, j: integer;
r: TStringList;
begin
if Assigned(FDrillingData) then FreeAndNil(FDrillingData);
FDrillingData := TStringTable.Create(6);
FirstCell := Excel.Cells[ActiveRow + 4, ActiveColumn];
Region := FirstCell.CurrentRegion;
Region.Select;
// начинаем с пятой
for i := 5 to Region.Rows.Count do
begin
r := FDrillingData.AddRow;
for j := 1 to Region.Columns.Count do
r[j - 1] := Region.Cells[i, j].Value;
end
end;
procedure TGRRConditionsImporter.ReadNIRConditions;
var FirstCell: OleVariant;
Region: OleVariant;
i, j: integer;
r: TStringList;
begin
if Assigned(FNirData) then FreeAndNil(FNirData);
FNirData := TStringTable.Create(3);
FirstCell := Excel.Cells[ActiveRow + 4, ActiveColumn];
Region := FirstCell.CurrentRegion;
Region.Select;
// начинаем с пятой
for i := 5 to Region.Rows.Count do
begin
r := FNirData.AddRow;
for j := 1 to Region.Columns.Count do
r[j - 1] := Region.Cells[i, j].Value;
end
end;
procedure TGRRConditionsImporter.ReadSeismicConditions;
var FirstCell: OleVariant;
Region: OleVariant;
i, j: integer;
r: TStringList;
begin
if Assigned(FSeismicData) then FreeAndNil(FSeismicData);
FSeismicData := TStringTable.Create(6);
FirstCell := Excel.Cells[ActiveRow + 4, ActiveColumn];
Region := FirstCell.CurrentRegion;
Region.Select;
// начинаем с пятой
for i := 5 to Region.Rows.Count do
begin
r := FSeismicData.AddRow;
for j := 1 to Region.Columns.Count do
r[j - 1] := Region.Cells[i, j].Value;
end
end;
{ TStringTable }
function TStringTable.AddRow: TStringList;
var i: Integer;
begin
Result := TStringList.Create;
inherited Add(Result);
for i := 0 to ColCount - 1 do
Result.Add('');
end;
constructor TStringTable.Create(AColCount: Integer);
begin
inherited Create(True);
FColCount := AColCount;
end;
function TStringTable.GetRow(const Index: integer): TStringList;
begin
Result := inherited Items[Index] as TStringList;
end;
end.
|
unit StringArray;
interface
type
HCkTask = Pointer;
HCkString = Pointer;
HCkStringArray = Pointer;
function CkStringArray_Create: HCkStringArray; stdcall;
procedure CkStringArray_Dispose(handle: HCkStringArray); stdcall;
function CkStringArray_getCount(objHandle: HCkStringArray): Integer; stdcall;
function CkStringArray_getCrlf(objHandle: HCkStringArray): wordbool; stdcall;
procedure CkStringArray_putCrlf(objHandle: HCkStringArray; newPropVal: wordbool); stdcall;
procedure CkStringArray_getDebugLogFilePath(objHandle: HCkStringArray; outPropVal: HCkString); stdcall;
procedure CkStringArray_putDebugLogFilePath(objHandle: HCkStringArray; newPropVal: PWideChar); stdcall;
function CkStringArray__debugLogFilePath(objHandle: HCkStringArray): PWideChar; stdcall;
procedure CkStringArray_getLastErrorHtml(objHandle: HCkStringArray; outPropVal: HCkString); stdcall;
function CkStringArray__lastErrorHtml(objHandle: HCkStringArray): PWideChar; stdcall;
procedure CkStringArray_getLastErrorText(objHandle: HCkStringArray; outPropVal: HCkString); stdcall;
function CkStringArray__lastErrorText(objHandle: HCkStringArray): PWideChar; stdcall;
procedure CkStringArray_getLastErrorXml(objHandle: HCkStringArray; outPropVal: HCkString); stdcall;
function CkStringArray__lastErrorXml(objHandle: HCkStringArray): PWideChar; stdcall;
function CkStringArray_getLastMethodSuccess(objHandle: HCkStringArray): wordbool; stdcall;
procedure CkStringArray_putLastMethodSuccess(objHandle: HCkStringArray; newPropVal: wordbool); stdcall;
function CkStringArray_getLength(objHandle: HCkStringArray): Integer; stdcall;
function CkStringArray_getTrim(objHandle: HCkStringArray): wordbool; stdcall;
procedure CkStringArray_putTrim(objHandle: HCkStringArray; newPropVal: wordbool); stdcall;
function CkStringArray_getUnique(objHandle: HCkStringArray): wordbool; stdcall;
procedure CkStringArray_putUnique(objHandle: HCkStringArray; newPropVal: wordbool); stdcall;
function CkStringArray_getVerboseLogging(objHandle: HCkStringArray): wordbool; stdcall;
procedure CkStringArray_putVerboseLogging(objHandle: HCkStringArray; newPropVal: wordbool); stdcall;
procedure CkStringArray_getVersion(objHandle: HCkStringArray; outPropVal: HCkString); stdcall;
function CkStringArray__version(objHandle: HCkStringArray): PWideChar; stdcall;
function CkStringArray_Append(objHandle: HCkStringArray; str: PWideChar): wordbool; stdcall;
function CkStringArray_AppendSerialized(objHandle: HCkStringArray; encodedStr: PWideChar): wordbool; stdcall;
procedure CkStringArray_Clear(objHandle: HCkStringArray); stdcall;
function CkStringArray_Contains(objHandle: HCkStringArray; str: PWideChar): wordbool; stdcall;
function CkStringArray_Find(objHandle: HCkStringArray; findStr: PWideChar; startIndex: Integer): Integer; stdcall;
function CkStringArray_FindFirstMatch(objHandle: HCkStringArray; matchPattern: PWideChar; startIndex: Integer): Integer; stdcall;
function CkStringArray_GetString(objHandle: HCkStringArray; index: Integer; outStr: HCkString): wordbool; stdcall;
function CkStringArray__getString(objHandle: HCkStringArray; index: Integer): PWideChar; stdcall;
function CkStringArray_GetStringLen(objHandle: HCkStringArray; index: Integer): Integer; stdcall;
procedure CkStringArray_InsertAt(objHandle: HCkStringArray; index: Integer; str: PWideChar); stdcall;
function CkStringArray_LastString(objHandle: HCkStringArray; outStr: HCkString): wordbool; stdcall;
function CkStringArray__lastString(objHandle: HCkStringArray): PWideChar; stdcall;
function CkStringArray_LoadFromFile(objHandle: HCkStringArray; path: PWideChar): wordbool; stdcall;
function CkStringArray_LoadFromFile2(objHandle: HCkStringArray; path: PWideChar; charset: PWideChar): wordbool; stdcall;
procedure CkStringArray_LoadFromText(objHandle: HCkStringArray; str: PWideChar); stdcall;
function CkStringArray_LoadTaskResult(objHandle: HCkStringArray; task: HCkTask): wordbool; stdcall;
function CkStringArray_Pop(objHandle: HCkStringArray; outStr: HCkString): wordbool; stdcall;
function CkStringArray__pop(objHandle: HCkStringArray): PWideChar; stdcall;
procedure CkStringArray_Prepend(objHandle: HCkStringArray; str: PWideChar); stdcall;
procedure CkStringArray_Remove(objHandle: HCkStringArray; str: PWideChar); stdcall;
function CkStringArray_RemoveAt(objHandle: HCkStringArray; index: Integer): wordbool; stdcall;
procedure CkStringArray_ReplaceAt(objHandle: HCkStringArray; index: Integer; str: PWideChar); stdcall;
function CkStringArray_SaveLastError(objHandle: HCkStringArray; path: PWideChar): wordbool; stdcall;
function CkStringArray_SaveNthToFile(objHandle: HCkStringArray; index: Integer; saveToPath: PWideChar): wordbool; stdcall;
function CkStringArray_SaveToFile(objHandle: HCkStringArray; path: PWideChar): wordbool; stdcall;
function CkStringArray_SaveToFile2(objHandle: HCkStringArray; saveToPath: PWideChar; charset: PWideChar): wordbool; stdcall;
function CkStringArray_SaveToText(objHandle: HCkStringArray; outStr: HCkString): wordbool; stdcall;
function CkStringArray__saveToText(objHandle: HCkStringArray): PWideChar; stdcall;
function CkStringArray_Serialize(objHandle: HCkStringArray; outStr: HCkString): wordbool; stdcall;
function CkStringArray__serialize(objHandle: HCkStringArray): PWideChar; stdcall;
procedure CkStringArray_Sort(objHandle: HCkStringArray; ascending: wordbool); stdcall;
procedure CkStringArray_SplitAndAppend(objHandle: HCkStringArray; str: PWideChar; boundary: PWideChar); stdcall;
function CkStringArray_StrAt(objHandle: HCkStringArray; index: Integer; outStr: HCkString): wordbool; stdcall;
function CkStringArray__strAt(objHandle: HCkStringArray; index: Integer): PWideChar; stdcall;
procedure CkStringArray_Subtract(objHandle: HCkStringArray; stringArrayObj: HCkStringArray); stdcall;
procedure CkStringArray_Union(objHandle: HCkStringArray; stringArrayObj: HCkStringArray); stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkStringArray_Create; external DLLName;
procedure CkStringArray_Dispose; external DLLName;
function CkStringArray_getCount; external DLLName;
function CkStringArray_getCrlf; external DLLName;
procedure CkStringArray_putCrlf; external DLLName;
procedure CkStringArray_getDebugLogFilePath; external DLLName;
procedure CkStringArray_putDebugLogFilePath; external DLLName;
function CkStringArray__debugLogFilePath; external DLLName;
procedure CkStringArray_getLastErrorHtml; external DLLName;
function CkStringArray__lastErrorHtml; external DLLName;
procedure CkStringArray_getLastErrorText; external DLLName;
function CkStringArray__lastErrorText; external DLLName;
procedure CkStringArray_getLastErrorXml; external DLLName;
function CkStringArray__lastErrorXml; external DLLName;
function CkStringArray_getLastMethodSuccess; external DLLName;
procedure CkStringArray_putLastMethodSuccess; external DLLName;
function CkStringArray_getLength; external DLLName;
function CkStringArray_getTrim; external DLLName;
procedure CkStringArray_putTrim; external DLLName;
function CkStringArray_getUnique; external DLLName;
procedure CkStringArray_putUnique; external DLLName;
function CkStringArray_getVerboseLogging; external DLLName;
procedure CkStringArray_putVerboseLogging; external DLLName;
procedure CkStringArray_getVersion; external DLLName;
function CkStringArray__version; external DLLName;
function CkStringArray_Append; external DLLName;
function CkStringArray_AppendSerialized; external DLLName;
procedure CkStringArray_Clear; external DLLName;
function CkStringArray_Contains; external DLLName;
function CkStringArray_Find; external DLLName;
function CkStringArray_FindFirstMatch; external DLLName;
function CkStringArray_GetString; external DLLName;
function CkStringArray__getString; external DLLName;
function CkStringArray_GetStringLen; external DLLName;
procedure CkStringArray_InsertAt; external DLLName;
function CkStringArray_LastString; external DLLName;
function CkStringArray__lastString; external DLLName;
function CkStringArray_LoadFromFile; external DLLName;
function CkStringArray_LoadFromFile2; external DLLName;
procedure CkStringArray_LoadFromText; external DLLName;
function CkStringArray_LoadTaskResult; external DLLName;
function CkStringArray_Pop; external DLLName;
function CkStringArray__pop; external DLLName;
procedure CkStringArray_Prepend; external DLLName;
procedure CkStringArray_Remove; external DLLName;
function CkStringArray_RemoveAt; external DLLName;
procedure CkStringArray_ReplaceAt; external DLLName;
function CkStringArray_SaveLastError; external DLLName;
function CkStringArray_SaveNthToFile; external DLLName;
function CkStringArray_SaveToFile; external DLLName;
function CkStringArray_SaveToFile2; external DLLName;
function CkStringArray_SaveToText; external DLLName;
function CkStringArray__saveToText; external DLLName;
function CkStringArray_Serialize; external DLLName;
function CkStringArray__serialize; external DLLName;
procedure CkStringArray_Sort; external DLLName;
procedure CkStringArray_SplitAndAppend; external DLLName;
function CkStringArray_StrAt; external DLLName;
function CkStringArray__strAt; external DLLName;
procedure CkStringArray_Subtract; external DLLName;
procedure CkStringArray_Union; external DLLName;
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(12 Out 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit dbcbr.ddl.generator.absolutedb;
interface
uses
SysUtils,
StrUtils,
Generics.Collections,
dbebr.factory.interfaces,
dbcbr.ddl.interfaces,
dbcbr.ddl.register,
dbcbr.ddl.generator,
dbcbr.database.mapping;
type
TDDLSQLGeneratorAbsoluteDB = class(TDDLSQLGenerator)
protected
function BuilderPrimayKeyDefinition(ATable: TTableMIK): string; override;
public
function GenerateCreateTable(ATable: TTableMIK): string; override;
function GenerateCreateSequence(ASequence: TSequenceMIK): string; override;
function GenerateDropTable(ATable: TTableMIK): string; override;
function GenerateDropSequence(ASequence: TSequenceMIK): string; override;
function GetSupportedFeatures: TSupportedFeatures; override;
end;
implementation
{ TDDLSQLGeneratorAbsoluteDB }
function TDDLSQLGeneratorAbsoluteDB.BuilderPrimayKeyDefinition(ATable: TTableMIK): string;
function GetPrimaryKeyColumns: string;
var
oColumn: TPair<string,TColumnMIK>;
begin
for oColumn in ATable.PrimaryKey.FieldsSort do
Result := Result + oColumn.Value.Name + ', ';
Result := Trim(Result);
Delete(Result, Length(Result), 1);
end;
begin
// Result := 'PRIMARY KEY(%s) %s';
// Result := Format(Result, [GetPrimaryKeyColumns, IfThen(ATable.PrimaryKey.AutoIncrement,'AUTOINCREMENT','')]);
Result := 'PRIMARY KEY(%s) ';
Result := Format(Result, [GetPrimaryKeyColumns]);
Result := ' ' + Result;
end;
function TDDLSQLGeneratorAbsoluteDB.GenerateCreateSequence(ASequence: TSequenceMIK): string;
begin
inherited;
Result := 'INSERT INTO SQLITE_SEQUENCE (NAME, SEQ) VALUES (%s, %s);';
Result := Format(Result, [QuotedStr(ASequence.Name), IntToStr(0)]);
end;
function TDDLSQLGeneratorAbsoluteDB.GenerateCreateTable(ATable: TTableMIK): string;
var
oSQL: TStringBuilder;
oColumn: TPair<string,TColumnMIK>;
begin
oSQL := TStringBuilder.Create;
Result := inherited GenerateCreateTable(ATable);
try
if ATable.Database.Schema <> '' then
oSQL.Append(Format(Result, [ATable.Database.Schema + '.' + ATable.Name]))
else
oSQL.Append(Format(Result, [ATable.Name]));
/// <summary>
/// Add Colunas
/// </summary>
for oColumn in ATable.FieldsSort do
begin
oSQL.AppendLine;
oSQL.Append(' ' + BuilderCreateFieldDefinition(oColumn.Value));
oSQL.Append(',');
end;
/// <summary>
/// Add PrimariKey
/// </summary>
if ATable.PrimaryKey.Fields.Count > 0 then
begin
oSQL.AppendLine;
oSQL.Append(BuilderPrimayKeyDefinition(ATable));
end;
/// <summary>
/// Add Indexe
/// </summary>
if ATable.IndexeKeys.Count > 0 then
begin
oSQL.AppendLine;
oSQL.Append(BuilderIndexeDefinition(ATable));
end;
oSQL.AppendLine;
Result := oSQL.ToString;
finally
oSQL.Free;
end;
end;
function TDDLSQLGeneratorAbsoluteDB.GenerateDropSequence(ASequence: TSequenceMIK): string;
begin
inherited;
Result := 'DELETE FROM SQLITE_SEQUENCE WHERE NAME = %s;';
Result := Format(Result, [QuotedStr(ASequence.Name)]);
end;
function TDDLSQLGeneratorAbsoluteDB.GenerateDropTable(ATable: TTableMIK): string;
begin
Result := inherited GenerateDropTable(ATable);
end;
function TDDLSQLGeneratorAbsoluteDB.GetSupportedFeatures: TSupportedFeatures;
begin
Result := inherited GetSupportedFeatures - [TSupportedFeature.ForeignKeys,
TSupportedFeature.Checks,
TSupportedFeature.Views,
TSupportedFeature.Triggers];
end;
initialization
TSQLDriverRegister.GetInstance.RegisterDriver(dnAbsoluteDB, TDDLSQLGeneratorAbsoluteDB.Create);
end.
|
program testboolean02(output);
var i, i1, j, j1:Boolean;
begin
i := True;
j := False;
if i <= j then
writeln('bad! i <= j');
if j <= i then
writeln('false correctly implies true');
if i <= True then
writeln('true correctly implies true');
if False <= j then
writeln('false correctly implies false');
if i <> j then
writeln('true does not equal false');
if i = True then
writeln('true equals true');
if j = False then
writeln('false equals false');
i1 := not j;
j1 := not i;
writeln('couple more ways to write True: ', not j, ' ', i1);
writeln('couple more ways to write False: ', not i, ' ' , j1);
if i and (not j) then
writeln('True and (not False) is true!');
writeln('');
writeln('truth tables');
writeln('True and True = ', i and i1);
writeln('True and False = ', i and j);
writeln('False and True = ', False and i1);
writeln('False and False = ', j and j1);
writeln('');
writeln('True or True = ', i or i1);
writeln('True or False = ', i or j);
writeln('False or True = ', j or i1);
writeln('False or False = ', False or j1);
writeln('');
writeln('XOR is done with the <> operator');
writeln('True xor True = ', i <> i1);
writeln('True xor False = ', True <> j);
writeln('False xor True = ', j1 <> i);
writeln('False xor False = ', j <> j1);
writeln('');
writeln('False = True ', i = j);
writeln('True = False ', j1 = i1);
end.
|
unit TabAdjustMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, CheckLst, JvExCheckLst, JvCheckListBox, StrUtils;
const DeleteFromAll = 98;
DeleteFromCurrent = 99;
type
TTabAdjustForm = class(TForm)
TabList: TJvCheckListBox;
CancelButton: TButton;
ChangeButton: TButton;
AffectGroup: TRadioGroup;
procedure ChangeButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
private
FSortTabs: Boolean;
procedure SetSortTabs(const Value: Boolean);
{ Private declarations }
public
{ Public declarations }
property SortTabs: Boolean read FSortTabs write SetSortTabs;
end;
var
TabAdjustForm: TTabAdjustForm;
implementation
{$R *.dfm}
procedure TTabAdjustForm.CancelButtonClick(Sender: TObject);
begin
ModalResult := 1;
end;
procedure TTabAdjustForm.SetSortTabs(const Value: Boolean);
begin
FSortTabs := Value;
Caption := ifthen(SortTabs, 'Sort Tabs', 'Delete Tabs');
AffectGroup.Visible := not FSortTabs;
end;
procedure TTabAdjustForm.ChangeButtonClick(Sender: TObject);
begin
if AffectGroup.Visible then
begin
if AffectGroup.ItemIndex = 1 then
ModalResult := DeleteFromAll
else
ModalResult := DeleteFromCurrent;
end
else
ModalResult := 50;
end;
end.
|
{*********************************************************}
{* OVCUTILS.PAS 4.06 *}
{*********************************************************}
{* ***** BEGIN LICENSE BLOCK ***** *}
{* Version: MPL 1.1 *}
{* *}
{* 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 TurboPower Orpheus *}
{* *}
{* The Initial Developer of the Original Code is TurboPower Software *}
{* *}
{* Portions created by TurboPower Software Inc. are Copyright (C)1995-2002 *}
{* TurboPower Software Inc. All Rights Reserved. *}
{* *}
{* Contributor(s): *}
{* *}
{* ***** END LICENSE BLOCK ***** *}
unit OvcUtils;
{ Miscellaneous Utilities }
interface
procedure StripCharSeq(CharSeq: string; var Str: string);
procedure StripCharFromEnd(Chr: Char; var Str: string);
procedure StripCharFromFront(Chr: Char; var Str: string);
implementation
{ Strips specified character(s) from the string and returns the modified string}
procedure StripCharSeq(CharSeq: string; var Str: string);
begin
while Pos(CharSeq, Str) > 0 do
Delete(Str, Pos(CharSeq, Str), Length(CharSeq));
end;
{ Strips the specified character from the end of the string }
procedure StripCharFromEnd(Chr: Char; var Str: string);
begin
while Str[Length(Str)] = Chr do Delete(Str, Length(Str), 1);
end;
{ Strips the specified character from the beginning of the string }
procedure StripCharFromFront(Chr: Char; var Str: string);
begin
while Str[1] = Chr do Delete(Str, 1, 1);
end;
end.
|
{ SMIX is Copyright 1995 by Ethan Brodsky. All rights reserved. }
unit XMS;
interface
{Initialization}
function XMSInstalled: boolean;
procedure XMSInit;
{Informational}
function XMSGetVersion: word;
function XMSGetFreeMem: word;
{Allocation and deallocation}
function XMSAllocate(var Handle: word; Size: word): boolean;
function XMSReallocate(Handle: word; NewSize: word): boolean;
function XMSFree(Handle: word): boolean;
{Memory moves}
type
PMoveParams = ^TMoveParams;
TMoveParams =
record
Length : LongInt; {Length must be a multiple of two}
SourceHandle : word;
SourceOffset : LongInt;
DestHandle : word;
DestOffset : LongInt;
end;
function XMSMove(Params: PMoveParams): boolean;
implementation {栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩}
var
XMSDriver: pointer;
{様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様}
function XMSInstalled: boolean; assembler;
asm
mov ax, 4300h
int 2Fh
cmp al, 80h
jne @NoXMSDriver
mov al, TRUE
jmp @Done
@NoXMSDriver:
mov al, FALSE
@Done:
end;
{陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳}
procedure XMSInit; assembler;
asm
mov ax, 4310h
int 2Fh
mov word ptr [XMSDriver], bx
mov word ptr [XMSDriver+2], es
end;
{様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様}
function XMSGetVersion: word; assembler;
asm
mov ah, 00h
call XMSDriver
end;
{陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳}
function XMSGetFreeMem: word; assembler;
asm
mov ah, 08h
call XMSDriver
mov ax, dx
end;
{様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様}
function XMSAllocate(var Handle: word; Size: word): boolean; assembler;
asm
mov ah, 09h
mov dx, Size
call XMSDriver
les di, Handle
mov es:[di], dx
end;
{陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳}
function XMSReallocate(Handle: word; NewSize: word): boolean; assembler;
asm
mov ah, 0Fh
mov bx, NewSize
mov dx, Handle
call XMSDriver
end;
{陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳陳}
function XMSFree(Handle: word): boolean; assembler;
asm
mov ah, 0Ah
mov dx, Handle
call XMSDriver
end;
{様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様様}
function XMSMove(Params: PMoveParams): boolean; assembler;
asm
push ds
mov ah, 0Bh
lds si, Params
call XMSDriver
pop ds
end;
end. {栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩栩} |
unit DCPcast128;
{$MODE Delphi}
interface
uses
Classes, Sysutils, Crypto;
type
TCipherCAST128= class(TCipher)
protected
KeyData: array[0..31] of DWord;
Rounds: longword;
procedure InitKey(const Key; Size: longword); override;
public
destructor Destroy; override;
class function Algorithm: TCipherAlgorithm; override;
class function MaxKeySize: integer; override;
class function SelfTest: boolean; override;
class function BlockSize: Integer; override;
procedure EncryptBlock(const InData; var OutData); override;
procedure DecryptBlock(const InData; var OutData); override;
end;
implementation
{$R-}{$Q-}
{$I DCPcast128.inc}
function LRot32(a, n: dword): dword;
begin
Result:= (a shl n) or (a shr (32-n));
end;
destructor TCipherCAST128.Destroy;
begin
FillChar(KeyData,Sizeof(KeyData),$FF);
Rounds:= 0;
inherited Destroy;
end;
class function TCipherCAST128.MaxKeySize: integer;
begin
Result:= 128;
end;
class function TCipherCast128.BlockSize: Integer;
begin
Result := 64;
end;
class function TCipherCAST128.Algorithm: TCipherAlgorithm;
begin
Result:= caCAST128;
end;
class function TCipherCAST128.SelfTest: boolean;
const
Key: array[0..15] of byte=
($01,$23,$45,$67,$12,$34,$56,$78,$23,$45,$67,$89,$34,$56,$78,$9A);
InBlock: array[0..7] of byte=
($01,$23,$45,$67,$89,$AB,$CD,$EF);
Out128: array[0..7] of byte=
($23,$8B,$4F,$E5,$84,$7E,$44,$B2);
Out80: array[0..7] of byte=
($EB,$6A,$71,$1A,$2C,$02,$27,$1B);
Out40: array[0..7] of byte=
($7A,$C8,$16,$D1,$6E,$9B,$30,$2E);
var
Block: array[0..7] of byte;
Cipher: TCipherCAST128;
begin
FillChar(Block, SizeOf(Block), 0);
Cipher:= TCipherCAST128.Create(@Key,128);
Cipher.EncryptBlock(InBlock,Block);
Result:= boolean(CompareMem(@Block,@Out128,8));
Cipher.DecryptBlock(Block,Block);
Result:= Result and boolean(CompareMem(@Block,@InBlock,8));
Cipher.Free;
Cipher := TCipherCAST128.Create(@Key,80);
Cipher.EncryptBlock(InBlock,Block);
Result:= Result and boolean(CompareMem(@Block,@Out80,8));
Cipher.DecryptBlock(Block,Block);
Result:= Result and boolean(CompareMem(@Block,@InBlock,8));
Cipher.Free;
Cipher := TCipherCAST128.Create(@Key,40);
Cipher.EncryptBlock(InBlock,Block);
Result:= Result and boolean(CompareMem(@Block,@Out40,8));
Cipher.DecryptBlock(Block,Block);
Result:= Result and boolean(CompareMem(@Block,@InBlock,8));
Cipher.Free;
end;
procedure TCipherCAST128.InitKey(const Key; Size: longword);
var
x, t, z: array[0..3] of DWord;
i: longword;
begin
Size:= Size div 8;
if Size<= 10 then
Rounds:= 12
else
Rounds:= 16;
FillChar(x, Sizeof(x), 0);
Move(Key,x,Size);
x[0]:= (x[0] shr 24) or ((x[0] shr 8) and $FF00) or ((x[0] shl 8) and $FF0000) or (x[0] shl 24);
x[1]:= (x[1] shr 24) or ((x[1] shr 8) and $FF00) or ((x[1] shl 8) and $FF0000) or (x[1] shl 24);
x[2]:= (x[2] shr 24) or ((x[2] shr 8) and $FF00) or ((x[2] shl 8) and $FF0000) or (x[2] shl 24);
x[3]:= (x[3] shr 24) or ((x[3] shr 8) and $FF00) or ((x[3] shl 8) and $FF0000) or (x[3] shl 24);
i:= 0;
while i< 32 do
begin
case (i and 4) of
0:
begin
z[0]:= x[0] xor cast_sbox5[(x[3] shr 16) and $FF] xor
cast_sbox6[x[3] and $FF] xor cast_sbox7[x[3] shr 24] xor
cast_sbox8[(x[3] shr 8) and $FF] xor cast_sbox7[x[2] shr 24];
t[0]:= z[0];
z[1]:= x[2] xor cast_sbox5[z[0] shr 24] xor
cast_sbox6[(z[0] shr 8) and $FF] xor cast_sbox7[(z[0] shr 16) and $FF] xor
cast_sbox8[z[0] and $FF] xor cast_sbox8[(x[2] shr 8) and $FF];
t[1]:= z[1];
z[2]:= x[3] xor cast_sbox5[z[1] and $FF] xor
cast_sbox6[(z[1] shr 8) and $FF] xor cast_sbox7[(z[1] shr 16) and $FF] xor
cast_sbox8[z[1] shr 24] xor cast_sbox5[(x[2] shr 16) and $FF];
t[2]:= z[2];
z[3]:= x[1] xor cast_sbox5[(z[2] shr 8) and $FF] xor
cast_sbox6[(z[2] shr 16) and $FF] xor cast_sbox7[z[2] and $FF] xor
cast_sbox8[z[2] shr 24] xor cast_sbox6[x[2] and $FF];
t[3]:= z[3];
end;
4:
begin
x[0]:= z[2] xor cast_sbox5[(z[1] shr 16) and $FF] xor
cast_sbox6[z[1] and $FF] xor cast_sbox7[z[1] shr 24] xor
cast_sbox8[(z[1] shr 8) and $FF] xor cast_sbox7[z[0] shr 24];
t[0]:= x[0];
x[1]:= z[0] xor cast_sbox5[x[0] shr 24] xor
cast_sbox6[(x[0] shr 8) and $FF] xor cast_sbox7[(x[0] shr 16) and $FF] xor
cast_sbox8[x[0] and $FF] xor cast_sbox8[(z[0] shr 8) and $FF];
t[1]:= x[1];
x[2]:= z[1] xor cast_sbox5[x[1] and $FF] xor
cast_sbox6[(x[1] shr 8) and $FF] xor cast_sbox7[(x[1] shr 16) and $FF] xor
cast_sbox8[x[1] shr 24] xor cast_sbox5[(z[0] shr 16) and $FF];
t[2]:= x[2];
x[3]:= z[3] xor cast_sbox5[(x[2] shr 8) and $FF] xor
cast_sbox6[(x[2] shr 16) and $FF] xor cast_sbox7[x[2] and $FF] xor
cast_sbox8[x[2] shr 24] xor cast_sbox6[z[0] and $FF];
t[3]:= x[3];
end;
end;
case (i and 12) of
0,12:
begin
KeyData[i+0]:= cast_sbox5[t[2] shr 24] xor cast_sbox6[(t[2] shr 16) and $FF] xor
cast_sbox7[t[1] and $FF] xor cast_sbox8[(t[1] shr 8) and $FF];
KeyData[i+1]:= cast_sbox5[(t[2] shr 8) and $FF] xor cast_sbox6[t[2] and $FF] xor
cast_sbox7[(t[1] shr 16) and $FF] xor cast_sbox8[t[1] shr 24];
KeyData[i+2]:= cast_sbox5[t[3] shr 24] xor cast_sbox6[(t[3] shr 16) and $FF] xor
cast_sbox7[t[0] and $FF] xor cast_sbox8[(t[0] shr 8) and $FF];
KeyData[i+3]:= cast_sbox5[(t[3] shr 8) and $FF] xor cast_sbox6[t[3] and $FF] xor
cast_sbox7[(t[0] shr 16) and $FF] xor cast_sbox8[t[0] shr 24];
end;
4,8:
begin
KeyData[i+0]:= cast_sbox5[t[0] and $FF] xor cast_sbox6[(t[0] shr 8) and $FF] xor
cast_sbox7[t[3] shr 24] xor cast_sbox8[(t[3] shr 16) and $FF];
KeyData[i+1]:= cast_sbox5[(t[0] shr 16) and $FF] xor cast_sbox6[t[0] shr 24] xor
cast_sbox7[(t[3] shr 8) and $FF] xor cast_sbox8[t[3] and $FF];
KeyData[i+2]:= cast_sbox5[t[1] and $FF] xor cast_sbox6[(t[1] shr 8) and $FF] xor
cast_sbox7[t[2] shr 24] xor cast_sbox8[(t[2] shr 16) and $FF];
KeyData[i+3]:= cast_sbox5[(t[1] shr 16) and $FF] xor cast_sbox6[t[1] shr 24] xor
cast_sbox7[(t[2] shr 8) and $FF] xor cast_sbox8[t[2] and $FF];
end;
end;
case (i and 12) of
0:
begin
KeyData[i+0]:= KeyData[i+0] xor cast_sbox5[(z[0] shr 8) and $FF];
KeyData[i+1]:= KeyData[i+1] xor cast_sbox6[(z[1] shr 8) and $FF];
KeyData[i+2]:= KeyData[i+2] xor cast_sbox7[(z[2] shr 16) and $FF];
KeyData[i+3]:= KeyData[i+3] xor cast_sbox8[z[3] shr 24];
end;
4:
begin
KeyData[i+0]:= KeyData[i+0] xor cast_sbox5[x[2] shr 24];
KeyData[i+1]:= KeyData[i+1] xor cast_sbox6[(x[3] shr 16) and $FF];
KeyData[i+2]:= KeyData[i+2] xor cast_sbox7[x[0] and $FF];
KeyData[i+3]:= KeyData[i+3] xor cast_sbox8[x[1] and $FF];
end;
8:
begin
KeyData[i+0]:= KeyData[i+0] xor cast_sbox5[(z[2] shr 16) and $FF];
KeyData[i+1]:= KeyData[i+1] xor cast_sbox6[z[3] shr 24];
KeyData[i+2]:= KeyData[i+2] xor cast_sbox7[(z[0] shr 8) and $FF];
KeyData[i+3]:= KeyData[i+3] xor cast_sbox8[(z[1] shr 8) and $FF];
end;
12:
begin
KeyData[i+0]:= KeyData[i+0] xor cast_sbox5[x[0] and $FF];
KeyData[i+1]:= KeyData[i+1] xor cast_sbox6[x[1] and $FF];
KeyData[i+2]:= KeyData[i+2] xor cast_sbox7[x[2] shr 24];
KeyData[i+3]:= KeyData[i+3] xor cast_sbox8[(x[3] shr 16) and $FF];
end;
end;
if (i >= 16) then
begin
KeyData[i+0]:= KeyData[i+0] and 31;
KeyData[i+1]:= KeyData[i+1] and 31;
KeyData[i+2]:= KeyData[i+2] and 31;
KeyData[i+3]:= KeyData[i+3] and 31;
end;
Inc(i,4);
end;
end;
procedure TCipherCAST128.EncryptBlock(const InData; var OutData);
var
t, l, r: DWord;
begin
l:= Pdword(@InData)^;
r:= Pdword(Pointer(@InData)+4)^;
l:= (l shr 24) or ((l shr 8) and $FF00) or ((l shl 8) and $FF0000) or (l shl 24);
r:= (r shr 24) or ((r shr 8) and $FF00) or ((r shl 8) and $FF0000) or (r shl 24);
t:= LRot32(KeyData[0]+r, KeyData[0+16]);
l:= l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t:= LRot32(KeyData[1] xor l, KeyData[1+16]);
r:= r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) +
cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t:= LRot32(KeyData[2]-r, KeyData[2+16]);
l:= l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor
cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t:= LRot32(KeyData[3]+l, KeyData[3+16]);
r:= r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t:= LRot32(KeyData[4] xor r, KeyData[4+16]);
l:= l xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) +
cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t:= LRot32(KeyData[5]-l, KeyData[5+16]);
r:= r xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor
cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t:= LRot32(KeyData[6]+r, KeyData[6+16]);
l:= l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t:= LRot32(KeyData[7] xor l, KeyData[7+16]);
r:= r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) +
cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t:= LRot32(KeyData[8]-r, KeyData[8+16]);
l:= l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor
cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t:= LRot32(KeyData[9]+l, KeyData[9+16]);
r:= r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t:= LRot32(KeyData[10] xor r, KeyData[10+16]);
l:= l xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) +
cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t:= LRot32(KeyData[11]-l, KeyData[11+16]);
r:= r xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor
cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
if Rounds> 12 then
begin
t:= LRot32(KeyData[12]+r, KeyData[12+16]);
l:= l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t:= LRot32(KeyData[13] xor l, KeyData[13+16]);
r:= r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) +
cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t:= LRot32(KeyData[14]-r, KeyData[14+16]);
l:= l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor
cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t:= LRot32(KeyData[15]+l, KeyData[15+16]);
r:= r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
end;
l:= (l shr 24) or ((l shr 8) and $FF00) or ((l shl 8) and $FF0000) or (l shl 24);
r:= (r shr 24) or ((r shr 8) and $FF00) or ((r shl 8) and $FF0000) or (r shl 24);
Pdword(@OutData)^:= r;
Pdword(pointer(@OutData)+4)^:= l;
end;
procedure TCipherCAST128.DecryptBlock(const InData; var OutData);
var
t, l, r: DWord;
begin
r:= Pdword(@InData)^;
l:= Pdword(pointer(@InData)+4)^;
l:= (l shr 24) or ((l shr 8) and $FF00) or ((l shl 8) and $FF0000) or (l shl 24);
r:= (r shr 24) or ((r shr 8) and $FF00) or ((r shl 8) and $FF0000) or (r shl 24);
if Rounds> 12 then
begin
t:= LRot32(KeyData[15]+l, KeyData[15+16]);
r:= r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t:= LRot32(KeyData[14]-r, KeyData[14+16]);
l:= l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor
cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t:= LRot32(KeyData[13] xor l, KeyData[13+16]);
r:= r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) +
cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t:= LRot32(KeyData[12]+r, KeyData[12+16]);
l:= l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
end;
t:= LRot32(KeyData[11]-l, KeyData[11+16]);
r:= r xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor
cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t:= LRot32(KeyData[10] xor r, KeyData[10+16]);
l:= l xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) +
cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t:= LRot32(KeyData[9]+l, KeyData[9+16]);
r:= r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t:= LRot32(KeyData[8]-r, KeyData[8+16]);
l:= l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor
cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t:= LRot32(KeyData[7] xor l, KeyData[7+16]);
r:= r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) +
cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t:= LRot32(KeyData[6]+r, KeyData[6+16]);
l:= l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t:= LRot32(KeyData[5]-l, KeyData[5+16]);
r:= r xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor
cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t:= LRot32(KeyData[4] xor r, KeyData[4+16]);
l:= l xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) +
cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t:= LRot32(KeyData[3]+l, KeyData[3+16]);
r:= r xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
t:= LRot32(KeyData[2]-r, KeyData[2+16]);
l:= l xor (((cast_sbox1[t shr 24] + cast_sbox2[(t shr 16) and $FF]) xor
cast_sbox3[(t shr 8) and $FF]) - cast_sbox4[t and $FF]);
t:= LRot32(KeyData[1] xor l, KeyData[1+16]);
r:= r xor (((cast_sbox1[t shr 24] - cast_sbox2[(t shr 16) and $FF]) +
cast_sbox3[(t shr 8) and $FF]) xor cast_sbox4[t and $FF]);
t:= LRot32(KeyData[0]+r, KeyData[0+16]);
l:= l xor (((cast_sbox1[t shr 24] xor cast_sbox2[(t shr 16) and $FF]) -
cast_sbox3[(t shr 8) and $FF]) + cast_sbox4[t and $FF]);
l:= (l shr 24) or ((l shr 8) and $FF00) or ((l shl 8) and $FF0000) or (l shl 24);
r:= (r shr 24) or ((r shr 8) and $FF00) or ((r shl 8) and $FF0000) or (r shl 24);
Pdword(@OutData)^:= l;
Pdword(pointer(@OutData)+4)^:= r;
end;
end.
|
unit U_dmRelDenuncias;
interface
uses
System.SysUtils, System.Classes, 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,
Datasnap.Provider, Datasnap.DBClient, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, FMX.frxClass, FMX.frxDBSet, ppCtrls, ppDB, ppDBPipe,
ppVar, ppPrnabl, ppClass, ppBands, ppCache, ppDesignLayer, ppParameter,
ppComm, ppRelatv, ppProd, ppReport, daDataView, daQueryDataView, daFireDAC,
ppModule, daDataModule;
type
TdmRelDenuncias = class(TDataModule)
frxRelDenuncias: TfrxReport;
frxdsRelDenuncias: TfrxDBDataset;
frxDBDataset1: TfrxDBDataset;
ppRelDenuncias: TppReport;
ppParameterList1: TppParameterList;
ppDesignLayers1: TppDesignLayers;
ppDesignLayer1: TppDesignLayer;
ppHeaderBand1: TppHeaderBand;
ppDetailBand1: TppDetailBand;
ppFooterBand1: TppFooterBand;
ppTitleBand1: TppTitleBand;
ppLabel1: TppLabel;
ppLine1: TppLine;
ppSystemVariable1: TppSystemVariable;
pplblPeriodo: TppLabel;
ppLine3: TppLine;
pplblTextoRodape: TppLabel;
ppDBPipeline1: TppDBPipeline;
ppLabel3: TppLabel;
ppLabel4: TppLabel;
ppLabel5: TppLabel;
ppLabel6: TppLabel;
ppdbListaDenuncias: TppDBPipeline;
ppDBText2: TppDBText;
ppDBText3: TppDBText;
ppListaDenuncias: TppReport;
ppParameterList2: TppParameterList;
ppDesignLayers2: TppDesignLayers;
ppDesignLayer2: TppDesignLayer;
ppHeaderBand2: TppHeaderBand;
ppDetailBand2: TppDetailBand;
ppFooterBand2: TppFooterBand;
ppLabel7: TppLabel;
ppDBText4: TppDBText;
ppDBText5: TppDBText;
ppTitleBand2: TppTitleBand;
ppLine2: TppLine;
ppDBText6: TppDBText;
pplblPeriodo1: TppLabel;
ppDadosRodapé1: TppLabel;
ppSystemVariable2: TppSystemVariable;
ppLine5: TppLine;
ppDBText7: TppDBText;
cdsRelDenuncias: TClientDataSet;
dspRelDenuncias: TDataSetProvider;
dsRelDenuncias: TDataSource;
ppGroup1: TppGroup;
ppGroupHeaderBand1: TppGroupHeaderBand;
ppGroupFooterBand1: TppGroupFooterBand;
ppShape1: TppShape;
ppLabel2: TppLabel;
ppDBText1: TppDBText;
FDqryRelDenuncias: TFDQuery;
ppLabel8: TppLabel;
ppDBText8: TppDBText;
ppLabel9: TppLabel;
ppDBText9: TppDBText;
ppLabel10: TppLabel;
ppLabel11: TppLabel;
ppDBText10: TppDBText;
ppLabel12: TppLabel;
ppDBText11: TppDBText;
private
{ Private declarations }
public
{ Public declarations }
end;
var
dmRelDenuncias: TdmRelDenuncias;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
uses U_dmSISVISA;
{$R *.dfm}
end.
|
unit uFrmUpdate;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, PngCustomButton, ExtCtrls, RzPanel, RzPrgres,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, RzEdit,
XPMan, IniFiles, VCLUnZip, VCLZip, superobject, uAutoUpdate, uTFSystem;
type
TFrmUpdate = class(TForm)
RzPanel1: TRzPanel;
Label1: TLabel;
RzPanel2: TRzPanel;
PngCustomButton1: TPngCustomButton;
lblHeadInfo: TLabel;
prgMain: TRzProgressBar;
lblProgress: TLabel;
memInfo: TRzMemo;
XPManifest1: TXPManifest;
UpdateTimer: TTimer;
VCLZip: TVCLZip;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure IdHTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Integer);
procedure IdHTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Integer);
procedure UpdateTimerTimer(Sender: TObject);
procedure VCLZipTotalPercentDone(Sender: TObject; Percent: Integer);
private
{ Private declarations }
//更新配置信息
m_UpdateConfig : RRsUpdateConfig;
//升级信息
m_UpdateInfo: RRsUpdateInfo;
//开始升级
function BeginUpdate(var strPatchFile: string): boolean;
//下载文件,返回下载文件路径
function DownloadFile(strUrl: string): string;
//解压文件,返回解压文件路径
function UnzipFileToDir(strZipFile: string): string;
//打开主程序
procedure ExecuteMainFile();
//打开升级程序
function ExecutePatchFile(strPatchFile: string): boolean;
//清空指定目录下的文件
function EmptyDir(strPath: string; bDelDir: boolean=false): boolean;
public
{ Public declarations }
class procedure ShowForm;
end;
var
FrmUpdate: TFrmUpdate;
implementation
{$R *.dfm}
class procedure TFrmUpdate.ShowForm;
begin
if FrmUpdate = nil then Application.CreateForm(TFrmUpdate, FrmUpdate);
FrmUpdate.Show;
end;
procedure TFrmUpdate.FormCreate(Sender: TObject);
begin
DoubleBuffered := true;
end;
procedure TFrmUpdate.FormShow(Sender: TObject);
begin
TAutoUpdateUtils.GetUpdateConfig(ExtractFilePath(Application.ExeName) + 'Update.ini',m_UpdateConfig);
memInfo.Clear;
memInfo.Lines.Add('当前在用的软件,详情如下:');
memInfo.Lines.Add(Format('升级地址:%s', [m_UpdateConfig.APIUrl]));
memInfo.Lines.Add(Format('项 目 ID:%s', [m_UpdateConfig.ProjectID]));
memInfo.Lines.Add(Format('版 本 号:%s', [m_UpdateConfig.ProjectVersion]));
memInfo.Lines.Add(Format('程 序 名:%s', [m_UpdateConfig.MainExeName]));
memInfo.Lines.Add('');
memInfo.Lines.Add('正在查找服务器是否存在可升级包,请稍候……');
UpdateTimer.Enabled := true;
end;
procedure TFrmUpdate.UpdateTimerTimer(Sender: TObject);
var
strPatchFile: string;
bUpdate: boolean;
begin
UpdateTimer.Enabled := false;
strPatchFile := '';
bUpdate := False;
try
if not TAutoUpdateUtils.GetUpdateInfo(m_UpdateConfig.APIUrl,m_UpdateConfig.ProjectID,
m_UpdateConfig.ProjectVersion,m_UpdateInfo) then
begin
memInfo.Lines.Add('获取更新信息失败');
exit;
end;
if not m_UpdateInfo.bNeedUpdate then
begin
memInfo.Lines.Add('系统没有找到新版的升级包');
exit;
end;
//查询服务器是否有升级包
memInfo.Lines.Add('服务器存在可升级包,详情如下:');
memInfo.Lines.Add(Format('版本号:%s', [m_UpdateInfo.strProjectVersion]));
memInfo.Lines.Add(Format('描 述:%s', [m_UpdateInfo.strUpdateBrief]));
memInfo.Lines.Add(Format('升级包:%s', [m_UpdateInfo.strPackageUrl])); //===后期删除
memInfo.Lines.Add(Format('程序名:%s', [m_UpdateInfo.strMainExeName])); //===后期删除
Application.ProcessMessages;
if m_UpdateInfo.strProjectVersion = '' then
begin
Box('升级包的版本号不能为空,请检查后重试');
Exit;
end;
if m_UpdateInfo.strMainExeName = '' then
begin
Box('升级包的程序名不能为空,请检查后重试');
Exit;
end;
if m_UpdateInfo.strPackageUrl = '' then
begin
Box('升级包的下载地址不能为空,请检查后重试');
Exit;
end;
bUpdate := BeginUpdate(strPatchFile);
finally
if bUpdate then bUpdate := ExecutePatchFile(strPatchFile);
if not bUpdate then ExecuteMainFile;
end;
end;
procedure TFrmUpdate.VCLZipTotalPercentDone(Sender: TObject; Percent: Integer);
begin
prgMain.PartsComplete := Percent * prgMain.TotalParts div 100;
Application.ProcessMessages;
end;
procedure TFrmUpdate.IdHTTPWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Integer);
begin
prgMain.PartsComplete := AWorkCount;
end;
procedure TFrmUpdate.IdHTTPWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Integer);
begin
prgMain.TotalParts := AWorkCountMax;
prgMain.PartsComplete := 0;
end;
function TFrmUpdate.BeginUpdate(var strPatchFile: string): boolean;
var
strUpdateFile, strUnzipPath: string;
begin
result := False;
if m_UpdateInfo.bNeedUpdate then
begin
strUpdateFile := DownloadFile(m_UpdateInfo.strPackageUrl);
if strUpdateFile <> '' then
begin
strUnzipPath := UnzipFileToDir(strUpdateFile);
if strUnzipPath <> '' then
begin
strPatchFile := strUnzipPath + 'Patch.exe';
result := True;
end;
end;
end;
end;
function TFrmUpdate.DownloadFile(strUrl: string): string;
var
IdHTTP: TIdHTTP;
Stream: TMemoryStream;
strUpdateFile: string;
begin
result := '';
strUpdateFile := ExtractFilePath(Application.ExeName) + 'Update.rar';
if FileExists(strUpdateFile) then if not DeleteFile(strUpdateFile) then exit;
lblProgress.Caption := '下载进度:';
memInfo.Lines.Add('');
memInfo.Lines.Add('开始下载文件……');
Application.ProcessMessages;
try
Stream := TMemoryStream.Create;
IdHTTP := TIdHTTP.Create(nil);
try
//下载升级包
IdHTTP.OnWork := IdHTTPWork;
IdHTTP.OnWorkBegin := IdHTTPWorkBegin;
IdHTTP.ReadTimeout := 3000;
IdHTTP.ConnectTimeout := 3000;
IdHTTP.Get(strUrl, Stream);
Stream.SaveToFile(strUpdateFile);
result := strUpdateFile;
memInfo.Lines.Add('下载文件成功');
Application.ProcessMessages;
finally
Stream.Free;
IdHTTP.Disconnect;
IdHTTP.Free;
end;
except on e : exception do
Box('下载文件异常,请检查后重试!'#13#10#13#10'下载地址:'+strUrl+#13#10#13#10+e.Message);
end;
end;
function TFrmUpdate.UnzipFileToDir(strZipFile: string): string;
var
strUnzipPath: string;
nFileCount: integer;
begin
result := '';
if not FileExists(strZipFile) then exit;
strUnzipPath := ExtractFilePath(Application.ExeName) + '_tf_update\';
if not DirectoryExists(strUnzipPath) then CreateDir(strUnzipPath);
if not EmptyDir(strUnzipPath) then exit;
lblProgress.Caption := '解压进度:';
memInfo.Lines.Add('');
memInfo.Lines.Add('解压开始,请稍候……');
Application.ProcessMessages;
try
VCLZip.OverwriteMode:=Always; //总是覆盖模式
VCLZip.Recurse := True; //包含下级目录中的文件
VCLZip.RelativePaths := True; //是否保持目录结构
VCLZip.StorePaths := True; //不保存目录信息
VCLZip.RecreateDirs := True; //创建目录
VCLZip.Password := '';
VCLZip.FilesList.Clear;
VCLZip.FilesList.Add('*.*');
VCLZip.DestDir := strUnzipPath;
VCLZip.ZipName := strZipFile;
nFileCount := VCLZip.UnZip;
result := strUnzipPath;
memInfo.Lines.Add(Format('解压完毕,共有%d个文件', [nFileCount]));
except on e : exception do
Box('解压升级包异常,请检查后重试!'#13#10#13#10'异常信息:'+e.Message);
end;
Application.ProcessMessages;
end;
procedure TFrmUpdate.ExecuteMainFile();
var
strPath, strMainExeName: string;
begin
strMainExeName := m_UpdateConfig.MainExeName;
if Pos('.', strMainExeName) = 0 then strMainExeName := strMainExeName + '.exe';
//判断本地是否存在可执行程序
strPath := ExtractFilePath(Application.ExeName);
if FileExists(strPath + strMainExeName) then
begin
WinExec(PChar(strPath + strMainExeName+ ' ' + paramstr(1)) , SW_SHOW);
end;
Close; //打开主程序,关闭程升级序
end;
function TFrmUpdate.ExecutePatchFile(strPatchFile: string): boolean;
var
strProjectVersion, strMainExeName, strSetupPath: string;
strParam: string;
begin
result := False;
try
if not FileExists(strPatchFile) then Exit;
strSetupPath := ExtractFilePath(Application.ExeName);
strProjectVersion := m_UpdateInfo.strProjectVersion;
strMainExeName := m_UpdateInfo.strMainExeName;
if strMainExeName = '' then strMainExeName := m_UpdateConfig.MainExeName;
if strMainExeName <> '' then
begin
if Pos('.', strMainExeName) = 0 then strMainExeName := strMainExeName + '.exe';
end;
strParam := Format(' %s %s %s', [strProjectVersion, strMainExeName, strSetupPath]);
WinExec(PChar(strPatchFile + strParam), SW_SHOW);
result := True;
finally
Close; //打开升级程序,关闭程升级序
end;
end;
function TFrmUpdate.EmptyDir(strPath: string; bDelDir: boolean): boolean;
var
SearchRec: TSearchRec;
strFile: string;
begin
result := true;
if strPath[Length(strPath)] <> '\' then strPath := strPath + '\';
try
if FindFirst(strPath+'*.*', faAnyFile, SearchRec) = 0 then
begin
repeat
if SearchRec.Name = '.' then continue;
if SearchRec.Name = '..' then continue;
strFile := strPath + SearchRec.Name;
if (SearchRec.Attr and faDirectory) = faDirectory then
begin
EmptyDir(strFile, true);
end
else
begin
FileSetAttr(strFile, 0);
result := result and DeleteFile(strFile);
end;
until FindNext(SearchRec) <> 0;
end;
FindClose(SearchRec);
if bDelDir then result := result and RemoveDir(strPath);
except
result := false;
end;
end;
end.
|
unit UDAOCaptura;
interface
uses
System.SysUtils,System.StrUtils,Classes,DB,DBClient, zdataset, ZDbcIntfs,
UDMConexion, UFolioCaptura, URegistroCaptura, Variants;
type
TDAOCaptura = class
private
FQuery : TZquery;
public
constructor create;
destructor destroy;
procedure AgregarIdentificacionFolio(p_IdenFoli: int64; p_IdenIden: int32;
p_ObseFoliIden: string; p_DescTipoIden: string;
p_NumeDocu: string);
procedure AgregarDatosPanilla(p_IdenDapl: int64;
p_IdenFond: Int32; p_FechNomi: string;
p_PeriCoti: string; p_FechPago: string);
procedure AgregarNovedadFolio(p_IdenFoli: int64; p_IdenTare: int32;
p_ObseFoli : string; p_TipoObse:Char);
function AgregarNuevaIdentificacion(p_DescIdenTipoIden: string; p_DescFuenIden: string;
p_NumeDocu: string; p_PrimNomb: string; p_SeguNomb : string;
p_PrimApel: string; p_SeguApel: string): int32;
function AsignarFolio(p_desctare: string; p_CodiFoli: string;
p_nombusua:string): TFolioCaptura;
Function CambiarEstadoCarpeta(p_IdenCarp: int32): Boolean;
function ConsultarDatosANI(p_DescTipoIden: string; p_numedocu: string;
p_primnomb:string; p_primapel:string): TDataSource;
function ConsultarDatosAsociados(p_IdenFoli: int64): TDataSource;
function ConsultarDatosMTI(p_identipo: variant; p_numedocu: string;
p_primnomb:string; p_primapel:string): TDataSource;
function ConsultarFondos: TDataSource;
function ConsultarPersonasFolio(p_idenfoli: int64): TList;
function ConsultarTiposIdentificacion: TDataSource;
procedure CancelarTransaccion;
Function DesbloquearFolio(p_IdenFoli: int64; p_DescTare: string) : Boolean;
procedure EliminarBloqueoFolioNoCapturable(p_IdenFoli: int64);
procedure EliminarDatosAsociacion(p_IdenFoid: int64; p_IdenFoli: Int64;
p_IdenCarp: Int64; p_IdenDapl: string);
procedure RegistrarMarcaFolio(p_IdenFoli: int64);
procedure FinalizarTransaccion;
procedure IniciarTransaccion;
end;
implementation
//Uses
//UCapturaDemanda;
{$REGION 'METODOS PROPIOS'}
procedure TDAOCaptura.AgregarIdentificacionFolio(p_IdenFoli: int64; p_IdenIden: int32;
p_ObseFoliIden: string;
p_DescTipoIden: string; p_NumeDocu: string);
begin
with FQuery do
begin
Close;
SQL.Clear;
SQL.Add('SELECT idfolioidentificacion');
SQL.Add(Format('FROM %s.FOLIOIDENTIFICACION ', [DMConexion.esquema]));
SQL.Add(Format('WHERE idfolio = %d AND ididentificacion = %d ',[p_IdenFoli,p_IdenIden]));
Open;
if IsEmpty then
begin
Close;
SQL.Clear;
SQL.Add(Format('INSERT INTO %s.FOLIOIDENTIFICACION (idfolio, ididentificacion, '
+ 'observacion, usuario)', [DMConexion.esquema]));
SQL.Add(Format(' VALUES (%d,%d,%s,''%s'')',
[p_IdenFoli, p_IdenIden,
ifthen(p_ObseFoliIden = '', 'NULL',QuotedStr(p_ObseFoliIden)),
ParamStr(1)]));
ExecSQL;
end
else
raise Exception.Create
(Format('El Folio [%d] ya se encuentra asociado con el Documento [%s - %s].',
[p_IdenFoli,p_DescTipoIden,p_NumeDocu]));
end;
end;
procedure TDAOCaptura.AgregarDatosPanilla(p_IdenDapl: int64;
p_IdenFond : int32; p_FechNomi: string;
p_PeriCoti: string; p_FechPago: string);
var
AdicWher: string;
begin
if (p_IdenFond > 0) or (p_FechNomi <> '') or (p_PeriCoti <> '') or (p_FechPago <> '') then
begin
with FQuery do
begin
Close;
SQL.Clear;
SQL.Add(Format('UPDATE %s.DATOPLANILLA ', [DMConexion.esquema]));
SQL.Add(' SET ');
adicwher:= '';
if p_IdenFond > 0 then
AdicWher := AdicWher + Format('idfondo = %d ',[p_IdenFond]);
if p_FechNomi <> '' then
AdicWher:= AdicWher +
IfThen(adicwher <> '',',', '')
+ Format('fechanomina = %s ',
[QuotedStr(FormatDateTime('yyyy-mm-dd',StrToDateDef(p_FechNomi,0)))]);
if p_PeriCoti <> '' then
AdicWher:= AdicWher + IfThen(adicwher <> '',',', '')
+ Format('periodocotizacion = %s ',
[QuotedStr(FormatDateTime('yyyy-mm-dd',StrToDateDef(p_PeriCoti,0)))]);
if p_FechPago <> '' then
AdicWher:= AdicWher + IfThen(adicwher <> '',',', '')
+ Format('fechapago = %s ',
[QuotedStr(FormatDateTime('yyyy-mm-dd',StrToDateDef(p_FechPago,0)))]);
SQL.Add(AdicWher);
SQL.Add(Format(' WHERE iddatoplanilla = %d ',[p_IdenDapl]));
SQL.Add(' RETURNING iddatoplanilla');
Open;
if IsEmpty then
raise Exception.Create
('Imposible Actualizar información de Fechas y/o Fondo para el Folio Solicitado.');
end;
end
else
raise Exception.Create
('No se enviaron datos de actualización de Fechas y/o Fondo para el Folio Solicitado.');
end;
procedure TDAOCaptura.AgregarNovedadFolio(p_IdenFoli: int64; p_IdenTare: int32;
p_ObseFoli : string; p_TipoObse:Char);
begin
with FQuery do
begin
Close;
SQL.Clear;
SQL.Add(Format('INSERT INTO %s.OBSERVACIONFOLIO (idfolio, idtarea, observacion, '
+ 'tipoobservacion, usuario) ',[DMConexion.esquema]));
SQL.Add(Format(' VALUES (%d,%d,''%s'',''%s'',''%s'' )',
[p_IdenFoli, p_IdenTare, p_ObseFoli, p_TipoObse, Paramstr(1)]));
open;
end;
end;
function TDAOCaptura.AgregarNuevaIdentificacion(p_DescIdenTipoIden: string; p_DescFuenIden: string;
p_NumeDocu: string; p_PrimNomb: string; p_SeguNomb : string;
p_PrimApel: string; p_SeguApel: string): int32;
begin
with FQuery do
begin
Close;
SQL.Clear;
SQL.Add('SELECT p_idenidennuev');
SQL.Add(Format('FROM %s.FNC_AGREGARIDENTIFICACIONPERSONA '
+ '(''%s'', ''%s'',''%s'', %s, %s, %s, %s,''%s'')',
[DMConexion.esquema, p_DescIdenTipoIden, p_DescFuenIden, p_NumeDocu,
ifthen(p_PrimNomb = '', 'NULL',QuotedStr(p_PrimNomb)),
ifthen(p_SeguNomb = '', 'NULL',QuotedStr(p_SeguNomb)),
ifthen(p_PrimApel = '', 'NULL',QuotedStr(p_PrimApel)),
ifthen(p_SeguApel = '', 'NULL',QuotedStr(p_SeguApel)),
Paramstr(1)]));
Open;
if not IsEmpty then
begin
First;
Result:= FieldByName('p_idenidennuev').Value;
end
else
raise Exception.Create(Format('No es posible Registrar el Documento [%s - %s].',
[p_NumeDocu,p_DescIdenTipoIden]));
end;
end;
function TDAOCaptura.AsignarFolio(p_desctare: string; p_CodiFoli: string;
p_nombusua:string): TFolioCaptura;
{ FUNCION QUE OBTIENE UN FOLIO DE UNA CARPETA QUE SE ENCUENTRE EN ESTADO DE
GENERACION XML Y QUE SE HAYA DESBLOQUEADO DEL PROCESO DE CAPTURA.
}
begin
try
Result:= TFolioCaptura.Create;
with FQuery do
begin
Close;
SQL.Clear;
SQL.Add('SELECT FOLI.idfolio, FOLI.codigofolio, FOLI.secuenciafolio, FOLI.iddatoplanilla, ');
SQL.Add(' IMAG.nombreimagen, CARP.idcarpeta, CARP.codigocarpeta, CARP.clasecarpeta, ');
SQL.Add(' TARE.idtarea, CAJA.codigocaja, TISD.descripciontiposeriedocumental, ');
SQL.Add(' SUBD.descripcionsubseriedocumental, 0 as p_diasbloq, ');
SQL.Add(' SEDO.descripcionseriedocumental, ');
SQL.Add(' SUBD.descripcionsubseriedocumental, 0 as p_diasbloq, ');
SQL.Add(' cast(''00:00:00'' as TIME) as p_horabloq, ');
SQL.Add(' IMAG.servidorftp, IMAG.rutaftp, DAPL.fechanomina, DAPL.idfondo, ');
SQL.Add(' DAPL.periodocotizacion, DAPL.fechapago ');
SQL.Add(Format('FROM %s.FOLIO FOLI ',[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.IMAGEN IMAG ON IMAG.idfolio = FOLI.idfolio',[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.CONTROLFOLIO COFO ON COFO.idfolio = FOLI.idfolio',[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.CARPETAALETA CAAL ON CAAL.idcarpetaaleta = FOLI.idcarpetaaleta',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.CARPETA CARP ON CARP.idcarpeta = CAAL.idcarpeta',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.FLUJO FLUJ ON FLUJ.idflujo = CARP.idflujo',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.TAREA TARE ON TARE.idtarea = FLUJ.idtareaproxima',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.CAJA ON CAJA.idcaja = CARP.idcaja',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.SERIEDOCUMENTAL SEDO ON '
+ 'SEDO.idseriedocumental = CARP.idseriedocumental',[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.TIPOSERIEDOCUMENTAL TISD ON '
+ 'TISD.idtiposeriedocumental = SEDO.idtiposeriedocumental',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.SERIESUBSERIE SESU ON SESU.idseriesubserie = CAAL.idseriesubserie',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.SUBSERIEDOCUMENTAL SUBD ON '
+ 'SUBD.idsubseriedocumental = SESU.idseriedocumental',[DMConexion.esquema]));
SQL.Add(Format('LEFT JOIN %s.DATOPLANILLA DAPL ON DAPL.iddatoplanilla = FOLI.iddatoplanilla',
[DMConexion.esquema]));
SQL.Add(Format('LEFT JOIN %s.FONDO FOND ON FOND.idfondo = DAPL.idfondo',
[DMConexion.esquema]));
SQL.Add(' WHERE IMAG.version = (SELECT MAX(version)');
SQL.Add(Format(' FROM %s.IMAGEN ',[DMConexion.esquema]));
SQL.Add(' WHERE idfolio = FOLI.idfolio)');
SQL.Add(Format(' AND FOLI.codigofolio >= ''%s''', [p_CodiFoli]));
SQL.Add(Format(' AND CARP.codigocarpeta = ''%s''', [leftstr(p_CodiFoli,8)]));
SQL.Add(' AND NOT COFO.bloqueado AND COFO.fechadesbloqueo IS NOT NULL');
SQL.Add(' AND COFO.IDTAREA = 4 '); // VERIFICA QUE ESTE EN TAREA CAPTURA EN LA TABLABLOQUEO
SQL.Add(' AND CARP.IDFLUJO = 4'); // VERIFICA QUE LA CARPETA ESTE EN ESTADO GENERACION XML
SQL.Add(' ORDER BY FOLI.codigofolio ');
SQL.Add(' LIMIT 2');
open;
first;
if (not Eof) then
begin
Result.IdFolio := FieldByName('idfolio').value;
Result.CodigoFolio := FieldByName('codigofolio').asstring;
Result.secuenciafolio := FieldByName('secuenciafolio').value;
Result.IdDatoPlanilla := FieldByName('iddatoplanilla').asstring;
Result.NombreImagen := FieldByName('nombreimagen').AsString;
Result.IdCarpeta := FieldByName('idcarpeta').value;
Result.CodigoCarpeta := FieldByName('codigocarpeta').AsString;
Result.ClaseCarpeta := FieldByName('clasecarpeta').AsString [1];
Result.IdTarea := FieldByName('idtarea').value;
Result.CodigoCaja := FieldByName('codigocaja').AsString;
Result.DescSerieDocum := FieldByName('descripcionseriedocumental').AsString;
Result.DescTipoSerieDocum := FieldByName('descripciontiposeriedocumental').AsString;
Result.DescSubSerieDocum := FieldByName('descripcionsubseriedocumental').AsString;
Result.DiasBloqueo := FieldByName('p_diasbloq').value;
Result.HorasBloqueo := FieldByName('p_horabloq').value;
Result.ServidorFtp := FieldByName('servidorftp').AsString;
Result.RutaFtp := FieldByName('rutaftp').AsString;
Result.RutaFtp := ifThen(AnsiRightStr(Result.RutaFtp,1) = '\',
Result.RutaFtp,Result.RutaFtp + '\');
Result.FechaNomina := FieldByName('fechanomina').asstring;
Result.IdFondo := StrToInt(ifthen(FieldByName('idfondo').asstring = '',
'0', FieldByName('idfondo').asstring));
Result.PeriodoCotizacion := AnsiRightStr(FieldByName('periodocotizacion').AsString,7);
Result.FechaPagoBanco := FieldByName('fechapago').asstring;
Next;
Result.CodigoFolioSigu:= '';
if (not Eof) then
Result.CodigoFolioSigu := FieldByName('codigofolio').asstring;
Close;
SQL.Clear;
SQL.Add('SELECT OBFO.idfolio, OBFO.observacion ');
SQL.Add(Format('FROM %s.OBSERVACIONFOLIO OBFO ', [DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.TAREA TARE ON TARE.idtarea = OBFO.idtarea',
[DMConexion.esquema]));
SQL.Add(Format('WHERE OBFO.idfolio = %d',[Result.IdFolio]));
SQL.Add( ' AND OBFO.tipoobservacion = ''R''');
SQL.Add(Format(' AND TARE. descripciontarea = ''%s''',[p_DescTare]));
SQL.Add( 'ORDER BY OBFO.idfolio');
open;
first;
while not Eof do
begin
Result.NovedadesFolio.add(FieldByName('observacion').AsString);
Next;
end;
end;
end;
except
on E:exception do
raise Exception.Create(format('No es posible consultar el folio [%s].',[p_CodiFoli])
+ #10#13 + '* '+ e.Message);
end;
end;
Function TDAOCaptura.CambiarEstadoCarpeta(p_IdenCarp: int32) : Boolean;
var
DescDeci: string;
begin
Result:= False;
with FQuery do
begin
Close;
SQL.Clear;
{LA SIGUIENTE CONSULTA CUENTA CANTIDAD DE FOLIOS CAPTURABLES DE LA CARPETA, CUANTOS DE
ELLOS ESTAN DESBLOQUEADOS Y CUANTOS DE ELLOS TIENEN NOVEDAD DE CAPTURA}
SQL.Add('SELECT COUNT(FOLI.capturable) AS cantidadcapturables, ');
SQL.Add(' SUM(CASE WHEN COFO.bloqueado = FALSE THEN 1 ELSE 0 END) '
+ ' AS cantidaddesbloqueados, ');
SQL.Add(' SUM (CASE WHEN EXISTS (SELECT idobservacionfolio ');
SQL.Add(Format(' FROM %s.OBSERVACIONFOLIO OBFO ',
[DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.TAREA TARE ON '
+ '(TARE.idtarea = OBFO.idtarea) ',
[DMConexion.esquema]));
SQL.Add(' WHERE OBFO.idfolio = FOLI.idfolio ');
SQL.Add(' AND TARE.descripciontarea = ''CAPTURA'')');
SQL.Add(' THEN 1 ELSE 0 END) AS cantidadnovedades ');
SQL.Add(Format('FROM %s.CARPETAALETA CAAL', [DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.FOLIO FOLI ON (FOLI.idcarpetaaleta = CAAL.idcarpetaaleta)',
[DMConexion.esquema]));
SQL.Add(Format('LEFT JOIN %s.CONTROLFOLIO COFO ON COFO.idfolio = FOLI.idfolio',
[DMConexion.esquema]));
SQL.Add(Format('LEFT JOIN %s.TAREA TARE ON TARE.idtarea = COFO.idtarea',
[DMConexion.esquema]));
SQL.Add(Format('WHERE CAAL.idcarpeta = %d ', [p_IdenCarp]));
SQL.Add(' AND FOLI.capturable ');
SQL.Add(' AND (TARE.descripciontarea IS NULL '
+ ' OR TARE.descripciontarea= ''CAPTURA'') ');
open;
first;
if not eof then
begin
{SE VERIFICA SI LA CANTIDAD DE FOLIOS ES IGUAL A LOS DESBLOQUEADOS}
if FieldByName('cantidadcapturables').Value =
FieldByName('cantidaddesbloqueados').Value then
begin
{SI HAY MINIMO UNA NOVEDAD EL ESTADO DE LA CARPETA SE VA POR PROCESO NOVEDAD}
if FieldByName('cantidadnovedades').value = 0 then
DescDeci:= 'GUARDADO SATISFACTORIO'
else
DescDeci:= 'PROCESO NOVEDAD';
Close;
SQL.Clear;
SQL.Add('SELECT * ');
SQL.Add(Format('FROM %s.FNC_ASIGNARFLUJOCARPETA (%d,''%s'')',
[DMConexion.esquema, p_IdenCarp, DescDeci]));
open;
end;
end
else
raise Exception.Create(Format('No es posible verificar la completitud de la '
+ 'Carpeta con ID [%d].',[p_IdenCarp]));
end;
end;
function TDAOCaptura.ConsultarDatosANI(p_DescTipoIden: string; p_numedocu: string;
p_primnomb:string; p_primapel:string): TDataSource;
{ FUNCION QUE BUSCA DATOS DE PERSONAS EN LA BASE DE DATOS DE ANI
}
const
Esquema = 'andes_ani';
var
adicwher : string;
QuerDatosANI: TZQuery;
begin
try
QuerDatosANI:= TZQuery.Create(nil);
QuerDatosANI.Connection:= DMConexion.conBDANI;
Result:= TDataSource.Create(nil);
adicwher := '';
with QuerDatosANI do
begin
Close;
SQL.Clear;
SQL.Add('SELECT numerocedula AS numerodocumento, primernombre, segundonombre, ');
SQL.Add(' CAST(CASE WHEN TRIM(segundonombre) IS NULL ');
SQL.Add(' THEN TRIM(primernombre) ');
SQL.Add(' ELSE TRIM(primernombre) || '' '' || TRIM(segundonombre)');
SQL.Add(' END AS CHARACTER VARYING) AS nombres , ');
SQL.Add(' primerapellido, segundoapellido, ');
SQL.Add(' CAST(CASE WHEN TRIM(segundoapellido) IS NULL ');
SQL.Add(' THEN TRIM(primerapellido) ');
SQL.Add(' ELSE TRIM(primerapellido) || '' '' || TRIM(segundoapellido)');
SQL.Add(' END AS CHARACTER VARYING) AS apellidos, ');
SQL.Add(Format('''%s'' AS descripciontipoidentificacion ', [p_DescTipoIden]));
SQL.Add(Format('FROM %s.CEDULA ', [Esquema]));
SQL.Add(' WHERE ');
if p_numedocu <> '' then
adicwher:= Format('numerocedula LIKE ''%s''',['%' + p_numedocu + '%']);
if p_primnomb <> '' then
adicwher:= adicwher + IfThen(adicwher <> '',' and ', '')
+ Format('primernombre LIKE ''%s''',['%' + p_primnomb + '%']);
if p_primapel <> '' then
adicwher:= adicwher + IfThen(adicwher <> '',' and ', '')
+ Format('primerapellido LIKE ''%s''',['%' + p_primapel + '%']);
SQL.Add(adicwher);
SQL.Add(' ORDER BY primernombre,segundonombre NULLS FIRST, primerapellido, '
+ 'segundoapellido NULLS FIRST');
open;
first;
result.DataSet:=QuerDatosANI;
end;
except
on E:exception do
raise Exception.Create('No es posible consultar información de Base de Datos ANI.'
+ #10#13 + '* '+ e.Message);
end;
end;
function TDAOCaptura.ConsultarDatosAsociados(p_IdenFoli: int64): TDataSource;
{ FUNCION QUE BUSCA DATOS DE PERSONAS ASOCIADAS AL FOLIO
}
var
QuerDatoAsoc: TZQuery;
begin
try
QuerDatoAsoc:= TZQuery.Create(nil);
QuerDatoAsoc.Connection:= DMConexion.ZConexion;
Result:= TDataSource.Create(nil);
with QuerDatoAsoc do
begin
Close;
SQL.Clear;
SQL.Add('SELECT FOID.idfolioidentificacion, IDEN.numerodocumento, TIID.descripciontipoidentificacion,');
SQL.Add(' CAST(CASE WHEN TRIM(PERS.segundonombre) IS NULL ');
SQL.Add(' THEN TRIM(PERS.primernombre) ');
SQL.Add(' ELSE TRIM(PERS.primernombre) || '' '' || TRIM(PERS.segundonombre)');
SQL.Add(' END AS CHARACTER VARYING) AS nombres , ');
SQL.Add(' CAST(CASE WHEN TRIM(PERS.segundoapellido) IS NULL ');
SQL.Add(' THEN TRIM(PERS.primerapellido) ');
SQL.Add(' ELSE TRIM(PERS.primerapellido) || '' '' || TRIM(PERS.segundoapellido)');
SQL.Add(' END AS CHARACTER VARYING) AS apellidos ');
SQL.Add(Format('FROM %s.FOLIOIDENTIFICACION FOID ', [DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.IDENTIFICACION IDEN ON IDEN.ididentificacion = FOID.ididentificacion',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.PERSONA PERS ON PERS.idpersona = IDEN.idpersona',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.TIPOIDENTIFICACION TIID ON '
+ 'TIID.idtipoidentificacion = IDEN.idtipoidentificacion',
[DMConexion.esquema]));
SQL.Add(' WHERE ');
SQL.Add(Format(' FOID.idfolio = %d',[p_idenfoli]));
SQL.Add(' ORDER BY FOID.idfolioidentificacion');
open;
first;
result.DataSet:=QuerDatoAsoc;
end;
except
on E:exception do
raise Exception.Create('No es posible consultar información de personas asociadas al Folio.'
+ #10#13 + '* '+ e.Message);
end;
end;
function TDAOCaptura.ConsultarDatosMTI(p_identipo: Variant; p_numedocu: string;
p_primnomb:string; p_primapel:string): TDataSource;
{ FUNCION QUE BUSCA DATOS DE PERSONAS EN LA BASE DE DATOS DE MTI
}
var
adicwher : string;
QuerDatosMTI: TZQuery;
begin
try
QuerDatosMTI:= TZQuery.Create(nil);
QuerDatosMTI.Connection:= DMConexion.ZConexion;
Result:= TDataSource.Create(nil);
adicwher := '';
with QuerDatosMTI do
begin
Close;
SQL.Clear;
SQL.Add('SELECT TIID.idtipoidentificacion, TIID.descripciontipoidentificacion, ');
SQL.Add(' IDEN.ididentificacion, IDEN.numerodocumento, ');
SQL.Add(' PERS.primernombre, PERS.segundonombre, ');
SQL.Add(' CAST(CASE WHEN TRIM(PERS.segundonombre) IS NULL ');
SQL.Add(' THEN TRIM(PERS.primernombre) ');
SQL.Add(' ELSE TRIM(PERS.primernombre) || '' '' || TRIM(PERS.segundonombre)');
SQL.Add(' END AS CHARACTER VARYING) AS nombres , ');
SQL.Add(' PERS.primerapellido, PERS.segundoapellido, ');
SQL.Add(' CAST(CASE WHEN TRIM(PERS.segundoapellido) IS NULL ');
SQL.Add(' THEN TRIM(PERS.primerapellido) ');
SQL.Add(' ELSE TRIM(PERS.primerapellido) || '' '' || TRIM(PERS.segundoapellido)');
SQL.Add(' END AS CHARACTER VARYING) AS apellidos ');
SQL.Add(Format('FROM %s.IDENTIFICACION IDEN ', [DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.PERSONA PERS ON PERS.idpersona = IDEN.idpersona',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.TIPOIDENTIFICACION TIID ON '
+ 'TIID.idtipoidentificacion = IDEN.idtipoidentificacion',
[DMConexion.esquema]));
SQL.Add(' WHERE ');
// LA SIGUIENTE LINEA ES TEMPORAL PARA QUE NO TRAIGA DATOS DE PERSONAS GRABADAS CON NUMERO PATRONAL [2016-02-26]
SQL.Add(' DESCRIPCIONTIPOIDENTIFICACION <> ''NÚMERO PATRONAL'' AND ');
///////////////////////////////////////////////////////////////////////////////////////////////////
if p_identipo <> NULL then
adicwher := adicwher + Format(' IDEN.idtipoidentificacion = %s ',[p_identipo]);
if p_numedocu <> '' then
adicwher:= adicwher + IfThen(adicwher <> '',' and ', '')
+ Format('IDEN.numerodocumento LIKE ''%s''',['%' + p_numedocu + '%']);
if p_primnomb <> '' then
adicwher:= adicwher + IfThen(adicwher <> '',' and ', '')
+ Format('PERS.primernombre LIKE ''%s''',['%' + p_primnomb + '%']);
if p_primapel <> '' then
adicwher:= adicwher + IfThen(adicwher <> '',' and ', '')
+ Format('PERS.primerapellido LIKE ''%s''',['%' + p_primapel + '%']);
SQL.Add(adicwher);
SQL.Add(' ORDER BY primernombre,segundonombre NULLS FIRST, primerapellido, '
+ 'segundoapellido NULLS FIRST');
open;
first;
result.DataSet:=QuerDatosMTI;
end;
except
on E:exception do
raise Exception.Create('No es posible consultar información de Base de Datos MTI.'
+ #10#13 + '* '+ e.Message);
end;
end;
function TDAOCaptura.ConsultarFondos: TDataSource;
var
QuerFond: TZQuery;
begin
try
QuerFond:= TZQuery.Create(nil);
QuerFond.Connection:= DMConexion.ZConexion;
Result:= TDataSource.Create(nil);
with QuerFond do
begin
Close;
SQL.Clear;
SQL.Add('SELECT idfondo, descripcionfondo');
SQL.Add(Format('FROM %s.FONDO',[DMConexion.Esquema]));
SQL.Add(' ORDER BY 2');
Open;
First;
Result.DataSet := QuerFond;
end;
except
on E:exception do
raise Exception.Create('No es posible consultar los Fondos-Entidades.'
+ #10#13 + '* '+ e.Message);
end;
end;
function TDAOCaptura.ConsultarPersonasFolio(p_idenfoli: int64): TList;
// FUNCION QUE BUSCA LOS DATOS DEL FOLIO QUE SE HAYAN CAPTURADO
var
DatoCapt : TRegistroCaptura;
begin
try
Result := TList.Create;
with FQuery do
begin
Close;
SQL.Clear;
SQL.Add('SELECT FOID.idfolio, TIID.descripciontipoidentificacion, ');
SQL.Add(' FUID.descripcionfuenteidentificacion, IDEN.ididentificacion, ');
SQL.Add(' IDEN.numerodocumento, PERS.idpersona, PERS.primernombre, ');
SQL.Add(' PERS.segundonombre, PERS.primerapellido, PERS.segundoapellido ');
SQL.Add(Format('FROM %s.FOLIOIDENTIFICACION FOID ', [DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.IDENTIFICACION IDEN ON IDEN.ididentificacion = FOID.ididentificacion',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.TIPOIDENTIFICACION TIID ON '
+ 'TIID.idtipoidentificacion = IDEN.idtipoidentificacion',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.FUENTEIDENTIFICACION FUID ON '
+ 'FUID.idfuenteidentificacion = IDEN.idfuenteidentificacion',
[DMConexion.esquema]));
SQL.Add(Format('INNER JOIN %s.PERSONA PERS ON PERS.idpersona = IDEN.idpersona',
[DMConexion.esquema]));
SQL.Add(Format('WHERE FOID.idfolio = %d',[p_idenfoli]));
open;
first;
while not Eof do
begin
DatoCapt:= TRegistroCaptura.Create;
DatoCapt.IdFolio:= FieldByName('idfolio').Value;
DatoCapt.DescripcionTipoIdentificacion:= FieldByName('DescripcionTipoIdentificacion').Value;
DatoCapt.descripcionfuenteidentificacion:= FieldByName('descripcionfuenteidentificacion').Value;
DatoCapt.ididentificacion:= FieldByName('ididentificacion').Value;
DatoCapt.numerodocumento:= FieldByName('numerodocumento').Value;
DatoCapt.idpersona:= FieldByName('idpersona').Value;
DatoCapt.primernombre:= FieldByName('primernombre').AsString;
DatoCapt.segundonombre:= FieldByName('segundonombre').AsString;
DatoCapt.primerapellido:= FieldByName('primerapellido').AsString;
DatoCapt.segundoapellido:= FieldByName('segundoapellido').AsString;
Result.Add(DatoCapt);
DatoCapt.Free;
Next;
end;
end;
except
on E:exception do
raise Exception.Create('No es posible consultar datos de las personas asociadas al Folio.'
+ #10#13 + '* '+ e.Message);
end;
end;
function TDAOCaptura.ConsultarTiposIdentificacion: TDataSource;
{ FUNCION QUE BUSCA LOS TIPOS DE IDENTIFICACION
}
var
QuerDatoTipi: TZQuery;
begin
try
QuerDatoTipi:= TZQuery.Create(nil);
QuerDatoTipi.Connection:= DMConexion.ZConexion;
Result:= TDataSource.Create(nil);
with QuerDatoTipi do
begin
Close;
SQL.Clear;
SQL.Add('SELECT idtipoidentificacion, descripciontipoidentificacion');
SQL.Add(Format('FROM %s.TIPOIDENTIFICACION ', [DMConexion.esquema]));
// LA SIGUIENTE LINEA ES TEMPORAL PARA QUE NO TRAIGA TIPO DE IDENTIFICACION NUMERO PATRONAL [2016-02-26]
SQL.Add(' WHERE descripciontipoidentificacion <> ''NÚMERO PATRONAL''');
/////////////////////////////////////////////////////////////////////////////////////////////////////////
SQL.Add(' ORDER BY 2');
open;
first;
result.DataSet:=QuerDatoTipi;
end;
except
on E:exception do
raise Exception.Create('No es posible consultar los Tipos de Identificacion.'
+ #10#13 + '* '+ e.Message);
end;
end;
Function TDAOCaptura.DesbloquearFolio(p_IdenFoli: int64; p_DescTare: string) : Boolean;
begin
Result:= False;
with FQuery do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * ');
SQL.Add(Format('FROM %s.FNC_DESBLOQUEARFOLIO(%d,''%s'')',
[DMConexion.esquema, p_IdenFoli,p_DescTare]));
open;
First;
if (not eof) and (FieldByName('p_folidesb').asstring <> '') then
result := True;
end;
end;
procedure TDAOCaptura.EliminarDatosAsociacion(p_IdenFoid: int64; p_IdenFoli: Int64;
p_IdenCarp: Int64; p_IdenDapl: string);
begin
with FQuery do
begin
Close;
SQL.Clear;
SQL.Add(Format('DELETE FROM %s.FOLIOIDENTIFICACION ', [DMConexion.esquema]));
SQL.Add(Format(' WHERE idfolioidentificacion = %d ',[p_IdenFoid]));
SQL.Add(' RETURNING idfolioidentificacion ');
Open;
if not IsEmpty then
begin
Close;
SQL.Clear;
SQL.Add('SELECT count(*) AS PERSONASFOLIO');
SQL.Add(Format('FROM %s.FOLIOIDENTIFICACION FOID ', [DMConexion.esquema]));
SQL.Add(' WHERE ');
SQL.Add(Format(' FOID.idfolio = %d',[p_IdenFoli]));
open;
if FieldByName('personasfolio').Value = 0 then
begin
Close;
SQL.Clear;
SQL.Add(Format('DELETE FROM %s.CONTROLFOLIO ', [DMConexion.esquema]));
SQL.Add(Format(' WHERE idfolio = %d ',[p_IdenFoli]));
Open;
Close;
SQL.Clear;
SQL.Add(Format('DELETE FROM %s.OBSERVACIONFOLIO', [DMConexion.esquema]));
SQL.Add(Format(' WHERE idfolio = %d ',[p_IdenFoli]));
SQL.Add(' AND idtarea = 4');
Open;
if p_IdenDapl <> '' then
begin
Close;
SQL.Clear;
SQL.Add(Format('UPDATE %s.FOLIO', [DMConexion.esquema]));
SQL.Add(' SET iddatoplanilla = NULL');
SQL.Add(Format(' WHERE idfolio = %d ',[p_IdenFoli]));
Open;
Close;
SQL.Clear;
SQL.Add(Format('DELETE FROM %s.DATOPLANILLA ', [DMConexion.esquema]));
SQL.Add(Format(' WHERE iddatoplanilla = %s ',[p_IdenDapl]));
Open;
end;
{SE ELIMINAN TODAS LAS IDENTIFICACIONES ASIGNADAS EN FOLIOS NO CAPTURABLES}
Close;
SQL.Clear;
SQL.Add(Format('DELETE FROM %s.FOLIOIDENTIFICACION FOID ', [DMConexion.esquema]));
SQL.Add(' WHERE EXISTS (SELECT FOLI.idfolio ');
SQL.Add(Format(' FROM %s.FOLIO FOLI ', [DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.CARPETAALETA CAAL ON '
+ 'CAAL.idcarpetaaleta = FOLI.idcarpetaaleta',
[DMConexion.esquema]));
SQL.Add(' WHERE FOID.idfolio = FOLI.idfolio ');
SQL.Add(Format(' AND CAAL.idcarpeta = %d ',[p_IdenCarp]));
SQL.Add(' AND NOT FOLI.capturable');
SQL.Add(' )');
Open;
{SE DEVUELVE EL ESTADO DE LA CARPETA A CAPTURA}
Close;
SQL.Clear;
SQL.Add(Format('UPDATE %s.CARPETA', [DMConexion.esquema]));
SQL.Add(' SET idflujo= (SELECT idflujo ');
SQL.Add(Format(' FROM %s.FLUJO FLUJ', [DMConexion.esquema]));
SQL.Add(Format(' INNER JOIN %s.TAREA TARE ON FLUJ.idtareaproxima = TARE.idtarea',
[DMConexion.esquema]));
SQL.Add(' WHERE descripciontarea = ''CAPTURA'' ');
SQL.Add(' )');
SQL.Add(Format(' WHERE idcarpeta = %d ',[p_IdenCarp]));
Open;
end;
end
else
raise Exception.Create
(Format('Imposible eliminar la asociación de la persona solicitada. ID [%d].',
[p_IdenFoid]));
end;
end;
{LOS DOS SIGUIENTES PROCEDIMIENTOS RegistrarMarcaFolio Y EliminarBloqueoFolioNoCapturable
SON TEMPORALES PARA SUBSANAR EL HECHO DE TENER TODOS LOS FOLIOS COMO 'CAPTURABLES'.}
procedure TDAOCaptura.RegistrarMarcaFolio(p_IdenFoli: int64);
begin
with FQuery do
begin
Close;
SQL.Clear;
SQL.Add(Format('UPDATE %s.FOLIO ', [DMConexion.esquema]));
SQL.Add( ' SET capturable = FALSE');
SQL.Add(Format(' WHERE idfolio = %d ',[p_IdenFoli]));
SQL.Add(' RETURNING idfolio');
Open;
if IsEmpty then
raise Exception.Create
(Format('Imposible registrar el Folio con ID [%d] como NO-CAPTURABLE.',
[p_IdenFoli]));
end;
end;
procedure TDAOCaptura.EliminarBloqueoFolioNoCapturable(p_IdenFoli: int64);
begin
with FQuery do
begin
Close;
SQL.Clear;
SQL.Add(Format('DELETE FROM %s.CONTROLFOLIO ', [DMConexion.esquema]));
SQL.Add(Format(' WHERE idfolio = %d ',[p_IdenFoli]));
SQL.Add(' AND idtarea in (SELECT idtarea ');
SQL.Add(Format(' FROM %s.TAREA', [DMConexion.esquema]));
SQL.Add( ' WHERE descripciontarea = ''CAPTURA'')');
SQL.Add(' RETURNING idfolio');
Open;
if IsEmpty then
raise Exception.Create
(Format('Imposible eliminar el bloqueo del Folio con ID [%d].',
[p_IdenFoli]));
end;
end;
///////////////////////////////////////////////////////////////////////////////////////////////
{$REGION 'CONTROL DE TRANSACCIONES'}
procedure TDAOCaptura.CancelarTransaccion;
begin
try
with FQuery do
begin
if Connection.InTransaction then
Connection.Rollback;
Connection.TransactIsolationLevel:= TZTransactIsolationLevel.tinone;
end;
finally
end;
end;
procedure TDAOCaptura.FinalizarTransaccion;
begin
try
with FQuery do
begin
Connection.commit;
Connection.TransactIsolationLevel:= TZTransactIsolationLevel.tinone;
end;
except
on E:exception do
raise Exception.Create('No es posible finalizar el Administrador de Transacciones. '
+ #10#13 + '* ' + e.Message);
end;
end;
procedure TDAOCaptura.IniciarTransaccion;
begin
try
with FQuery do
begin
Connection.TransactIsolationLevel := TZTransactIsolationLevel.tiReadCommitted;
Connection.StartTransaction;
end;
except
on E:exception do
raise Exception.Create('No es posible inicializar Administrador de Transacciones. '
+ #10#13 + '* ' + e.Message);
end;
end;
{$ENDREGION}
{$REGION 'CONSTRUCTOR Y DESTRUCTOR'}
constructor TDAOCaptura.create;
begin
FQuery:= TZQuery.create(nil);
FQuery.Connection:= DMConexion.ZConexion;
end;
destructor TDAOCaptura.destroy;
begin
FQuery.Close;
FQuery.Connection.Disconnect;
FQuery.free;
end;
{$ENDREGION}
end.
|
unit URegister;
interface
uses UItemID, UProductCatalog, USale, UMoney, UProductDescription;
type
IRegicter = interface
function getTotalSale():IMoney;
procedure endSale();
procedure enterItem(id: integer; quantity: integer);
procedure makeNewSale();
procedure makePayment(cashTendered: IMoney);
end;
TRegicter = class(TInterfacedObject, IRegicter)
private
/// <link>aggregation</link>
catalog: IProductCatalog;
/// <link>aggregation</link>
currentSale: ISale;
public
function getTotalSale():IMoney;
procedure endSale();
procedure enterItem(id: integer; quantity: integer);
procedure makeNewSale();
procedure makePayment(cashTendered: IMoney);
constructor Create(catalog: IProductCatalog);
end;
implementation
{ Regicter }
constructor TRegicter.Create(catalog: IProductCatalog);
begin
// catalog := TProductCatalog.Create;
Self.catalog := catalog;
end;
procedure TRegicter.endSale;
begin
currentSale.becomeComplete();
end;
procedure TRegicter.enterItem(id: integer; quantity: integer);
var
desc: IProductDescription;
begin
desc := catalog.getProductDescription(id);
currentSale.makeLineItem(desc, quantity);
end;
function TRegicter.getTotalSale: IMoney;
begin
result:=currentSale.getTotal;
end;
procedure TRegicter.makeNewSale;
begin
currentSale := TSale.Create;
end;
procedure TRegicter.makePayment(cashTendered: IMoney);
begin
currentSale.makePayment(cashTendered);
end;
end.
|
(*
* Copyright (c) 2008-2009, Ciobanu Alexandru
* 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 the <organization> 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 AUTHOR ''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 AUTHOR 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.
*)
{$I ../Library/src/DeHL.Defines.inc}
unit Tests.Time;
interface
uses SysUtils, DateUtils,
Windows,
Tests.Utils,
TestFramework,
DeHL.Exceptions,
DeHL.Types,
DeHL.DateTime,
TimeSpan;
type
TTestTime = class(TTestCase)
private
procedure TestTimeValue(const TestName : String; const Time : TTime; const Hour, Minute, Second, Milli : Word);
published
procedure TestCreation();
procedure TestMaths();
procedure TestOperators();
procedure TestExceptions();
procedure TestProperties();
procedure TestSysTime();
procedure TestType();
end;
implementation
{ TTestTime }
procedure TTestTime.TestOperators;
var
xTime1, xTime2, xTime3 : TTime;
vTime : System.TDateTime;
begin
{ Implicit conversions }
xTime1 := TTime.Create(10, 00, 00, 00);
vTime := xTime1;
xTime2 := vTime;
TestTimeValue('Implicit', xTime1, xTime2.Hour, xTime2.Minute, xTime2.Second, xTime2.Millisecond);
{ Add operators }
xTime1 := xTime1 + TTimeSpan.FromMilliseconds(1500);
TestTimeValue('TTime + TTimeSpan', xTime1, 10, 00, 01, 500);
xTime1 := TTimeSpan.FromSeconds(70) + xTime1;
TestTimeValue('TTimeSpan + TTime', xTime1, 10, 01, 11, 500);
{ Subtract operators }
xTime1 := xTime1 - TTimeSpan.FromSeconds(10);
TestTimeValue('TTime - TTimeSpan', xTime1, 10, 01, 1, 500);
xTime3 := TTime.Create(00, 00, 00, 00);
xTime3 := xTime3 + (xTime1 - xTime2);
TestTimeValue('TTime - TTime', xTime3, 00, 01, 1, 500);
xTime3 := TTime.Create(00, 00, 00, 00);
xTime3 := xTime3 + (xTime2 - xTime1);
TestTimeValue('TTime - TTime', xTime3, 00, 01, 1, 500);
{ Equality }
xTime1 := TTime.Now;
xTime2 := xTime1 + TTimeSpan.FromSeconds(1);
Check(xTime1 = xTime1, '(TTime = TTime) Failed for the same value!');
Check(not (xTime1 = xTime2), 'not (TTime = TTime) Failed for the same value!');
Check(not (xTime2 = xTime1), 'not (TTime = TTime) Failed for the same value!');
Check(xTime1 <> xTime2, '(TTime <> TTime) Failed for the different values!');
Check(xTime2 <> xTime1, '(TTime <> TTime) Failed for the different values!');
Check(not (xTime2 <> xTime2), 'not (TTime <> TTime) Failed for the different values!');
{ Greater }
xTime1 := TTime.Now;
xTime2 := xTime1 + TTimeSpan.FromSeconds(1);
Check(xTime2 > xTime1, '(TTime > TTime) Failed!');
Check(not (xTime2 > xTime2), 'not (TTime > TTime) Failed!');
Check(not (xTime1 > xTime2), 'not (TTime > TTime) Failed!');
Check(xTime2 >= xTime1, '(TTime >= TTime) Failed!');
Check(xTime2 >= xTime2, '(TTime >= TTime) Failed!');
Check(not (xTime1 >= xTime2), 'not (TTime >= TTime) Failed!');
{ Less }
xTime1 := TTime.Now;
xTime2 := xTime1 + TTimeSpan.FromSeconds(1);
Check(xTime1 < xTime2, '(TTime < TTime) Failed!');
Check(not (xTime1 < xTime1), 'not (TTime < TTime) Failed!');
Check(not (xTime2 < xTime1), 'not (TTime < TTime) Failed!');
Check(xTime1 <= xTime2, '(TTime <= TTime) Failed!');
Check(xTime1 <= xTime1, '(TTime <= TTime) Failed!');
Check(not (xTime2 <= xTime1), 'not (TTime <= TTime) Failed!');
end;
procedure TTestTime.TestProperties;
var
xTime : TTime;
begin
xTime := TTime.Create(11, 00, 00, 00);
Check(not xTime.IsPM, 'Must not be PM');
xTime := xTime.AddHours(1);
Check(xTime.IsPM, 'Must be PM');
end;
procedure TTestTime.TestSysTime;
var
DT0: TTime;
DT1: TTime;
begin
DT0 := TTime.SystemNow;
Sleep(100);
DT1 := TTime.SystemNow;
Check((DT1 - DT0).TotalMilliseconds > 90, 'SystemNow expected to be consistently over 90ms');
end;
procedure TTestTime.TestCreation;
var
FromTime : TTime;
FromData : TTime;
FromNow : TTime;
FromStr : TTime;
xNow : TDateTime;
Hour, Minute, Second, Milli : Word;
begin
xNow := Now;
FromTime := TTime.Create(xNow);
FromData := TTime.Create(10, 19, 59, 5);
FromNow := TTime.Now;
FromStr := TTime.Create(TimeToStr(xNow));
DecodeTime(xNow, Hour, Minute, Second, Milli);
TestTimeValue('FromTime', FromTime, Hour, Minute, Second, Milli);
TestTimeValue('FromData', FromData, 10, 19, 59, 5);
TestTimeValue('FromNow', FromNow, FromNow.Hour, FromNow.Minute, FromNow.Second, FromNow.Millisecond);
TestTimeValue('FromStr', FromStr, Hour, Minute, Second, 0);
end;
procedure TTestTime.TestExceptions;
var
bWasEx : Boolean;
Fs : TFormatSettings;
begin
GetLocaleFormatSettings(GetUserDefaultLCID(), Fs);
{ Wrong Hour }
bWasEx := False;
try
TTime.Create(24, 1, 0, 0);
except
on EArgumentOutOfRangeException do
bWasEx := True;
on Exception do;
end;
Check(bWasEx, 'EArgumentOutOfRangeException not thrown in TTime.Create() (Wrong Hour).');
{ Wrong Minute }
bWasEx := False;
try
TTime.Create(22, 60, 0, 0);
except
on EArgumentOutOfRangeException do
bWasEx := True;
on Exception do;
end;
Check(bWasEx, 'EArgumentOutOfRangeException not thrown in TTime.Create() (Wrong Minute).');
{ Wrong Second }
bWasEx := False;
try
TTime.Create(5, 1, 60, 0);
except
on EArgumentOutOfRangeException do
bWasEx := True;
on Exception do;
end;
Check(bWasEx, 'EArgumentOutOfRangeException not thrown in TTime.Create() (Wrong Second).');
{ Wrong MSec }
bWasEx := False;
try
TTime.Create(22, 1, 0, 1000);
except
on EArgumentOutOfRangeException do
bWasEx := True;
on Exception do;
end;
Check(bWasEx, 'EArgumentOutOfRangeException not thrown in TTime.Create() (Wrong MSec).');
{ Wrong String }
bWasEx := False;
try
TTime.Create('albadalba');
except
on EArgumentFormatException do
bWasEx := True;
on Exception do;
end;
Check(bWasEx, 'EArgumentFormatException not thrown in TTime.Create() (Wrong String).');
{ Wrong String with Format }
bWasEx := False;
try
TTime.Create('albadalba', Fs);
except
on EArgumentFormatException do
bWasEx := True;
on Exception do;
end;
Check(bWasEx, 'EArgumentFormatException not thrown in TTime.Create() (Wrong String with format).');
end;
procedure TTestTime.TestMaths;
var
FromData : TTime;
begin
FromData := TTime.Create(09, 00, 00, 00);
{ Ms }
FromData := FromData.AddMilliseconds(500);
TestTimeValue('+500ms', FromData, 09, 00, 00, 500);
FromData := FromData.AddMilliseconds(1500);
TestTimeValue('+1500ms', FromData, 09, 00, 02, 000);
FromData := FromData.AddMilliseconds(-500);
TestTimeValue('-500ms', FromData, 09, 00, 01, 500);
{ Sec }
FromData := FromData.AddSeconds(10);
TestTimeValue('+10s', FromData, 09, 00, 11, 500);
FromData := FromData.AddSeconds(59);
TestTimeValue('+59s', FromData, 09, 01, 10, 500);
FromData := FromData.AddSeconds(-10);
TestTimeValue('-10s', FromData, 09, 01, 00, 500);
{ Min }
FromData := FromData.AddMinutes(5);
TestTimeValue('+5m', FromData, 09, 06, 00, 500);
FromData := FromData.AddMinutes(60);
TestTimeValue('+60m', FromData, 10, 06, 00, 500);
FromData := FromData.AddMinutes(-7);
TestTimeValue('-7m', FromData, 09, 59, 00, 500);
{ Hour }
FromData := FromData.AddHours(2);
TestTimeValue('+2h', FromData, 11, 59, 00, 500);
FromData := FromData.AddHours(22);
TestTimeValue('+22h', FromData, 9, 59, 00, 500);
FromData := FromData.AddHours(-8);
TestTimeValue('-8h', FromData, 1, 59, 00, 500);
end;
procedure TTestTime.TestTimeValue(const TestName : String; const Time: TTime; const Hour, Minute, Second,
Milli: Word);
var
xDateTime : TDateTime;
__Time, __TimeFmt : String;
Fs : TFormatSettings;
begin
try
xDateTime := EncodeTime(Hour, Minute, Second, Milli);
GetLocaleFormatSettings(GetUserDefaultLCID(), Fs);
__Time := TimeToStr(xDateTime);
__TimeFmt := TimeToStr(xDateTime, Fs);
except
Fail('(' + TestName + ') Wrong time properties passed in!');
end;
Check(Time.Hour = Hour, '(' + TestName + ') Expected Hour is wrong!');
Check(Time.Minute = Minute, '(' + TestName + ') Expected Minute is wrong!');
Check(Time.Second = Second, '(' + TestName + ') Expected Second is wrong!');
Check(Time.Millisecond = Milli, '(' + TestName + ') Expected Millisecond is wrong!');
Check(Time.ToString() = __Time, '(' + TestName + ') Expected string representation is wrong!');
Check(Time.ToString(Fs) = __TimeFmt, '(' + TestName + ') Expected formatted string representation is wrong!');
end;
procedure TTestTime.TestType;
var
Support: IType<TTime>;
TS1, TS2: TTime;
begin
Support := TType<TTime>.Default;
TS1 := TTime.Create(10, 22, 15, 100);
TS2 := TTime.Create(10, 22, 15, 101);
Check(Support.Compare(TS1, TS2) < 0, 'Compare(TS1, TS2) was expected to be less than 0');
Check(Support.Compare(TS2, TS1) > 0, 'Compare(TS2, TS1) was expected to be bigger than 0');
Check(Support.Compare(TS1, TS1) = 0, 'Compare(TS1, TS1) was expected to be 0');
Check(Support.AreEqual(TS1, TS1), 'AreEqual(TS1, TS1) was expected to be true');
Check(not Support.AreEqual(TS1, TS2), 'AreEqual(TS1, TS2) was expected to be false');
Check(Support.GenerateHashCode(TS1) <> Support.GenerateHashCode(TS2), 'GenerateHashCode(TS1)/TS2 were expected to be different');
Check(Support.Management() = tmNone, 'Type support = tmNone');
Check(Support.Name = 'TTime', 'Type Name = "TTime"');
Check(Support.Size = SizeOf(TTime), 'Type Size = SizeOf(TTime)');
Check(Support.TypeInfo = TypeInfo(TTime), 'Type information provider failed!');
Check(Support.Family = tfDate, 'Type Family = tfDate');
Check(Support.GetString(TS1) = TS1.ToString(), 'Invalid string was generated!');
end;
initialization
TestFramework.RegisterTest(TTestTime.Suite);
end.
|
unit DesUtils;
interface
uses
Winapi.Windows, Winapi.ShellApi, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes, System.RegularExpressions,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Math, StrUtils, IOUtils, IniFiles, ComObj,
IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, IdHTTP, IdSMTP, IdExplicitTLSClientServerBase, IdSMTPBase,
IdText, IdMessage, IdMessageParts, IdMessageClient, IdAttachmentFile,
Data.DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection,
Superobject, AArray;
type
TDesResult = class
public
Code,
Messg : string;
constructor create(Code, Messg : string);
function isOk : boolean;
function isErr : boolean;
end;
TDesU = class(TForm)
dbAbra: TZConnection;
qrAbra: TZQuery;
qrAbra2: TZQuery;
qrAbra3: TZQuery;
qrAbraOC: TZQuery;
qrAbraOC2: TZQuery;
dbZakos: TZConnection;
qrZakos: TZQuery;
qrZakosOC: TZQuery;
idMessage: TIdMessage;
idSMTP: TIdSMTP;
IdSSLIOHandler: TIdSSLIOHandlerSocketOpenSSL;
procedure FormCreate(Sender: TObject);
procedure desUtilsInit(createOptions : string = '');
procedure programInit(programName : string);
function zalogujZpravu(TextZpravy: string): string;
function odstranNulyZCislaUctu(cisloU : string) : string;
function prevedCisloUctuNaText(cisloU : string) : string;
function opravRadekVypisuPomociPDocument_ID(Vypis_ID, RadekVypisu_ID, PDocument_ID, PDocumentType : string) : string;
procedure opravRadekVypisuPomociVS(Vypis_ID, RadekVypisu_ID, VS : string);
function getOleObjDataDisplay(abraOleObj_Data : variant) : ansistring;
function vytvorFaZaInternetKredit(VS : string; castka : currency; datum : double) : string;
function vytvorFaZaVoipKredit(VS : string; castka : currency; datum : double) : string;
function zrusPenizeNaCeste(VS : string) : string;
function ulozKomunikaci(Typ, Customer_id, Zprava: string): string; // typ 2 je mail, typ 23 SMS
function posliPdfEmailem(FullPdfFileName, emailAddrStr, emailPredmet, emailZprava, emailOdesilatel : string; ExtraPrilohaFileName: string = '') : TDesResult;
procedure syncAbraPdfToRemoteServer(year, month : integer);
public
PROGRAM_NAME,
PROGRAM_PATH,
LOG_PATH,
LOG_FILENAME,
GPC_PATH,
PDF_PATH,
VAT_RATE,
abraDefaultCommMethod,
abraConnName,
abraUserUN,
abraUserPW,
abraWebApiUrl : string;
appMode: integer;
AbraOLE: variant;
VAT_MULTIPLIER: double;
adpIniFile: TIniFile;
//abraValues : TAArray;
function getAbraOLE() : variant;
procedure abraOLELogout();
function abraBoGet(abraBoName : string) : string;
function abraBoGetById(abraBoName, sId : string) : string;
{ ABRA zapisující funkce pomocí SuperObjectu, v praxi pro testování }
function abraBoCreate_SoWebApi(jsonSO: ISuperObject; abraBoName : string) : TDesResult;
function abraBoUpdate_SoWebApi(jsonSO: ISuperObject; abraBoName, abraBoId : string; abraBoChildName: string = ''; abraBoChildId: string = '') : string;
{ ABRA zapisující funkce pomocí SuperObjectu, používáno }
function abraBoCreate(boAA: TAArray; abraBoName : string) : string;
function abraBoCreateOLE(boAA: TAArray; abraBoName : string) : string;
function abraBoCreateWebApi_v0(boAA: TAArray; abraBoName : string) : string;
function abraBoCreateWebApi(boAA: TAArray; abraBoName : string) : TDesResult;
function abraBoCreateRowWebApi(boAA: TAArray; abraBoName, parent_id : string) : string;
function abraBoUpdate(boAA: TAArray; abraBoName, abraBoId : string; abraBoChildName: string = ''; abraBoChildId: string = '') : string;
function abraBoUpdateOLE(boAA: TAArray; abraBoName, abraBoId : string; abraBoChildName: string = ''; abraBoChildId: string = '') : string;
function abraBoUpdateWebApi(boAA: TAArray; abraBoName, abraBoId : string; abraBoChildName: string = ''; abraBoChildId: string = '') : string;
procedure logJson(boAAjson, header : string);
function getAbraPeriodId(pYear : string) : string; overload;
function getAbraPeriodId(pDate : double) : string; overload;
function getAbraDocqueueId(code, documentType : string) : string;
function getAbraDocqueueCodeById(id : string) : string;
function getAbraVatrateId(code : string) : string;
function getAbraVatindexId(code : string) : string;
//function getAbraIncometypeId(code : string) : string;
//function getAbraBusorderId(busOrderName : string) : string;
function getAbracodeByVs(vs : string) : string;
function getAbracodeByContractNumber(cnumber : string) : string;
function getFirmIdByCode(code : string) : string;
function getZustatekByAccountId (accountId : string; datum : double) : double;
function existujeVAbreDokladSPrazdnymVs() : boolean;
function isVoipKreditContract(cnumber : string) : boolean;
function isCreditContract(cnumber : string) : boolean;
function sendGodsSms(telCislo, smsText : string) : string;
function sendSms(telCislo, smsText : string) : string;
function getIniValue(iniGroup, iniItem : string) : string;
private
function newAbraIdHttp(timeout : single; isJsonPost : boolean) : TIdHTTP;
end;
function odstranDiakritiku(textDiakritika : string) : string;
function removeLeadingZeros(const Value: string): string;
function LeftPad(value:integer; length:integer=8; pad:char='0'): string; overload;
function LeftPad(value: string; length:integer=8; pad:char='0'): string; overload;
function Str6digitsToDate(datum : string) : double;
function IndexByName(DataObject: variant; Name: ShortString): integer;
function pocetRadkuTxtSouboru(SName: string): integer;
function RemoveSpaces(const s: string): string;
function KeepOnlyNumbers(const S: string): string;
function SplitStringInTwo(const InputString, Delimiter: string; out LeftPart, RightPart: string): Boolean;
function destilujTelCislo(telCislo: string): string;
function destilujMobilCislo(telCislo: string): string;
function FindInFolder(sFolder, sFile: string; bUseSubfolders: Boolean): string;
procedure writeToFile(pFileName, pContent : string);
procedure appendToFile(pFileName, pContent : string);
function LoadFileToStr(const FileName: TFileName): ansistring;
function FloatToStrFD (pFloat : extended) : string;
function RandString(const stringsize: integer): string;
function debugRozdilCasu(cas01, cas02 : double; textZpravy : string) : string;
procedure RunCMD(cmdLine: string; WindowMode: integer);
function getWindowsUserName : string;
function getWindowsCompName : string;
const
Ap = chr(39);
ApC = Ap + ',';
ApZ = Ap + ')';
var
DesU : TDesU;
implementation
{$R *.dfm}
uses AbraEntities;
{****************************************************************************}
{********************** ABRA common functions ***********************}
{****************************************************************************}
procedure TDesU.FormCreate(Sender: TObject);
begin
desUtilsInit();
end;
procedure TDesU.desUtilsInit(createOptions : string);
begin
VAT_RATE := '21'; // globání nastavení sazby DPH!
VAT_MULTIPLIER := (100 + StrToInt(VAT_RATE))/100;
PROGRAM_PATH := ExtractFilePath(ParamStr(0));
if not(FileExists(PROGRAM_PATH + 'abraDesProgramy.ini'))
AND not(FileExists(PROGRAM_PATH + '..\DE$_Common\abraDesProgramy.ini')) then
begin
Application.MessageBox(PChar('Nenalezen soubor abraDesProgramy.ini, program ukončen'),
'abraDesProgramy.ini', MB_OK + MB_ICONERROR);
Application.Terminate;
end;
if FileExists(PROGRAM_PATH + 'abraDesProgramy.ini') then
adpIniFile := TIniFile.Create(PROGRAM_PATH + 'abraDesProgramy.ini')
else
adpIniFile := TIniFile.Create(PROGRAM_PATH + '..\DE$_Common\abraDesProgramy.ini');
with adpIniFile do try
appMode := StrToInt(ReadString('Preferences', 'AppMode', '1'));
abraDefaultCommMethod := ReadString('Preferences', 'AbraDefaultCommMethod', 'OLE');
abraConnName := ReadString('Preferences', 'abraConnName', '');
abraUserUN := ReadString('Preferences', 'AbraUserUN', '');
abraUserPW := ReadString('Preferences', 'AbraUserPW', '');
abraWebApiUrl := ReadString('Preferences', 'AbraWebApiUrl', '');
GPC_PATH := IncludeTrailingPathDelimiter(ReadString('Preferences', 'GpcPath', ''));
PDF_PATH := IncludeTrailingPathDelimiter(ReadString('Preferences', 'PDFDir', ''));
dbAbra.HostName := ReadString('Preferences', 'AbraHN', '');
dbAbra.Database := ReadString('Preferences', 'AbraDB', '');
dbAbra.User := ReadString('Preferences', 'AbraUN', '');
dbAbra.Password := ReadString('Preferences', 'AbraPW', '');
dbZakos.HostName := ReadString('Preferences', 'ZakHN', '');
dbZakos.Database := ReadString('Preferences', 'ZakDB', '');
dbZakos.User := ReadString('Preferences', 'ZakUN', '');
dbZakos.Password := ReadString('Preferences', 'ZakPW', '');
idSMTP.Host := ReadString('Mail', 'SMTPServer', '');
idSMTP.HeloName := idSMTP.Host; // táta to tak má, ale HeloName by mělo být jméno klienta (volajícího), tedy tohoto programu. ale asi je úplně jedno, co tam je
idSMTP.Username := ReadString('Mail', 'SMTPLogin', '');
idSMTP.Password := ReadString('Mail', 'SMTPPW', '');
finally
adpIniFile.Free;
end;
if not dbAbra.Connected then try
dbAbra.Connect;
except on E: exception do
begin
Application.MessageBox(PChar('Nedá se připojit k databázi Abry, program ukončen.' + ^M + E.Message), 'DesU DB Abra', MB_ICONERROR + MB_OK);
Application.Terminate;
end;
end;
if (not dbZakos.Connected) AND (dbZakos.Database <> '') then try begin
dbZakos.Connect;
//qrZakos.SQL.Text := 'SET CHARACTER SET utf8'; // přesunuto do vlastností TZConnection
//qrZakos.SQL.Text := 'SET AUTOCOMMIT = 1'; // přesunuto do vlastností TZConnection
// qrZakos.ExecSQL;
end;
except on E: exception do
begin
Application.MessageBox(PChar('Nedá se připojit k databázi smluv, program ukončen.' + ^M + E.Message), 'DesU DB smluv', MB_ICONERROR + MB_OK);
Application.Terminate;
end;
end;
AbraEnt := TAbraEnt.Create;
end;
procedure TDesU.programInit(programName : string);
begin
PROGRAM_NAME := programName;
LOG_PATH := PROGRAM_PATH + 'Logy\' + PROGRAM_NAME + '\';
if not DirectoryExists(LOG_PATH) then Forcedirectories(LOG_PATH);
LOG_FILENAME := LOG_PATH + FormatDateTime('yyyy.mm".log"', Date);
end;
function TDesU.zalogujZpravu(TextZpravy: string): string;
begin
Result := FormatDateTime('dd.mm.yy hh:nn:ss ', Now) + TextZpravy;
DesUtils.appendToFile(LOG_FILENAME,
Format('(%s - %s) ', [Trim(getWindowsCompName), Trim(getWindowsUserName)]) + Result);
end;
function TDesU.getAbraOLE() : variant;
begin
Result := null;
if VarIsEmpty(AbraOLE) then try
AbraOLE := CreateOLEObject('AbraOLE.Application');
if not AbraOLE.Connect('@' + abraConnName) then begin
ShowMessage('Problém s Abrou (connect ' + abraConnName + ').');
Exit;
end;
//Zprava('Připojeno k Abře (connect DES).');
if not AbraOLE.Login(abraUserUN, abraUserPW) then begin
ShowMessage('Problém s Abrou (login ' + abraUserUN +').');
Exit;
end;
//Zprava('Přihlášeno k Abře (login Supervisor).');
except on E: exception do
begin
Application.MessageBox(PChar('Problém s Abrou.' + ^M + E.Message), 'Abra', MB_ICONERROR + MB_OK);
//Zprava('Problém s Abrou - ' + E.Message);
Exit;
end;
end;
Result := AbraOLE;
end;
procedure TDesU.abraOLELogout();
begin
if VarIsEmpty(AbraOLE) then Exit;
try
self.AbraOLE.Logout;
except
end;
self.AbraOLE := Unassigned;
end;
{*** ABRA WebApi IdHTTP functions ***}
function TDesU.newAbraIdHttp(timeout : single; isJsonPost : boolean) : TIdHTTP;
var
idHTTP: TIdHTTP;
begin
idHTTP := TidHTTP.Create;
idHTTP.Request.BasicAuthentication := True;
idHTTP.Request.Username := abraUserUN;
idHTTP.Request.Password := abraUserPW;
idHTTP.ReadTimeout := Round (timeout * 1000); // ReadTimeout je v milisekundách
if (isJsonPost) then begin
idHTTP.Request.ContentType := 'application/json; charset=UTF-8';
idHTTP.Request.AcceptCharset := 'UTF-8';
idHTTP.Request.CharSet := 'UTF-8';
idHTTP.Response.CharSet := 'UTF-8';
end;
Result := idHTTP;
end;
function TDesU.abraBoGet(abraBoName : string) : string;
begin
Result := abraBoGetById(abraBoName, '');
end;
function TDesU.abraBoGetById(abraBoName, sId : string) : string;
var
idHTTP: TIdHTTP;
endpoint : string;
begin
idHTTP := newAbraIdHttp(900, false);
endpoint := abraWebApiUrl + abraBoName;
if sId <> '' then
endpoint := endpoint + '/' + sId;
try
try
Result := idHTTP.Get(endpoint);
except
on E: Exception do
ShowMessage('Error on request: '#13#10 + e.Message);
end;
finally
idHTTP.Free;
end;
end;
function TDesU.abraBoCreate_SoWebApi(jsonSO: ISuperObject; abraBoName : string) : TDesResult;
var
idHTTP: TIdHTTP;
sstreamJson: TStringStream;
newAbraBo : string;
exceptionSO : ISuperObject;
begin
self.logJson(jsonSO.AsJSon(true), 'abraBoCreate_SoWebApi request - ' + abraWebApiUrl + abraBoName + 's');
//IdGlobal.GIdDefaultTextEncoding := encUTF8;
sstreamJson := TStringStream.Create(jsonSO.AsJSon(), TEncoding.UTF8);
idHTTP := newAbraIdHttp(900, true);
try
try begin
newAbraBo := idHTTP.Post(abraWebApiUrl + abraBoName + 's', sstreamJson);
Result := TDesResult.create('ok', newAbraBo);
self.logJson(newAbraBo, 'abraBoCreateWebApi_SO response - ' + abraWebApiUrl + abraBoName + 's');
end;
except
on E: EIdHTTPProtocolException do begin
exceptionSO := SO(E.errorMessage);
Result := TDesResult.create('err_http' + IntToStr(idHTTP.ResponseCode),
exceptionSO.S['title']
+ ': ' + exceptionSO.S['description']
);
self.logJson(E.errorMessage, 'abraBoCreateWebApi_SO response - ' + abraWebApiUrl + abraBoName + 's');
end;
on E: Exception do begin
//ShowMessage('Error on request: '#13#10 + e.Message);
end;
end;
finally
sstreamJson.Free;
idHTTP.Free;
end;
end;
function TDesU.abraBoUpdate_SoWebApi(jsonSO: ISuperObject; abraBoName, abraBoId, abraBoChildName, abraBoChildId : string) : string;
var
idHTTP: TIdHTTP;
sstreamJson: TStringStream;
endpoint : string;
begin
// http://localhost/DES/issuedinvoices/8L6U000101/rows/5A3K100101
endpoint := abraWebApiUrl + abraBoName + 's/' + abraBoId;
if abraBoChildName <> '' then
endpoint := endpoint + '/' + abraBoChildName + 's/' + abraBoChildId;
self.logJson(jsonSO.AsJSon(true), 'abraBoUpdate_SoWebApi - ' + endpoint);
//sstreamJson := TStringStream.Create(Utf8Encode(pJson)); // D2007 and earlier only
sstreamJson := TStringStream.Create(jsonSO.AsJSon(), TEncoding.UTF8);
idHTTP := newAbraIdHttp(900, true);
try
try
Result := idHTTP.Put(endpoint, sstreamJson);
except
on E: Exception do
ShowMessage('Error on request: '#13#10 + e.Message);
end;
finally
sstreamJson.Free;
idHTTP.Free;
end;
end;
{** **}
procedure TDesU.logJson(boAAjson, header : string);
begin
if appMode >= 3 then begin
if not DirectoryExists(PROGRAM_PATH + '\log\json\') then
Forcedirectories(PROGRAM_PATH + '\log\json\');
writeToFile(PROGRAM_PATH + '\log\json\' + formatdatetime('yymmdd-hhnnss', Now) + '_' + RandString(3) + '.txt', header + sLineBreak + UTF8ToString(boAAjson));
end;
end;
// ABRA BO create
function TDesU.abraBoCreate(boAA: TAArray; abraBoName : string) : string;
begin
if AnsiLowerCase(abraDefaultCommMethod) = 'webapi' then
Result := self.abraBoCreateWebApi_v0(boAA, abraBoName)
else begin
Result := self.abraBoCreateOLE(boAA, abraBoName);
self.abraOLELogout;
end;
end;
function TDesU.abraBoCreateWebApi_v0(boAA: TAArray; abraBoName : string) : string;
var
idHTTP: TIdHTTP;
sstreamJson: TStringStream;
newAbraBo : string;
begin
self.logJson(boAA.AsJSon(), 'abraBoCreateWebApi_AA_v0 - ' + abraWebApiUrl + abraBoName + 's');
sstreamJson := TStringStream.Create(boAA.AsJSon(), TEncoding.UTF8);
idHTTP := newAbraIdHttp(900, true);
try
try begin
newAbraBo := idHTTP.Post(abraWebApiUrl + abraBoName + 's', sstreamJson);
Result := SO(newAbraBo).S['id'];
end;
except
on E: Exception do begin
ShowMessage('Error on request: '#13#10 + e.Message);
end;
end;
finally
sstreamJson.Free;
idHTTP.Free;
end;
end;
function TDesU.abraBoCreateWebApi(boAA: TAArray; abraBoName : string) : TDesResult;
var
idHTTP: TIdHTTP;
sstreamJson: TStringStream;
newAbraBo : string;
exceptionSO : ISuperObject;
errMessage : string;
begin
sstreamJson := TStringStream.Create(boAA.AsJSon(), TEncoding.UTF8);
idHTTP := newAbraIdHttp(900, true);
try
try begin
newAbraBo := idHTTP.Post(abraWebApiUrl + abraBoName + 's', sstreamJson);
self.logJson(boAA.AsJSon() + sLineBreak + 'response:' + sLineBreak + newAbraBo,
'abraBoCreateWebApi - ' + abraWebApiUrl + abraBoName + 's');
Result := TDesResult.create('ok', newAbraBo);
end;
except
on E: EIdHTTPProtocolException do begin
errMessage := UTF8String(E.errorMessage);
self.logJson(boAA.AsJSon() + sLineBreak + 'error response HTTP '
+ IntToStr(idHTTP.ResponseCode) + sLineBreak + errMessage,
'abraBoCreateWebApi - ' + abraWebApiUrl + abraBoName + 's');
exceptionSO := SO(errMessage);
Result := TDesResult.create('err_http' + IntToStr(idHTTP.ResponseCode),
exceptionSO.S['title']
+ ': ' + exceptionSO.S['description']
);
end;
end;
finally
sstreamJson.Free;
idHTTP.Free;
end;
end;
function TDesU.abraBoCreateOLE(boAA: TAArray; abraBoName : string) : string;
var
i, j : integer;
BO_Object,
BO_Data,
BORow_Object,
BORow_Data,
BO_Data_Coll,
NewID : variant;
iBoRowAA : TAArray;
begin
self.logJson(boAA.AsJSon(), 'abraBoCreateOLE_AA - abraBoName=' + abraBoName);
AbraOLE := getAbraOLE();
BO_Object:= AbraOLE.CreateObject('@'+abraBoName);
BO_Data:= AbraOLE.CreateValues('@'+abraBoName);
BO_Object.PrefillValues(BO_Data);
for i := 0 to boAA.Count - 1 do
BO_Data.ValueByName(boAA.Keys[i]) := boAA.Values[i];
if boAA.RowList.Count > 0 then
begin
BORow_Object := AbraOLE.CreateObject('@'+abraBoName+'Row');
BO_Data_Coll := BO_Data.Value[IndexByName(BO_Data, 'Rows')];
for i := 0 to boAA.RowList.Count - 1 do
begin
BORow_Data := AbraOLE.CreateValues('@'+abraBoName+'Row');
BORow_Object.PrefillValues(BORow_Data);
iBoRowAA := TAArray(boAA.RowList[i]);
for j := 0 to iBoRowAA.Count - 1 do
BORow_Data.ValueByName(iBoRowAA.Keys[j]) := iBoRowAA.Values[j];
BO_Data_Coll.Add(BORow_Data);
end;
end;
try begin
NewID := BO_Object.CreateNewFromValues(BO_Data); //NewID je ID Abry
//Result := Result + 'Číslo nového BO je ' + NewID;
Result := NewID;
end;
except on E: exception do
begin
Application.MessageBox(PChar('Problem ' + ^M + E.Message), 'AbraOLE');
Result := 'Chyba při zakládání BO';
end;
end;
end;
//ABRA BO create row
function TDesU.abraBoCreateRowWebApi(boAA: TAArray; abraBoName, parent_id : string) : string;
var
idHTTP: TIdHTTP;
sstreamJson: TStringStream;
jsonRequest, newAbraBo : string;
begin
jsonRequest := '{"rows":[' + boAA.AsJSon() + ']}';
self.logJson(jsonRequest, 'abraBoCreateRowWebApi_AA - ' + abraWebApiUrl + abraBoName + 's/' + parent_id);
sstreamJson := TStringStream.Create(jsonRequest, TEncoding.UTF8);
idHTTP := newAbraIdHttp(900, true);
try
try begin
newAbraBo := idHTTP.Put(abraWebApiUrl + abraBoName + 's/' + parent_id, sstreamJson);
Result := SO(newAbraBo).S['id'];
end;
except
on E: Exception do begin
ShowMessage('Error on request: '#13#10 + e.Message);
end;
end;
finally
sstreamJson.Free;
idHTTP.Free;
end;
end;
//ABRA BO update
function TDesU.abraBoUpdate(boAA: TAArray; abraBoName, abraBoId, abraBoChildName, abraBoChildId: string) : string;
begin
if AnsiLowerCase(self.abraDefaultCommMethod) = 'webapi' then
Result := self.abraBoUpdateWebApi(boAA, abraBoName, abraBoId, abraBoChildName, abraBoChildId)
else
Result := self.abraBoUpdateOLE(boAA, abraBoName, abraBoId, abraBoChildName, abraBoChildId);
end;
function TDesU.abraBoUpdateWebApi(boAA: TAArray; abraBoName, abraBoId, abraBoChildName, abraBoChildId : string) : string;
var
idHTTP: TIdHTTP;
sstreamJson: TStringStream;
endpoint : string;
begin
// http://localhost/DES/issuedinvoices/8L6U000101/rows/5A3K100101
endpoint := abraWebApiUrl + abraBoName + 's/' + abraBoId;
if abraBoChildName <> '' then
endpoint := endpoint + '/' + abraBoChildName + 's/' + abraBoChildId;
self.logJson(boAA.AsJSon(), 'abraBoUpdateWebApi_AA - ' + endpoint);
sstreamJson := TStringStream.Create(boAA.AsJSon(), TEncoding.UTF8);
idHTTP := newAbraIdHttp(900, true);
try
Result := idHTTP.Put(endpoint, sstreamJson);
finally
sstreamJson.Free;
idHTTP.Free;
end;
end;
function TDesU.abraBoUpdateOLE(boAA: TAArray; abraBoName, abraBoId, abraBoChildName, abraBoChildId : string) : string;
var
i: integer;
BO_Object,
BO_Data,
BORow_Object,
BORow_Data,
BO_Data_Coll : variant;
begin
abraBoName := abraBoName + abraBoChildName;
if abraBoChildName <> '' then
abraBoId := abraBoChildId; //budeme pracovat s ID childa
self.logJson(boAA.AsJSon(), 'abraBoUpdateOLE_AA - abraBoName=' + abraBoName + ' abraBoId=' + abraBoId);
AbraOLE := getAbraOLE();
BO_Object := AbraOLE.CreateObject('@' + abraBoName);
BO_Data := AbraOLE.CreateValues('@' + abraBoName);
BO_Data := BO_Object.GetValues(abraBoId);
for i := 0 to boAA.Count - 1 do
BO_Data.ValueByName(boAA.Keys[i]) := boAA.Values[i];
BO_Object.UpdateValues(abraBoId, BO_Data);
end;
{*** ABRA data manipulating functions ***}
function TDesU.odstranNulyZCislaUctu(cisloU : string) : string;
begin
Result := removeLeadingZeros(cisloU);
if Result = '/0000' then Result := ''; //toto je u PayU, jako číslo účtu protistrany uvádí samé nuly - 0000000000000000/0000
end;
function TDesU.prevedCisloUctuNaText(cisloU : string) : string;
begin
Result := cisloU;
if cisloU = '2100098382/2010' then Result := 'DES Fio běžný';
if cisloU = '2602372070/2010' then Result := 'DES Fio spořící';
if cisloU = '2800098383/2010' then Result := 'DES Fiokonto';
if cisloU = '171336270/0300' then Result := 'DES ČSOB';
if cisloU = '2107333410/2700' then Result := 'PayU';
if cisloU = '160987123/0300' then Result := 'Česká pošta';
end;
procedure TDesU.opravRadekVypisuPomociVS(Vypis_ID, RadekVypisu_ID, VS : string);
var
boAA: TAArray;
sResponse: string;
begin
boAA := TAArray.Create;
boAA['VarSymbol'] := ''; //odstranit VS aby se Abra chytla při přiřazení
sResponse := self.abraBoUpdate(boAA, 'bankstatement', Vypis_ID, 'row', RadekVypisu_ID);
boAA := TAArray.Create;
boAA['VarSymbol'] := VS;
sResponse := self.abraBoUpdate(boAA, 'bankstatement', Vypis_ID, 'row', RadekVypisu_ID);
end;
function TDesU.opravRadekVypisuPomociPDocument_ID(Vypis_ID, RadekVypisu_ID, PDocument_ID, PDocumentType : string) : string;
var
boAA: TAArray;
faktura : TDoklad;
sResponse, text: string;
preplatek : currency;
begin
//pozor, funguje jen pro faktury, tedy PDocumentType "03"
dbAbra.Reconnect;
with qrAbraOC do begin
// načtu dluh na faktuře. když není kladný, končíme
SQL.Text := 'SELECT'
+ ' (ii.LOCALAMOUNT - ii.LOCALPAIDAMOUNT - ii.LOCALCREDITAMOUNT + ii.LOCALPAIDCREDITAMOUNT) as Dluh'
+ ' from ISSUEDINVOICES ii'
+ ' WHERE ii.ID = ''' + PDocument_ID + '''';
Open;
if not Eof then begin
if FieldByName('Dluh').AsCurrency <= 0 then begin
Result := 'no_unpaid_amount';
Close;
Exit;
end;
end;
Close;
end;
//spárovat fakturu Vypis_ID s řádkem výpisu RadekVypisu_ID
boAA := TAArray.Create;
boAA['PDocumentType'] := PDocumentType;
boAA['PDocument_ID'] := PDocument_ID;
sResponse := self.abraBoUpdateWebApi(boAA, 'bankstatement', Vypis_ID, 'row', RadekVypisu_ID);
Result := 'ok';
{* podívám se, jestli není po spárování přeplacená (ii.LOCALAMOUNT - ii.LOCALPAIDAMOUNT - ii.LOCALCREDITAMOUNT + ii.LOCALPAIDCREDITAMOUNT)
* bude záporné. Pokud je přeplacená,
* 1) vložíme nový řádek s přeplatkem - vyplníme Firm_ID, ale nevyplňujeme VS
* 2) amount spárovaného řádku RadekVypisu_ID ponížíme o velikost přeplatku
}
dbAbra.Reconnect;
faktura := TDoklad.create(PDocument_ID, PDocumentType);
if faktura.castkaNezaplaceno < 0 then //faktura je přeplacená
begin
preplatek := - faktura.castkaNezaplaceno;
with qrAbraOC do begin
// načtu částku z řádky výpisu
SQL.Text := 'SELECT amount, text,'
+ ' bankaccount, specsymbol, docdate$date, accdate$date, firm_id'
+ ' FROM BANKSTATEMENTS2 WHERE id = ''' + RadekVypisu_ID + '''';
Open;
if Eof then begin
Exit;
end;
//řádku z výpisu upravím -> snížím částku o přeplatek
boAA := TAArray.Create;
boAA['Amount'] := FieldByName('amount').AsCurrency - preplatek;
text := FieldByName('text').AsString;
boAA['Text'] := trim (copy(text, LastDelimiter('|', text) + 1, length(text)) ); //zkopíruju obsah za posledním svislítkem
sResponse := self.abraBoUpdateWebApi(boAA, 'bankstatement', Vypis_ID, 'row', RadekVypisu_ID);
//vyrobím nový řádek výpisu s částkou přeplatku
boAA := TAArray.Create;
boAA['amount'] := preplatek;
boAA['text'] := FieldByName('text').AsString;
boAA['bankaccount'] := FieldByName('bankaccount').AsString;
boAA['specsymbol'] := FieldByName('specsymbol').AsString;
boAA['docdate$date'] := FieldByName('docdate$date').AsFloat;
boAA['accdate$date'] := FieldByName('accdate$date').AsFloat;
boAA['firm_id'] := FieldByName('firm_id').AsString;
boAA['credit'] := true;
boAA['division_id'] := AbraEnt.getDivisionId;
boAA['currency_id'] := AbraEnt.getCurrencyId;
sResponse := self.abraBoCreateRowWebApi(boAA, 'bankstatement', Vypis_ID);
Close;
end;
Result := 'new_bsline_added';
end;
end;
function TDesU.getOleObjDataDisplay(abraOleObj_Data : variant) : ansistring;
var
j : integer;
begin
Result := '';
for j := 0 to abraOleObj_Data.Count - 1 do begin
Result := Result + inttostr(j) + 'r ' + abraOleObj_Data.Names[j] + ': ' + vartostr(abraOleObj_Data.Value[j]) + sLineBreak;
end;
end;
function TDesU.vytvorFaZaInternetKredit(VS : string; castka : currency; datum : double) : string;
var
i: integer;
boAA, boRowAA: TAArray;
newId, firmAbraCode: String;
begin
firmAbraCode := self.getAbracodeByContractNumber(VS);
if firmAbraCode = '' then begin
Result := '';
Exit;
end;
boAA := TAArray.Create;
boAA['DocQueue_ID'] := AbraEnt.getDocQueue('Code=FO4').ID;
boAA['Period_ID'] := self.getAbraPeriodId(datum);
boAA['VatDate$DATE'] := datum;
boAA['DocDate$DATE'] := datum;
boAA['Firm_ID'] := self.getFirmIdByCode(firmAbraCode);
boAA['Description'] := 'Kredit Internet';
boAA['Varsymbol'] := VS;
boAA['PricesWithVat'] := true;
// 1. řádek
boRowAA := boAA.addRow();
boRowAA['Rowtype'] := 0;
boRowAA['Text'] := ' ';
boRowAA['Division_ID'] := AbraEnt.getDivisionId;
//2. řádek
boRowAA := boAA.addRow();
boRowAA['Rowtype'] := 1;
boRowAA['Totalprice'] := castka;
boRowAA['Text'] := 'Kredit Internet';
boRowAA['Vatrate_ID'] := AbraEnt.getVatIndex('Code=Výst21').VATRate_ID;
boRowAA['VatIndex_ID'] := AbraEnt.getVatIndex('Code=Výst21').ID;
boRowAA['Incometype_ID'] := AbraEnt.getIncomeType('Code=SL').ID; // služby
//boRowAA['BusOrder_Id'] := self.getAbraBusorderId('kredit Internet'); //taková zakázka (BusOrder) není
boRowAA['Division_ID'] := AbraEnt.getDivisionId;
//writeToFile(ExtractFilePath(ParamStr(0)) + '!json' + formatdatetime('hhnnss', Now) + '.txt', jsonBo.AsJSon(true));
try begin
newId := DesU.abraBoCreate(boAA, 'issuedinvoice');
Result := newId;
end;
except on E: exception do
begin
Application.MessageBox(PChar('Problem ' + ^M + E.Message), 'Vytvoření fa');
Result := 'Chyba při vytváření faktury';
end;
end;
{ 24.3.2023 bylo zakomentováno, tabulka DE$_EuroFree se nepoužívá od cca 02-2023
// 26.10.2019 datum vytvoření faktury se uloží do tabulky DE$_EuroFree v databázi Abry
with qrAbra do begin
SQL.Text := 'UPDATE DE$_EuroFree SET'
+ ' AccDate = ''' + FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz', Date) + ''''
+ ' WHERE Firm_Id = ''' + self.getFirmIdByCode(firmAbraCode) + ''''
+ ' AND AccDate IS NULL'
+ ' AND PayUDate = (SELECT MAX(PayUDate) FROM DE$_EuroFree'
+ ' WHERE Firm_Id = ''' + self.getFirmIdByCode(firmAbraCode) + ''''
+ ' AND AccDate IS NULL)';
ExecSQL;
end;
}
end;
function TDesU.vytvorFaZaVoipKredit(VS : string; castka : currency; datum : double) : string;
var
boAA, boRowAA: TAArray;
newId, firmAbraCode: string;
begin
firmAbraCode := self.getAbracodeByContractNumber(VS);
if firmAbraCode = '' then begin
Result := '';
Exit;
end;
boAA := TAArray.Create;
boAA['DocQueue_ID'] := AbraEnt.getDocQueue('Code=FO2').ID;
boAA['Period_ID'] := self.getAbraPeriodId(datum);
boAA['VatDate$DATE'] := datum;
boAA['DocDate$DATE'] := datum;
boAA['Firm_ID'] := self.getFirmIdByCode(firmAbraCode);
boAA['Description'] := 'Kredit VoIP';
boAA['Varsymbol'] := VS;
boAA['PricesWithVat'] := true;
// 1. řádek
boRowAA := boAA.addRow();
boRowAA['Rowtype'] := 0;
boRowAA['Text'] := ' ';
boRowAA['Division_Id'] := AbraEnt.getDivisionId;;
//2. řádek
boRowAA := boAA.addRow();
boRowAA['Rowtype'] := 1;
boRowAA['Totalprice'] := castka;
boRowAA['Text'] := 'Kredit VoIP';
boRowAA['Vatrate_ID'] := AbraEnt.getVatIndex('Code=Výst21').VATRate_ID;
boRowAA['VatIndex_ID'] := AbraEnt.getVatIndex('Code=Výst21').ID;
boRowAA['Incometype_Id'] := AbraEnt.getIncomeType('Code=SL').ID; // služby
boRowAA['BusOrder_Id'] := AbraEnt.getBusOrder('Name=kredit VoIP').ID; // self.getAbraBusorderId('kredit VoIP'); // '6400000101' je 'kredit VoIP' v DB
boRowAA['Division_Id'] := AbraEnt.getDivisionId;
//writeToFile(ExtractFilePath(ParamStr(0)) + '!json' + formatdatetime('hhnnss', Now) + '.txt', jsonBo.AsJSon(true));
try begin
newId := DesU.abraBoCreate(boAA, 'issuedinvoice');
Result := newId;
end;
except on E: exception do
begin
Application.MessageBox(PChar('Problem ' + ^M + E.Message), 'Vytvoření fa');
Result := 'Chyba při vytváření faktury';
end;
end;
end;
function TDesU.getAbraPeriodId(pYear : string) : string;
begin
Result := AbraEnt.getPeriod('Code=' + pYear).ID
end;
function TDesU.getAbraPeriodId(pDate : double) : string;
var
abraPeriod : TAbraPeriod;
begin
abraPeriod := TAbraPeriod.create(pDate);
Result := abraPeriod.ID;
end;
function TDesU.getAbraDocqueueId(code, documentType : string) : string;
begin
with DesU.qrAbraOC do begin
SQL.Text := 'SELECT Id FROM DocQueues'
+ ' WHERE Hidden = ''N'' AND Code = ''' + code + ''' AND DocumentType = ''' + documentType + '''';
Open;
if not Eof then begin
Result := FieldByName('Id').AsString;
end;
Close;
end;
end;
function TDesU.getAbraDocqueueCodeById(id : string) : string;
begin
with DesU.qrAbraOC do begin
SQL.Text := 'SELECT Code FROM DocQueues'
+ ' WHERE Hidden = ''N'' AND Id = ''' + id + '''';
Open;
if not Eof then begin
Result := FieldByName('Code').AsString;
end;
Close;
end;
end;
{ takhle bylo napřímo
function TDesU.getAbraVatrateId(code : string) : string;
begin
with DesU.qrAbraOC do begin
SQL.Text := 'SELECT VatRate_Id FROM VatIndexes'
+ ' WHERE Hidden = ''N'' AND Code = ''' + code + '''';
Open;
if not Eof then begin
Result := FieldByName('VatRate_Id').AsString;
end;
Close;
end;
end;
}
function TDesU.getAbraVatrateId(code : string) : string;
var
abraVatIndex : TAbraVatIndex;
begin
abraVatIndex := TAbraVatIndex.create(code);
Result := abraVatIndex.VATRate_Id;
end;
{ takhle bylo napřímo
function TDesU.getAbraVatindexId(code : string) : string;
begin
with DesU.qrAbraOC do begin
SQL.Text := 'SELECT Id FROM VatIndexes'
+ ' WHERE Hidden = ''N'' AND Code = ''' + code + '''';
Open;
if not Eof then begin
Result := FieldByName('Id').AsString;
end;
Close;
end;
end;
}
function TDesU.getAbraVatindexId(code : string) : string;
var
abraVatIndex : TAbraVatIndex;
begin
abraVatIndex := TAbraVatIndex.create(code);
Result := abraVatIndex.id;
end;
{
function TDesU.getAbraIncometypeId(code : string) : string;
begin
with DesU.qrAbraOC do begin
SQL.Text := 'SELECT Id FROM IncomeTypes'
+ ' WHERE Code = ''' + code + '''';
Open;
if not Eof then begin
Result := FieldByName('Id').AsString;
end;
Close;
end;
end;
function TDesU.getAbraBusorderId(busOrderName : string) : string;
begin
with DesU.qrAbraOC do begin
SQL.Text := 'SELECT Id FROM BusOrders'
+ ' WHERE Name = ''' + busOrderName + '''';
Open;
if not Eof then begin
Result := FieldByName('Id').AsString;
end;
Close;
end;
end;
}
function TDesU.getAbracodeByVs(vs : string) : string;
begin
with DesU.qrZakosOC do begin
SQL.Text := 'SELECT abra_code FROM customers'
+ ' WHERE variable_symbol = ''' + vs + '''';
Open;
if not Eof then begin
Result := FieldByName('abra_code').AsString;
end;
Close;
end;
end;
function TDesU.getAbracodeByContractNumber(cnumber : string) : string;
begin
with DesU.qrZakosOC do begin
SQL.Text := 'SELECT cu.abra_code FROM customers cu, contracts co '
+ ' WHERE co.number = ''' + cnumber + ''''
+ ' AND cu.id = co.customer_id';
Open;
if not Eof then begin
Result := FieldByName('abra_code').AsString;
end;
Close;
end;
end;
function TDesU.getFirmIdByCode(code : string) : string;
begin
with DesU.qrAbraOC do begin
SQL.Text := 'SELECT Id FROM Firms'
+ ' WHERE Code = ''' + code + '''';
Open;
if not Eof then begin
Result := FieldByName('Id').AsString;
end;
Close;
end;
end;
function TDesU.getZustatekByAccountId (accountId : string; datum : double) : double;
var
sqlstring : string;
//currentAbraPeriod,
previousAbraPeriod, currentAbraPeriod : TAbraPeriod;
pocatecniZustatek, aktualniZustatek: double;
begin
with DesU.qrAbraOC do begin
currentAbraPeriod := TAbraPeriod.create(datum);
SQL.Text := 'SELECT DEBITBEGINNING as pocatecniZustatek,'
+ '(DEBITBEGINNING - CREDITBEGINNING + DEBITBEGINNIGTURNOVER - CREDITBEGINNIGTURNOVER + DEBITTURNOVER - CREDITTURNOVER) as aktualniZustatek'
+ ' FROM ACCOUNTCALCULUS'
+ ' (''%'',''' + accountId + ''',null,null,'
+ FloatToStrFD(currentAbraPeriod.dateFrom) + ',' + FloatToStrFD(datum) + ','
+ ' '''',''0'','''',''0'','''',''0'','''',''0'',null,null,null,0)';
Open;
if not Eof then begin
pocatecniZustatek := FieldByName('pocatecniZustatek').AsCurrency;
aktualniZustatek := FieldByName('aktualniZustatek').AsCurrency;
end;
Close;
if pocatecniZustatek = 0 then begin
// Pokud je pocatecniZustatek nulový, znamená to nesprávnou hodnotu kvůli neuzavřenému předchozímu roku. Proto vypočítáme konečný zůstatek předchozího roku a ten přičteme k aktuálnímu zůstatku.
previousAbraPeriod := TAbraPeriod.create(datum - 365);
SQL.Text := 'SELECT '
+ '(DEBITBEGINNING - CREDITBEGINNING + DEBITBEGINNIGTURNOVER - CREDITBEGINNIGTURNOVER + DEBITTURNOVER - CREDITTURNOVER) as konecnyZustatekPredchozihoRoku'
+ ' FROM ACCOUNTCALCULUS'
+ ' (''%'',''' + accountId + ''',null,null,'
+ FloatToStrFD(previousAbraPeriod.dateFrom) + ',' + FloatToStrFD(previousAbraPeriod.dateTo) + ','
+ ' '''',''0'','''',''0'','''',''0'','''',''0'',null,null,null,0)';
Open;
Result := aktualniZustatek + FieldByName('konecnyZustatekPredchozihoRoku').AsCurrency;
Close;
end else begin
Result := aktualniZustatek;
end;
end;
end;
function TDesU.existujeVAbreDokladSPrazdnymVs() : boolean;
var
messagestr: string;
begin
Result := false;
messagestr := '';
dbAbra.Reconnect;
//nutné rozdělit do dvou částí: přetypování (CAST) padá, pokud existuje VS jako prázný řetězec
with DesU.qrAbraOC do begin
// existuje fa s prázným VS?
// SQL.Text := 'SELECT Id, DE$_CISLO_DOKLADU(DOCQUEUE_ID, ORDNUMBER, PERIOD_ID) as DOKLAD ' //takhle je to pomocí stored function, ale ABRA neumí stored function zálohovat
SQL.Text := 'SELECT Id, (SELECT DOKLAD FROM DE$_CISLO_DOKLADU(DOCQUEUE_ID, ORDNUMBER, PERIOD_ID) as DOKLAD) '
+ ' FROM IssuedInvoices WHERE VarSymbol = ''''';
Open;
if not Eof then begin
Result := true;
ShowMessage('POZOR! V Abře existuje faktura ' + FieldByName('DOKLAD').AsString + ' s prázným VS. Je potřeba ji opravit před pokračováním práce s programem.');
Close;
Exit;
end;
Close;
// existuje zálohový list s prázným VS?
SQL.Text := 'SELECT Id, (SELECT DOKLAD FROM DE$_CISLO_DOKLADU(DOCQUEUE_ID, ORDNUMBER, PERIOD_ID) as DOKLAD) '
+ ' FROM IssuedDInvoices WHERE VarSymbol = ''''';
Open;
if not Eof then begin
Result := true;
ShowMessage('POZOR! V Abře existuje zál. list ' + FieldByName('DOKLAD').AsString + ' s prázným VS. Je potřeba ho opravit před pokračováním práce s programem.');
Close;
Exit;
end;
Close;
// existuje fa s VS, který obahuje pouze nuly?
SQL.Text := 'SELECT ID, VARSYMBOL, DOKLAD'
+ ' FROM (SELECT ID, VARSYMBOL, CAST(VARSYMBOL AS INTEGER) as VS_INT, (SELECT DOKLAD FROM DE$_CISLO_DOKLADU(DOCQUEUE_ID, ORDNUMBER, PERIOD_ID) as DOKLAD)'
+ ' FROM IssuedInvoices where VARSYMBOL < ''1'')'
+ ' WHERE VS_INT = 0';
Open;
while not Eof do begin
Result := true;
messagestr := messagestr + 'POZOR! V Abře existuje faktura ' + FieldByName('DOKLAD').AsString + ' s VS "' + FieldByName('VARSYMBOL').AsString + '"' + sLineBreak;
Next;
end;
// existuje zálohový list s VS, který obahuje pouze nuly?
SQL.Text := 'SELECT ID, VARSYMBOL, DOKLAD'
+ ' FROM (SELECT ID, VARSYMBOL, CAST(VARSYMBOL AS INTEGER) as VS_INT, (SELECT DOKLAD FROM DE$_CISLO_DOKLADU(DOCQUEUE_ID, ORDNUMBER, PERIOD_ID) as DOKLAD)'
+ ' FROM IssuedDInvoices where VARSYMBOL < ''1'')'
+ ' WHERE VS_INT = 0';
Open;
while not Eof do begin
Result := true;
messagestr := messagestr + 'POZOR! V Abře existuje zál. list ' + FieldByName('DOKLAD').AsString + ' s VS "' + FieldByName('VARSYMBOL').AsString + '"' + sLineBreak;
Next;
end;
if messagestr <> '' then ShowMessage(messagestr);
Close;
end;
end;
function TDesU.getIniValue(iniGroup, iniItem : string) : string;
begin
if FileExists(PROGRAM_PATH + 'abraDesProgramy.ini') then
adpIniFile := TIniFile.Create(PROGRAM_PATH + 'abraDesProgramy.ini')
else
adpIniFile := TIniFile.Create(PROGRAM_PATH + '..\DE$_Common\abraDesProgramy.ini');
try
Result := adpIniFile.ReadString(iniGroup, iniItem, '');
finally
adpIniFile.Free;
end;
end;
{ *** DB Zakos (Aplikace) manipulating functions *** }
function TDesU.isVoipKreditContract(cnumber : string) : boolean;
begin
with DesU.qrZakosOC do begin
SQL.Text := 'SELECT co.id FROM contracts co '
+ ' WHERE co.number = ''' + cnumber + ''''
// + ' AND co.credit = 1' kredit
+ ' AND co.tariff_id = 2'; //je to kreditni Voip
Open;
if not Eof then
Result := true
else
Result := false;
Close;
end;
end;
function TDesU.isCreditContract(cnumber : string) : boolean;
begin
with DesU.qrZakosOC do begin
SQL.Text := 'SELECT co.id FROM contracts co '
+ ' WHERE co.number = ''' + cnumber + ''''
+ ' AND co.credit = 1';
Open;
if not Eof then
Result := true
else
Result := false;
Close;
end;
end;
function TDesU.zrusPenizeNaCeste(VS : string) : string;
var
i: integer;
boAA, boRowAA: TAArray;
newId, firmAbraCode: String;
begin
with DesU.qrZakosOC do begin
SQL.Text := 'UPDATE customers SET pay_u_payment = 0 where variable_symbol = ''' + VS + '''';
ExecSQL;
Close;
end;
end;
function TDesU.ulozKomunikaci(Typ, Customer_id, Zprava: string): string; // typ 2 je mail, typ 23 SMS
// ukládá záznam o odeslané zprávě zákazníkovi do tabulky "communications" v databázi aplikace
var
CommId: integer;
SQLStr: string;
begin
Result := '';
with DesU.qrZakosOC do try
Close;
SQL.Text := 'SELECT MAX(Id) FROM communications';
Open;
CommId := Fields[0].AsInteger + 1;
Close;
SQLStr := 'INSERT INTO communications ('
+ ' Id,'
+ ' Customer_id,'
+ ' User_id,'
+ ' Communication_type_id,'
+ ' Content,'
+ ' Created_at,'
+ ' Updated_at) VALUES ('
+ IntToStr(CommId) + ', '
+ Customer_id + ', '
+ '1, ' // admin
+ Typ + ','
+ Ap + Zprava + ApC
+ Ap + FormatDateTime('yyyy-mm-dd hh:nn:ss', Now) + ApC
+ Ap + FormatDateTime('yyyy-mm-dd hh:nn:ss', Now) + ApZ;
SQL.Text := SQLStr;
ExecSQL;
except on E: exception do
Result := E.Message;
end;
end;
function TDesU.posliPdfEmailem(FullPdfFileName, emailAddrStr, emailPredmet, emailZprava, emailOdesilatel : string; ExtraPrilohaFileName: string = '') : TDesResult;
begin
if not FileExists(FullPdfFileName) then begin
Result := TDesResult.create('err', Format('Soubor %s neexistuje. Přeskočeno.', [FullPdfFileName]));
Exit;
end;
// alespoň nějaká kontrola mailové adresy
if Pos('@', emailAddrStr) = 0 then begin
Result := TDesResult.create('err', Format('Neplatná mailová adresa "%s". Přeskočeno.', [emailAddrStr]));
Exit;
end;
emailAddrStr := StringReplace(emailAddrStr, ',', ';', [rfReplaceAll]); // čárky za středníky
with idMessage do begin
Clear;
From.Address := emailOdesilatel;
// ReceiptRecipient.Text := emailOdesilatel;
// více mailových adres oddělených středníky se rozdělí
while Pos(';', emailAddrStr) > 0 do begin
Recipients.Add.Address := Trim(Copy(emailAddrStr, 1, Pos(';', emailAddrStr)-1));
emailAddrStr := Copy(emailAddrStr, Pos(';', emailAddrStr)+1, Length(emailAddrStr));
end;
Recipients.Add.Address := Trim(emailAddrStr);
Subject := emailPredmet;
ContentType := 'multipart/mixed';
with TIdText.Create(idMessage.MessageParts, nil) do begin
Body.Text := emailZprava;
ContentType := 'text/plain';
Charset := 'utf-8';
end;
with TIdAttachmentFile.Create(IdMessage.MessageParts, FullPdfFileName) do begin
ContentType := 'application/pdf';
FileName := ExtractFileName(FullPdfFileName);
end;
// přidá se extra příloha, je-li vybrána
if ExtraPrilohaFileName <> '' then
with TIdAttachmentFile.Create(IdMessage.MessageParts, ExtraPrilohaFileName) do begin
ContentType := 'application/pdf'; //případná extra příloha má být dle zadání vždy jen pdf
FileName := ExtraPrilohaFileName;
end;
try
if not idSMTP.Connected then idSMTP.Connect;
idSMTP.Send(idMessage); // ! samotné poslání mailu
Result := TDesResult.create('ok', Format('Soubor %s byl odeslán na adresu %s.', [FullPdfFileName, emailAddrStr]));
except on E: exception do
Result := TDesResult.create('err', Format('Soubor %s se nepodařilo odeslat na adresu %s.' + #13#10 + 'Chyba: %s',
[FullPdfFileName, emailAddrStr, E.Message]));
end;
end;
end;
procedure TDesU.syncAbraPdfToRemoteServer(year, month : integer);
// odeslání faktur převedených do PDF na vzdálený server
begin
RunCMD (Format('WinSCP.com /command "option batch abort" "option confirm off" "open AbraPDF" "synchronize remote '
+ '%s%4d\%2.2d /home/abrapdf/%4d" "exit"', [DesU.PDF_PATH, year, month, year]), SW_SHOWNORMAL);
end;
{******************** GODS ************}
function TDesU.sendGodsSms(telCislo, smsText : string) : string;
var
idHTTP: TIdHTTP;
sstreamJson: TStringStream;
callJson, postCallResult, godsSmsUrl: string;
begin
Result := '';
if (godsSmsUrl = '') then Result := 'chybi SMS url';
if (telCislo = '') then Result := 'chybi tel. cislo';
if (smsText = '') then Result := 'chybi SMS text';
idHTTP := TidHTTP.Create;
godsSmsUrl := getIniValue('Preferences', 'GodsSmsUrl');
idHTTP.Request.BasicAuthentication := True;
idHTTP.Request.Username := getIniValue('Preferences', 'GodsSmsUN');
idHTTP.Request.Password := getIniValue('Preferences', 'GodsSmsPW');
idHTTP.ReadTimeout := Round (10 * 1000); // ReadTimeout je v milisekundách
idHTTP.Request.ContentType := 'application/json';
idHTTP.Request.CharSet := 'utf-8';
callJson := '{"from":"Eurosignal", "msisdn":"420' + telCislo + '",'
+ '"message":"' + smsText + '"}';
sstreamJson := TStringStream.Create(callJson, TEncoding.UTF8);
try
try
if (godsSmsUrl <> '') AND (telCislo <> '') AND (smsText <> '') then
begin
Result := idHTTP.Post(godsSmsUrl, sstreamJson);
// takhle vypadá vzorový response z GODS SMS brány
// {
// "status": "success",
// "data": {"message-id": "c3d8ebd4-879e-412e-8e16-3d4a2335d967" }
// }
// }
end;
except
on E: Exception do begin
ShowMessage('Error on request: '#13#10 + e.Message);
end;
end;
finally
sstreamJson.Free;
idHTTP.Free;
end;
if appMode >= 1 then begin
if not DirectoryExists(PROGRAM_PATH + '\logy\') then
Forcedirectories(PROGRAM_PATH + '\logy\');
appendToFile(PROGRAM_PATH + '\logy\SMS_odeslane.txt', formatdatetime('dd.mm.yyyy hh:nn:ss', Now) + ' - ' + telCislo + ' - ' + smsText + ' - ' + Result);
end;
end;
{******************** SMSbrána ************}
function TDesU.sendSms(telCislo, smsText: string): string;
var
idHTTP: TIdHTTP;
SmsUrl,
SmsUN,
SmsPW,
sXMLResult,
sHTTPtext: string;
iErrOd,
iErrDo,
iResult: integer;
begin
Result := '';
idHTTP := TidHTTP.Create;
idHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create;
SmsUrl := getIniValue('Preferences', 'SmsUrl');
SmsUN := getIniValue('Preferences', 'SmsUN');
SmsPW := getIniValue('Preferences', 'SmsPW');
// idHTTP.Request.BasicAuthentication := True;
// idHTTP.Request.Username := SmsUN;
// idHTTP.Request.Password := SmsPW;
idHTTP.ReadTimeout := Round (10 * 1000); // ReadTimeout je v milisekundách
idHTTP.Request.ContentType := 'text/plain';
idHTTP.Request.CharSet := 'ASCII';
sHTTPtext := SmsUrl + '?login=' + SmsUN + #38 + 'password=' + SmsPW + '&action=send_sms&delivery_report=0&number=' + telCislo + '&message=' + odstranDiakritiku(smsText);
try
try
if (SmsUrl <> '') AND (telCislo <> '') AND (smsText <> '') then sXMLResult := idHTTP.Get(sHTTPtext);
except
on E: Exception do begin
ShowMessage('Error on request: '#13#10 + E.Message);
Exit;
end;
end;
// vrácené XML má mezi <err> a </err> číslo (-1 až 12), 0 je OK
iErrOd := Pos('<err>', sXMLResult) + 5;
iErrDo := Pos('</err>', sXMLResult);
iResult := StrToInt(Copy(sXMLResult, iErrOd, iErrDo-iErrOd));
case iResult of
0: Result := 'OK';
2: Result := 'Bad username';
3: Result := 'Bad password';
9: Result := 'Low credit';
10: Result := 'Bad phone number';
11: Result := 'No message';
12: Result := 'Too long message ';
else
Result := 'Error number ' + IntToStr(iResult);
end;
finally
idHTTP.Free;
idHTTP.IOHandler.Free;
end;
end;
{***************************************************************************}
{******************** General helper functions *********************}
{***************************************************************************}
{** class TDesResult **}
constructor TDesResult.create(Code, Messg : string);
begin
self.Code := Code;
self.Messg := Messg;
end;
function TDesResult.isOk : boolean;
begin
Result := LowerCase(LeftStr(self.Code, 2)) = 'ok';
end;
function TDesResult.isErr : boolean;
begin
Result := LowerCase(LeftStr(self.Code, 3)) = 'err';
end;
{** other functions **}
// předaný string vrátí bez háčku a čárek
function odstranDiakritiku(textDiakritika : string) : string;
var
s: string;
b: TBytes;
begin
s := textDiakritika;
b := TEncoding.Unicode.GetBytes(s);
b := TEncoding.Convert(TEncoding.Unicode, TEncoding.ASCII, b);
Result := TEncoding.ASCII.GetString(b);
end;
// odstraní ze stringu nuly na začátku
function removeLeadingZeros(const Value: string): string;
// ostraní nuly z řetězce zleva. pokud je řetězec složený pouze z nul, vrátí prázdný řetězec.
var
i: Integer;
begin
for i := 1 to Length(Value) do
if Value[i]<>'0' then
begin
Result := Copy(Value, i, MaxInt);
exit;
end;
Result := '';
end;
//zaplní řetězec nulama zleva až do celkové délky lenght
function LeftPad(value:integer; length:integer=8; pad:char='0'): string; overload;
begin
result := RightStr(StringOfChar(pad,length) + IntToStr(value), length );
end;
function LeftPad(value: string; length:integer=8; pad:char='0'): string; overload;
begin
result := RightStr(StringOfChar(pad,length) + value, length );
end;
function Str6digitsToDate(datum : string) : double;
begin
Result := StrToDate(copy(datum, 1, 2) + '.' + copy(datum, 3, 2) + '.20' + copy(datum, 5, 2));
end;
function IndexByName(DataObject: variant; Name: ShortString): integer;
// náhrada za nefunkční DataObject.ValuByName(Name)
var
i: integer;
begin
Result := -1;
i := 0;
while i < DataObject.Count do begin
if DataObject.Names[i] = Name then begin
Result := i;
Break;
end;
Inc(i);
end;
end;
function pocetRadkuTxtSouboru(SName: string): integer;
var
oSL : TStringlist;
begin
oSL := TStringlist.Create;
oSL.LoadFromFile(SName);
Result := oSL.Count;
oSL.Free;
end;
function RemoveSpaces(const s: string): string;
var
len, p: integer;
pc: PChar;
const
WhiteSpace = [#0, #9, #10, #13, #32, #160];
begin
len := Length(s);
SetLength(Result, len);
pc := @s[1];
p := 0;
while len > 0 do begin
if not (pc^ in WhiteSpace) then begin
inc(p);
Result[p] := pc^;
end;
inc(pc);
dec(len);
end;
SetLength(Result, p);
end;
function KeepOnlyNumbers(const S: string): string;
var
i: Integer;
begin
Result := '';
for i := 1 to Length(S) do
if CharInSet(S[i], ['0'..'9']) then
Result := Result + S[i];
end;
function SplitStringInTwo(const InputString, Delimiter: string; out LeftPart, RightPart: string): Boolean;
var
DelimiterPos: Integer;
begin
DelimiterPos := Pos(Delimiter, InputString);
Result := (DelimiterPos > 0);
if Result then
begin
LeftPart := Copy(InputString, 1, DelimiterPos - 1);
RightPart := Copy(InputString, DelimiterPos + Length(Delimiter), Length(InputString) - DelimiterPos - Length(Delimiter) + 1);
end
else
begin
LeftPart := '';
RightPart := '';
end;
end;
function destilujTelCislo(telCislo: string): string;
var
regexpr : TRegEx;
match : TMatch;
begin
Result := '';
telCislo := stringreplace(telCislo, '+420', '', [rfReplaceAll, rfIgnoreCase]);
telCislo := RemoveSpaces(telCislo); // nekdy jsou cisla psana jako 3 skupiny po 3 znacich
regexpr := TRegEx.Create('\d{9}',[roIgnoreCase,roMultiline]); //hledam devitimistne cislo
match := regexpr.Match(telCislo);
if match.Success then
Result := match.Value;
end;
function destilujMobilCislo(telCislo: string): string;
var
regexpr : TRegEx;
match : TMatch;
begin
Result := '';
telCislo := stringreplace(telCislo, '+420', '', [rfReplaceAll, rfIgnoreCase]);
telCislo := RemoveSpaces(telCislo); // nekdy jsou cisla psana jako 3 skupiny po 3 znacich
regexpr := TRegEx.Create('[6-7]{1}\d{8}',[roIgnoreCase,roMultiline]); //hledam devitimistne cislo zacinajici na 6 nebo 7
match := regexpr.Match(telCislo);
if match.Success then
Result := match.Value;
end;
function FindInFolder(sFolder, sFile: string; bUseSubfolders: Boolean): string;
var
sr: TSearchRec;
i: Integer;
sDatFile: String;
begin
Result := '';
sFolder := IncludeTrailingPathDelimiter(sFolder);
if System.SysUtils.FindFirst(sFolder + sFile, faAnyFile - faDirectory, sr) = 0 then
begin
Result := sFolder + sr.Name;
System.SysUtils.FindClose(sr);
Exit;
end;
//not found .... search in subfolders
if bUseSubfolders then
begin
//find first subfolder
if System.SysUtils.FindFirst(sFolder + '*.*', faDirectory, sr) = 0 then
begin
try
repeat
if ((sr.Attr and faDirectory) <> 0) and (sr.Name <> '.') and (sr.Name <> '..') then //is real folder?
begin
//recursive call!
//Result := FindInFolder(sFolder + sr.Name, sFile, bUseSubfolders); // plná rekurze
Result := FindInFolder(sFolder + sr.Name, sFile, false); // rekurze jen do 1. úrovně
if Length(Result) > 0 then Break; //found it ... escape
end;
until System.SysUtils.FindNext(sr) <> 0; //...next subfolder
finally
System.SysUtils.FindClose(sr);
end;
end;
end;
end;
procedure writeToFile(pFileName, pContent : string);
var
OutputFile : TextFile;
begin
AssignFile(OutputFile, pFileName);
ReWrite(OutputFile);
WriteLn(OutputFile, pContent);
CloseFile(OutputFile);
end;
procedure appendToFile(pFileName, pContent : string);
var
F : TextFile;
begin
AssignFile(F, pFileName);
try
if FileExists(pFileName) = false then
Rewrite(F)
else
begin
Append(F);
end;
Writeln(F, pContent);
finally
CloseFile(F);
end;
end;
function LoadFileToStr(const FileName: TFileName): ansistring;
var
FileStream : TFileStream;
begin
FileStream:= TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
if FileStream.Size>0 then
begin
SetLength(Result, FileStream.Size);
FileStream.Read(Pointer(Result)^, FileStream.Size);
end;
finally
FileStream.Free;
end;
end;
function RandString(const stringsize: integer): string;
var
i: integer;
const ss: string = 'abcdefghijklmnopqrstuvwxyz';
begin
for i:=1 to stringsize do
Result:=Result + ss[random(length(ss)) + 1];
end;
// FloatToStr s nahrazením čárek tečkami
function FloatToStrFD (pFloat : extended) : string;
begin
Result := AnsiReplaceStr(FloatToStr(pFloat), ',', '.');
end;
function debugRozdilCasu(cas01, cas02 : double; textZpravy : string) : string;
// do DebugString vypíše časový rozdíl a zprávu
begin
cas01 := cas01 * 24 * 3600;
cas02 := cas02 * 24 * 3600;
Result := 'Trvání: ' + FloatToStr(RoundTo(cas02 - cas01, -2)) + ' s, ' + textZpravy;
if DesU.appMode >= 3 then OutputDebugString(PChar(Result));
end;
procedure RunCMD(cmdLine: string; WindowMode: integer);
procedure ShowWindowsErrorMessage(r: integer);
var
sMsg: string;
begin
sMsg := SysErrorMessage(r);
if (sMsg = '') and (r = ERROR_BAD_EXE_FORMAT) then
sMsg := SysErrorMessage(ERROR_BAD_FORMAT);
MessageDlg(sMsg, mtError, [mbOK], 0);
end;
var
si: TStartupInfo;
pi: TProcessInformation;
sei: TShellExecuteInfo;
err: Integer;
begin
// We need a function which does following:
// 1. Replace the Environment strings, e.g. %SystemRoot% --> ExpandEnvStr
// 2. Runs EXE files with parameters (e.g. "cmd.exe /?") --> WinExec
// 3. Runs EXE files without path (e.g. "calc.exe") --> WinExec
// 4. Runs EXE files without extension (e.g. "calc") --> WinExec
// 5. Runs non-EXE files (e.g. "Letter.doc") --> ShellExecute
// 6. Commands with white spaces (e.g. "C:\Program Files\xyz.exe") must be enclosed in quotes.
//cmdLine := ExpandEnvStr(cmdLine); // *hw* nefunguje mi, nepotrebujeme
{$IFDEF UNICODE}
UniqueString(cmdLine);
{$ENDIF}
ZeroMemory(@si, sizeof(si));
si.cb := sizeof(si);
si.dwFlags := STARTF_USESHOWWINDOW;
si.wShowWindow := WindowMode;
if CreateProcess(nil, PChar(cmdLine), nil, nil, False, 0, nil, nil, si, pi) then
begin
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
Exit;
end;
err := GetLastError;
if (err = ERROR_BAD_EXE_FORMAT) or
(err = ERROR_BAD_FORMAT) then
begin
ZeroMemory(@sei, sizeof(sei));
sei.cbSize := sizeof(sei);
sei.lpFile := PChar(cmdLine);
sei.nShow := WindowMode;
if ShellExecuteEx(@sei) then Exit;
err := GetLastError;
end;
ShowWindowsErrorMessage(err);
end;
function getWindowsUserName : string;
// přívětivější GetUserName
var
dwSize : DWord;
begin
SetLength(Result, 32);
dwSize := 31;
GetUserName(PChar(Result), dwSize);
SetLength(Result, dwSize);
end;
// ------------------------------------------------------------------------------------------------
function getWindowsCompName : string;
// přívětivější GetComputerName
var
dwSize : DWord;
begin
SetLength(Result, 32);
dwSize := 31;
GetComputerName(PChar(Result), dwSize);
SetLength(Result, dwSize);
end;
end.
|
unit UFrmCatalogoMateriales;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmMiniCatalogo, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, dxRibbonSkins, dxSkinsCore, dxSkinBlack, dxSkinBlue,
dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic,
dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters,
dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue,
dxSkinsdxRibbonPainter, dxRibbonCustomizationForm, cxStyles,
dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit,
cxNavigator, DB, cxDBData, dxBarBuiltInMenu, dxSkinsdxBarPainter, dxBar,
dxRibbon, ZAbstractRODataset, ZAbstractDataset, ZDataset, cxSplitter,
dxLayoutContainer, dxLayoutControl, cxPC, ExtCtrls, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid, cxContainer, dxLayoutcxEditAdapters, cxTextEdit, cxDBEdit, cxMaskEdit,
cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxCalendar,
UConection, MemDS, DBAccess, Uni;
type
TFrmCatalogoMateriales = class(TFrmMiniCatalogo)
cxColCodigo: TcxGridDBColumn;
cxColMaterial: TcxGridDBColumn;
cxColUMedida: TcxGridDBColumn;
cxColFecha: TcxGridDBColumn;
cxTextCodigo: TcxDBTextEdit;
lyCodigo: TdxLayoutItem;
cxTextMaterial: TcxDBTextEdit;
lyMaterial: TdxLayoutItem;
cbbUMedida: TcxDBLookupComboBox;
lyUMedida: TdxLayoutItem;
cxDateFecha: TcxDBDateEdit;
lyFecha: TdxLayoutItem;
zUMedida: TUniQuery;
dsUMedida: TDataSource;
procedure FormCreate(Sender: TObject);
procedure dxButtonNuevoClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmCatalogoMateriales: TFrmCatalogoMateriales;
implementation
{$R *.dfm}
procedure TFrmCatalogoMateriales.dxButtonNuevoClick(Sender: TObject);
begin
inherited;
if zDatosUPt.Active and (zDatosUpt.State in [dsInsert]) then
begin
zDatosUPT.FieldByName('Fecharegistro').AsDateTime := NOW();
zDatosUpt.FieldByName('Tipo').AsString := 'MATERIAL';
end;
end;
procedure TFrmCatalogoMateriales.FormCreate(Sender: TObject);
begin
inherited;
QueryName := 'factura_servicios';
PKField := 'IdServicio';
CampoMostrar := 'Servicio';
pCondiciones := '~(IdServicio)&(Codigo)';
pCampos := 'IdServicio,Codigo';
end;
procedure TFrmCatalogoMateriales.FormShow(Sender: TObject);
begin
inherited;
AsignarSQL(zUMedida, 'master_unidadmedida', pReadOnly);
FiltrarDataset(zUMedida, 'IdUnidadMedida', ['-1']);
if zUMedida.Active then
zUMedida.Refresh
else
zUMedida.Open;
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Janela Abertura OS
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com</p>
@author Albert Eije (alberteije@gmail.com)
@version 2.0
******************************************************************************* }
unit UOSAbertura;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UTelaCadastro, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids,
JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, Mask, JvExMask, JvToolEdit,
JvCombobox, LabeledCtrls, DBCtrls, LabeledDBCtrls, DB, DBClient, StrUtils,
Math, JSonVO, Generics.Collections, Atributos, Constantes, CheckLst,
JvExCheckLst, JvCheckListBox, JvBaseEdits, OleCtnrs, WideStrings, FMTBcd,
Provider, SqlExpr, DBXMySql, PlatformDefaultStyleActnCtrls, ActnList, ActnMan,
ToolWin, ActnCtrls, ShellApi, Biblioteca, System.Actions, Controller;
type
TFOSAbertura = class(TFTelaCadastro)
ScrollBox: TScrollBox;
PageControlDadosOSAbertura: TPageControl;
tsDadosComplementares: TTabSheet;
tsProdutoServico: TTabSheet;
PanelDocumentacao: TPanel;
GridProdutoServico: TJvDBUltimGrid;
tsEquipamento: TTabSheet;
PanelDepreciacao: TPanel;
GridEquipamentos: TJvDBUltimGrid;
EditIdStatusOS: TLabeledCalcEdit;
EditStatusNome: TLabeledEdit;
PanelDadosComplementares: TPanel;
EditDataInicio: TLabeledDateEdit;
EditDataPrevisao: TLabeledDateEdit;
EditDataFim: TLabeledDateEdit;
MemoObservacaoCliente: TLabeledMemo;
CDSOSProdutoServico: TClientDataSet;
DSOSProdutoServico: TDataSource;
CDSOSEvolucao: TClientDataSet;
DSOSEvolucao: TDataSource;
tsEvolucao: TTabSheet;
PanelMovimentacao: TPanel;
GridEvolucao: TJvDBUltimGrid;
CDSOSAberturaEquipamento: TClientDataSet;
DSOSAberturaEquipamento: TDataSource;
EditIdColaborador: TLabeledCalcEdit;
EditColaboradorNome: TLabeledEdit;
EditIdCliente: TLabeledCalcEdit;
EditClienteNome: TLabeledEdit;
EditNumero: TLabeledEdit;
EditNomeContato: TLabeledEdit;
ActionToolBarDepreciacao: TActionToolBar;
ActionManagerBem: TActionManager;
ActionToolBar1: TActionToolBar;
BevelEdits: TBevel;
EditHoraInicio: TLabeledMaskEdit;
EditHoraPrevisao: TLabeledMaskEdit;
EditHoraFim: TLabeledMaskEdit;
EditFoneContato: TLabeledMaskEdit;
MemoObservacaoAbertura: TLabeledMemo;
procedure ControlaPersistencia(pDataSet: TDataSet);
procedure FormCreate(Sender: TObject);
procedure GridProdutoServicoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure GridEquipamentosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure GridEvolucaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditIdStatusOSKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditIdColaboradorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditIdClienteKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
IdTipoOSAbertura: Integer;
public
{ Public declarations }
procedure GridParaEdits; override;
procedure LimparCampos; override;
// Controles CRUD
function DoInserir: Boolean; override;
function DoEditar: Boolean; override;
function DoExcluir: Boolean; override;
function DoSalvar: Boolean; override;
procedure ConfigurarLayoutTela;
end;
var
FOSAbertura: TFOSAbertura;
implementation
uses OSAberturaVO, OSAberturaController, OsProdutoServicoVO,
OsEquipamentoVO, OsEvolucaoVO, ULookup, UDataModule,
ViewPessoaColaboradorVO, ViewPessoaColaboradorController,
ViewPessoaClienteVO, ViewPessoaClienteController, OsStatusVO,
OsStatusController, ProdutoVO, ProdutoController, OsEquipamentoController,
OsAberturaEquipamentoVO;
{$R *.dfm}
{$REGION 'Infra'}
procedure TFOSAbertura.FormCreate(Sender: TObject);
var
Form: TForm;
begin
ClasseObjetoGridVO := TOSAberturaVO;
ObjetoController := TOSAberturaController.Create;
inherited;
// Configura a Grid dos Produtos
ConfiguraCDSFromVO(CDSOSProdutoServico, TOsProdutoServicoVO);
ConfiguraGridFromVO(GridProdutoServico, TOsProdutoServicoVO);
// Configura a Grid dos Equipamentos
ConfiguraCDSFromVO(CDSOSAberturaEquipamento, TOsAberturaEquipamentoVO);
ConfiguraGridFromVO(GridEquipamentos, TOsAberturaEquipamentoVO);
// Configura a Grid das Evoluções
ConfiguraCDSFromVO(CDSOSEvolucao, TOsEvolucaoVO);
ConfiguraGridFromVO(GridEvolucao, TOsEvolucaoVO);
end;
procedure TFOSAbertura.LimparCampos;
var
i: Integer;
begin
inherited;
CDSOSProdutoServico.EmptyDataSet;
CDSOSAberturaEquipamento.EmptyDataSet;
CDSOSEvolucao.EmptyDataSet;
ConfigurarLayoutTela;
end;
procedure TFOSAbertura.ConfigurarLayoutTela;
begin
PanelEdits.Enabled := True;
PageControlDadosOSAbertura.ActivePageIndex := 0;
if StatusTela = stNavegandoEdits then
begin
PanelDadosComplementares.Enabled := False;
GridProdutoServico.ReadOnly := True;
GridEquipamentos.ReadOnly := True;
GridEvolucao.ReadOnly := True;
end
else
begin
PanelDadosComplementares.Enabled := True;
GridProdutoServico.ReadOnly := False;
GridEquipamentos.ReadOnly := False;
GridEvolucao.ReadOnly := False;
end;
end;
{$ENDREGION}
{$REGION 'Controles CRUD'}
function TFOSAbertura.DoInserir: Boolean;
begin
Result := inherited DoInserir;
if Result then
begin
EditIdStatusOS.SetFocus;
end;
end;
function TFOSAbertura.DoEditar: Boolean;
begin
Result := inherited DoEditar;
if Result then
begin
EditIdStatusOS.SetFocus;
end;
end;
function TFOSAbertura.DoExcluir: Boolean;
begin
if inherited DoExcluir then
begin
try
TController.ExecutarMetodo('OsAberturaController.TOsAberturaController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean');
Result := TController.RetornoBoolean;
except
Result := False;
end;
end
else
begin
Result := False;
end;
if Result then
TController.ExecutarMetodo('OsAberturaController.TOsAberturaController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista');
end;
function TFOSAbertura.DoSalvar: Boolean;
begin
Result := inherited DoSalvar;
if Result then
begin
try
if not Assigned(ObjetoVO) then
ObjetoVO := TOSAberturaVO.Create;
/// EXERCICIO: Preencha os dados dos campos transientes
TOSAberturaVO(ObjetoVO).IdOsStatus := EditIdStatusOS.AsInteger;
TOSAberturaVO(ObjetoVO).IdColaborador := EditIdColaborador.AsInteger;
TOSAberturaVO(ObjetoVO).IdCliente := EditIdCliente.AsInteger;
TOSAberturaVO(ObjetoVO).Numero := EditNumero.Text;
TOSAberturaVO(ObjetoVO).DataInicio := EditDataInicio.Date;
TOSAberturaVO(ObjetoVO).HoraInicio := EditHoraInicio.Text;
TOSAberturaVO(ObjetoVO).DataPrevisao := EditDataPrevisao.Date;
TOSAberturaVO(ObjetoVO).HoraPrevisao := EditHoraPrevisao.Text;
TOSAberturaVO(ObjetoVO).DataFim := EditDataFim.Date;
TOSAberturaVO(ObjetoVO).HoraFim := EditHoraFim.Text;
TOSAberturaVO(ObjetoVO).NomeContato := EditNomeContato.Text;
TOSAberturaVO(ObjetoVO).FoneContato := EditFoneContato.Text;
TOSAberturaVO(ObjetoVO).ObservacaoCliente := MemoObservacaoCliente.Text;
TOSAberturaVO(ObjetoVO).ObservacaoAbertura := MemoObservacaoAbertura.Text;
// Produtos
TController.PreencherObjectListFromCDS<TOsProdutoServicoVO>(TOSAberturaVO(ObjetoVO).ListaOsProdutoServicoVO, CDSOSProdutoServico);
// Equipamentos
TController.PreencherObjectListFromCDS<TOsAberturaEquipamentoVO>(TOSAberturaVO(ObjetoVO).ListaOsEquipamentoVO, CDSOSAberturaEquipamento);
// Evoluções
TController.PreencherObjectListFromCDS<TOsEvolucaoVO>(TOSAberturaVO(ObjetoVO).ListaOsEvolucaoVO, CDSOSEvolucao);
if StatusTela = stInserindo then
begin
TController.ExecutarMetodo('OsAberturaController.TOsAberturaController', 'Insere', [TOSAberturaVO(ObjetoVO)], 'PUT', 'Lista');
end
else if StatusTela = stEditando then
begin
if TOSAberturaVO(ObjetoVO).ToJSONString <> StringObjetoOld then
begin
TController.ExecutarMetodo('OsAberturaController.TOsAberturaController', 'Altera', [TOSAberturaVO(ObjetoVO)], 'POST', 'Boolean');
end
else
Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
end;
except
Result := False;
end;
end;
end;
{$ENDREGION}
{$REGION 'Campos Transientes'}
procedure TFOSAbertura.EditIdColaboradorKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Filtro: String;
begin
if Key = VK_F1 then
begin
if EditIdColaborador.Value <> 0 then
Filtro := 'ID = ' + EditIdColaborador.Text
else
Filtro := 'ID=0';
try
EditIdColaborador.Clear;
EditColaboradorNome.Clear;
if not PopulaCamposTransientes(Filtro, TViewPessoaColaboradorVO, TViewPessoaColaboradorController) then
PopulaCamposTransientesLookup(TViewPessoaColaboradorVO, TViewPessoaColaboradorController);
if CDSTransiente.RecordCount > 0 then
begin
EditIdColaborador.Text := CDSTransiente.FieldByName('ID').AsString;
EditColaboradorNome.Text := CDSTransiente.FieldByName('NOME').AsString;
end
else
begin
Exit;
EditIdCliente.SetFocus;
end;
finally
CDSTransiente.Close;
end;
end;
end;
procedure TFOSAbertura.EditIdClienteKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Filtro: String;
begin
if Key = VK_F1 then
begin
if EditIdCliente.Value <> 0 then
Filtro := 'ID = ' + EditIdCliente.Text
else
Filtro := 'ID=0';
try
EditIdCliente.Clear;
EditClienteNome.Clear;
if not PopulaCamposTransientes(Filtro, TViewPessoaClienteVO, TViewPessoaClienteController) then
PopulaCamposTransientesLookup(TViewPessoaClienteVO, TViewPessoaClienteController);
if CDSTransiente.RecordCount > 0 then
begin
EditIdCliente.Text := CDSTransiente.FieldByName('ID').AsString;
EditClienteNome.Text := CDSTransiente.FieldByName('NOME').AsString;
end
else
begin
Exit;
EditNumero.SetFocus;
end;
finally
CDSTransiente.Close;
end;
end;
end;
procedure TFOSAbertura.EditIdStatusOSKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Filtro: String;
begin
if Key = VK_F1 then
begin
if EditIdStatusOS.Value <> 0 then
Filtro := 'ID = ' + EditIdStatusOS.Text
else
Filtro := 'ID=0';
try
EditIdStatusOS.Clear;
EditStatusNome.Clear;
if not PopulaCamposTransientes(Filtro, TOsStatusVO, TOsStatusController) then
PopulaCamposTransientesLookup(TOsStatusVO, TOsStatusController);
if CDSTransiente.RecordCount > 0 then
begin
EditIdStatusOS.Text := CDSTransiente.FieldByName('ID').AsString;
EditStatusNome.Text := CDSTransiente.FieldByName('NOME').AsString;
end
else
begin
Exit;
EditIdColaborador.SetFocus;
end;
finally
CDSTransiente.Close;
end;
end;
end;
{$ENDREGION}
{$REGION 'Controle de Grid'}
procedure TFOSAbertura.GridParaEdits;
begin
inherited;
if not CDSGrid.IsEmpty then
begin
ObjetoVO := TOSAberturaVO(TController.BuscarObjeto('OsAberturaController.TOsAberturaController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET'));
end;
if Assigned(ObjetoVO) then
begin
EditIdStatusOS.AsInteger := TOSAberturaVO(ObjetoVO).IdOsStatus;
EditIdColaborador.AsInteger := TOSAberturaVO(ObjetoVO).IdColaborador;
EditIdCliente.AsInteger := TOSAberturaVO(ObjetoVO).IdCliente;
EditNumero.Text := TOSAberturaVO(ObjetoVO).Numero;
EditDataInicio.Date := TOSAberturaVO(ObjetoVO).DataInicio;
EditHoraInicio.Text := TOSAberturaVO(ObjetoVO).HoraInicio;
EditDataPrevisao.Date := TOSAberturaVO(ObjetoVO).DataPrevisao;
EditHoraPrevisao.Text := TOSAberturaVO(ObjetoVO).HoraPrevisao;
EditDataFim.Date := TOSAberturaVO(ObjetoVO).DataFim;
EditHoraFim.Text := TOSAberturaVO(ObjetoVO).HoraFim;
EditNomeContato.Text := TOSAberturaVO(ObjetoVO).NomeContato;
EditFoneContato.Text := TOSAberturaVO(ObjetoVO).FoneContato;
MemoObservacaoCliente.Text := TOSAberturaVO(ObjetoVO).ObservacaoCliente;
MemoObservacaoAbertura.Text := TOSAberturaVO(ObjetoVO).ObservacaoAbertura;
// Preenche as grids internas com os dados das Listas que vieram no objeto
TController.TratarRetorno<TOsProdutoServicoVO>(TOSAberturaVO(ObjetoVO).ListaOsProdutoServicoVO, True, True, CDSOSProdutoServico);
TController.TratarRetorno<TOsAberturaEquipamentoVO>(TOSAberturaVO(ObjetoVO).ListaOsEquipamentoVO, True, True, CDSOSAberturaEquipamento);
TController.TratarRetorno<TOsEvolucaoVO>(TOSAberturaVO(ObjetoVO).ListaOsEvolucaoVO, True, True, CDSOSEvolucao);
// Limpa as listas para comparar posteriormente se houve inclusões/alterações e subir apenas o necessário para o servidor
TOSAberturaVO(ObjetoVO).ListaOsProdutoServicoVO.Clear;
TOSAberturaVO(ObjetoVO).ListaOsEquipamentoVO.Clear;
TOSAberturaVO(ObjetoVO).ListaOsEvolucaoVO.Clear;
// Serializa o objeto para consultar posteriormente se houve alterações
FormatSettings.DecimalSeparator := '.';
StringObjetoOld := ObjetoVO.ToJSONString;
FormatSettings.DecimalSeparator := ',';
end;
end;
procedure TFOSAbertura.GridProdutoServicoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_F1 then
begin
try
PopulaCamposTransientesLookup(TProdutoVO, TProdutoController);
if CDSTransiente.RecordCount > 0 then
begin
CDSOSProdutoServico.Append;
CDSOSProdutoServico.FieldByName('ID_PRODUTO').AsInteger := CDSTransiente.FieldByName('ID').AsInteger;
CDSOSProdutoServico.FieldByName('VALOR_UNITARIO').AsFloat := CDSTransiente.FieldByName('VALOR_VENDA').AsFloat;
CDSOSProdutoServico.Post;
end;
finally
CDSTransiente.Close;
end;
end;
//
If Key = VK_RETURN then
GridProdutoServico.SelectedIndex := GridProdutoServico.SelectedIndex + 1;
end;
procedure TFOSAbertura.GridEquipamentosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
/// EXERCICIO
/// Insira na grid a opção para o usuário selecionar entre (0=NENHUM | 1=GARANTIA | 2=SEGURO | 3=CONTRATO)
/// para o campo Tipo Cobertura
if Key = VK_F1 then
begin
try
PopulaCamposTransientesLookup(TOsEquipamentoVO, TOsEquipamentoController);
if CDSTransiente.RecordCount > 0 then
begin
CDSOSAberturaEquipamento.Append;
CDSOSAberturaEquipamento.FieldByName('ID_OS_EQUIPAMENTO').AsInteger := CDSTransiente.FieldByName('ID').AsInteger;
CDSOSAberturaEquipamento.Post;
end;
finally
CDSTransiente.Close;
end;
end;
//
If Key = VK_RETURN then
GridEquipamentos.SelectedIndex := GridEquipamentos.SelectedIndex + 1;
end;
procedure TFOSAbertura.GridEvolucaoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
If Key = VK_RETURN then
GridEvolucao.SelectedIndex := GridEvolucao.SelectedIndex + 1;
end;
procedure TFOSAbertura.ControlaPersistencia(pDataSet: TDataSet);
begin
pDataSet.FieldByName('PERSISTE').AsString := 'S';
end;
{$ENDREGION}
/// EXERCICIO
/// Onde armazenar o agendamento das visitas técnicas? É preciso uma nova tabela?
/// Faça a integração com a agenda corporativa do técnico no momento da abertura da OS
/// EXERCICIO
/// A partir da OS criada, gere um orçamento de venda no módulo Vendas
/// EXERCICIO
/// O SB menciona a integração com o Financeiro e NF-e/NFS-e.
/// A única integração necessária aqui é com o módulo Vendas, pois de lá
/// já deve existir a integração com o financeiro e NF-e/NFS-e
/// EXERCICIO
/// Crie uma janela para mesclagem de OS's ou crie uma opção nesta janela
/// para realizar tal tarefa
end.
|
unit fEscolheProduto;
interface
uses
Generics.Collections,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, AdvEdit, DB, ADODB, Grids, BaseGrid, AdvGrid, DBAdvGrid,
ExtCtrls, AdvObj,
fFormPesquisa,
Entidades.Cadastro,
Aurelius.Bind.Dataset,
Aurelius.Criteria.Base,
Aurelius.Engine.ObjectManager, ActnList, System.Actions;
type
TfmEscolheProduto = class(TfmFormPesquisa)
AureliusDataset1: TAureliusDataset;
Button1: TButton;
Button3: TButton;
ActionList1: TActionList;
acEditar: TAction;
acNovo: TAction;
procedure acEditarExecute(Sender: TObject);
procedure acNovoExecute(Sender: TObject);
procedure acEditarUpdate(Sender: TObject);
private
FServicesOnly: boolean;
protected
function DefineCriteria: TCriteria; override;
function Dataset: TAureliusDataset; override;
procedure FilterRecord(DataSet: TDataSet; AText: string; var Accept: Boolean); override;
public
property ServicesOnly: boolean read FServicesOnly write FServicesOnly;
end;
implementation
uses
Aurelius.Criteria.Linq,
dConnection,
fProduto,
Math,
StrUtils;
{$R *.dfm}
procedure TfmEscolheProduto.acEditarExecute(Sender: TObject);
begin
if TfmProduto.Editar(AureliusDataset1.Current<TProduto>.Id) then
AtualizaListagem;
end;
procedure TfmEscolheProduto.acEditarUpdate(Sender: TObject);
begin
acEditar.Enabled := AureliusDataset1.Current<TProduto> <> nil;
end;
procedure TfmEscolheProduto.acNovoExecute(Sender: TObject);
begin
if TfmProduto.Editar(Null) then
AtualizaListagem;
end;
function TfmEscolheProduto.Dataset: TAureliusDataset;
begin
Result := AureliusDataset1;
end;
function TfmEscolheProduto.DefineCriteria: TCriteria;
begin
if ServicesOnly then
Result := Manager.Find<TProduto>
.Where(not TLinq.Eq('Area', TArea.Loja))
else
Result := inherited DefineCriteria;
end;
procedure TfmEscolheProduto.FilterRecord(DataSet: TDataSet; AText: string;
var Accept: Boolean);
begin
if IntFilterValid then
Accept := Dataset.FieldByName('ProductCode').AsInteger = IntFilter
else
Accept := (Filter = '')
or
(Pos(FilterTrimUpper, Uppercase(Dataset.FieldByName('Descricao').AsString)) > 0)
or
(FilterTrimUpper = Trim(Dataset.FieldByName('CodigoBarras').AsString));
end;
end.
|
unit PTypes;
(*****************************************************************************
Prozessprogrammierung SS08
Aufgabe: Muehle
Datentypen fuer den Prozessrechner.
Autor: Alexander Bertram (B_TInf 2616)
*****************************************************************************)
interface
uses
RTKernel, RTTextIO,
Types;
const
{ Name der Konfigurationsdatei }
cIniFilename = 'MILL.INI';
{ Taskparameter }
{ Spielleiter }
cLeaderPriority = MainPriority;
cLeaderStack = cDefaultStack * 6;
cLeaderTaskName = 'Spielleiter';
cLeaderMailboxSlots = 10;
{ Spieler }
cPlayerPriority = MainPriority + 1;
cPlayerStack = cDefaultStack * 7;
{ Spielstein }
cTokenPriority = MainPriority + 2;
cTokenStack = cDefaultStack * 4;
cTokenTaskName = 'Spielstein';
{ Klautask }
cStealPriority = MainPriority + 3;
cStealStack = cDefaultStack;
cStealTaskName = 'Klautask';
{ Fensterposition }
{ Statistikfensterposition des Benutzers }
cUserStatisticWindowFirstCol = 40;
cUserStatisticWindowFirstRow = 0;
cUserStatisticWindowLastCol = cUserStatisticWindowFirstCol + 39;
cUserStatisticWindowLastRow = cUserStatisticWindowFirstRow + 5;
{ Statusfensterposition des Benutzers }
cUserStatusWindowFirstCol = cUserStatisticWindowFirstCol;
cUserStatusWindowFirstRow = cUserStatisticWindowLastRow + 1;
cUserStatusWindowLastCol = cUserStatusWindowFirstCol + 39;
cUserStatusWindowLastRow = cUserStatusWindowFirstRow + 9;
{ Statistikfensterposition des CPU-Spielers }
cCPUStatisticWindowFirstCol = cUserStatisticWindowFirstCol;
cCPUStatisticWindowFirstRow = cUserStatusWindowLastRow + 1;
cCPUStatisticWindowLastCol = cCPUStatisticWindowFirstCol + 39;
cCPUStatisticWindowLastRow = cCPUStatisticWindowFirstRow + 5;
{ Statusfensterposition des CPU-Spielers }
cCPUStatusWindowFirstCol = cUserStatisticWindowFirstCol;
cCPUStatusWindowFirstRow = cCPUStatisticWindowLastRow + 1;
cCPUStatusWindowLastCol = cCPUStatusWindowFirstCol + 39;
cCPUStatusWindowLastRow = cCPUStatusWindowFirstRow + 10;
{ Spielleiterfenster }
cLeaderWindowFirstCol = 0;
cLeaderWindowFirstRow = 0;
cLeaderWindowLastCol = cLeaderWindowFirstCol + 39;
cLeaderWindowLastRow = cCPUStatusWindowLastRow;
cLeaderWindowColor = Gray;
{ Systemstatusfenster }
cSystemStatusWindowFirstCol = 0;
cSystemStatusWindowFirstRow = 43;
cSystemStatusWindowLastCol = cSystemStatusWindowFirstCol + 79;
cSystemStatusWindowLastRow = cSystemStatusWindowFirstRow + 6;
cSystemStatusWindowFrameColor = LightRed;
cSystemStatusWindowAttribute = Gray;
{ Tasten- / Menuefenster }
cKeyWindowFirstCol = 0;
cKeyWindowFirstRow = cLeaderWindowLastRow + 1;
cKeyWindowLastCol = cKeyWindowFirstCol + 79;
cKeyWindowLastRow = cKeyWindowFirstRow + 9;
cKeyWindowColor = Gray;
{ RTKernel-Timerticks }
cTimerInterval = 1 / 1000;
type
{ Spielsteintaskhandles eines Spielers }
TTokenTaskHandles = array[0..cTokenCount - 1] of TaskHandle;
{ Spielertaskhandles }
TPlayerTaskHandles = array[TPlayer] of TaskHandle;
{ Bedenkzeit }
TTimeLimit = 0..10;
{ Bedenkzeiten beider Spieler }
TPLayerTimeLimits = array[TPLayer] of TTimeLimit;
{ Spielparameter }
TGameParameters = record
{ Erster Spieler }
FirstPlayer: TPlayer;
{ Spielerfarben }
PlayerColors: TPlayerColors;
{ Maximale Bedenkzeit des CPU-Spielers }
CPUMaxTimeLimit: TTimeLimit;
end;
{ Spielleiternachricht }
{ Nachrichtart }
TLeaderMessageKind = (
{ Spielertaskhandles }
lemkPlayerTaskHandles,
{ Erster Spieler }
lemkFirstPlayer,
{ Spielerfarben }
lemkPlayerColors,
{ Initialisierung }
lemkInit,
{ Zugvorbereitung }
lemkPrepareMove,
{ Zug }
lemkMove,
{ Zugbestaetigung }
lemkPlayerMoved,
{ Spielende }
lemkEndGame,
{ Zugwahl des Benutzers }
lemkUserMoveSelected,
{ Anfrage nach Zugmoeglcihkeiten }
lemkGetTokenMovePossibilities,
{ Schlagvorbereitung }
lemkPrepareCapture,
{ Schlag }
lemkCapture,
{ Schlagbestaetigung }
lemkPlayerCaptured,
{ Spielende }
lemkGameOver,
{ Cheatzug }
lemkStealToken,
{ Maximale Bedenkzeit }
lemkTimeLimit);
{ Nachricht }
TLeaderMessage = record
case Kind: TLeaderMessageKind of
lemkPlayerTaskHandles: (
PlayerTaskHandles: TPlayerTaskHandles;
);
lemkFirstPlayer: (
FirstPlayer: TPlayer;
);
lemkPlayerColors: (
PlayerColors: TPlayerColors;
);
lemkUserMoveSelected: (
MoveData: TMoveData;
);
lemkPlayerMoved, lemkPlayerCaptured: (
TokenMoveData: TTokenMoveData;
);
lemkGetTokenMovePossibilities: (
TokenTaskHandle: TaskHandle;
);
lemkTimeLimit: (
TimeLimit: TTimeLimit;
);
end;
{ Spielernachricht }
{ Nachrichtart }
TPlayerMessageKind = (
{ Spielerart }
plmkPlayerKind,
{ Fensterposition }
plmkWindowPosition,
{ Fensterfarbe }
plmkWindowColor,
{ Maximale Bedenkzeit }
plmkMaxTimeLimit,
{ Spielleitertaskhandle }
plmkLeaderTaskhandle,
{ Initialisierung }
plmkInit,
{ Zug }
plmkMove,
{ Spielsteindaten }
plmkTokenData,
{ Inkrementierung der maximalen Bedenkzeit }
plmkIncrementMaxTimeLimit,
{ Dekrementierung der maximalen Bedenkzeit }
plmkDecrementMaxTimeLimit,
{ Zugwahl des Benutzers }
plmkUserMoveSelected,
{ Zugbestaetigung des Spielsteins }
plmkTokenMoved,
{ Anfrage nach Zugmoeglichkeiten }
plmkGetMovePossibilities,
{ Spielfeld }
plmkField,
{ Zugvorbereitung }
plmkPrepareMove,
{ Schlagvorbereitung }
plmkPrepareCapture,
{ Schlag }
plmkCapture,
{ Cheatzug }
plmkStealToken);
{ Nachricht }
TPlayerMessage = record
case Kind: TPlayerMessageKind of
plmkPlayerKind: (
PlayerKind: TPlayer;
);
plmkWindowPosition: (
WindowPosition: TWindowPosition;
);
plmkWindowColor: (
WindowColor: TWindowColor;
);
plmkMaxTimeLimit: (
MaxTimeLimit: TTimeLimit;
);
plmkLeaderTaskhandle: (
LeaderTaskHandle: TaskHandle;
);
plmkTokenData: (
TokenData: TTokenData;
);
plmkGetMovePossibilities: (
TokenTaskHandle: TaskHandle;
);
plmkUserMoveSelected, plmkTokenMoved: (
TokenMoveData: TTokenMoveData;
);
plmkField: (
Field: TField;
);
end;
{ Spielsteinnachricht }
TTokenMessageKind = (
{ Initialisierung }
tmkInit,
{ Spielertaskhandle }
tmkPlayerTaskHandle,
{ Anfrage nach Spielsteindaten }
tmkGetTokenData,
{ Zug }
tmkMove,
{ Zugbestaetigung }
tmkTokenMoved,
{ Spielfeld }
tmkField,
{ Spielerphase }
tmkPlayerStage,
{ Cheatzug }
tmkSteal);
{ Nachricht }
TTokenMessage = record
case Kind: TTokenMessageKind of
tmkPlayerTaskHandle: (
PlayerTaskHandle: TaskHandle;
);
tmkGetTokenData: (
SenderTaskHandle: TaskHandle;
);
tmkMove: (
MoveData: TMoveData;
);
tmkField: (
Field: TField;
);
tmkPlayerStage: (
PlayerStage: TPlayerStage;
);
end;
implementation
end. |
unit TNT_Skybox;
interface
uses
OpenGL12, TNT_Entity, TNT_Texture;
type
TSkybox = class(TEntity)
private
Tex: array [0..5] of TTexture;
public
constructor Create(Name: String);
procedure Render; override;
destructor Destroy; override;
end;
implementation
uses
TNT_3D, TNT_Vector;
constructor TSkybox.Create(Name: String);
begin
inherited EntityCreate(TYPE_SKYBOX, Vector(0,0,0), Vector(0,0,0), 0);
Name := 'skybox/' + Name + '/' + Name;
Tex[0] := TTexture.Create(Name + '_rt.tex', GL_CLAMP, GL_LINEAR, False);
Tex[1] := TTexture.Create(Name + '_ft.tex', GL_CLAMP, GL_LINEAR, False);
Tex[2] := TTexture.Create(Name + '_lf.tex', GL_CLAMP, GL_LINEAR, False);
Tex[3] := TTexture.Create(Name + '_bk.tex', GL_CLAMP, GL_LINEAR, False);
Tex[4] := TTexture.Create(Name + '_up.tex', GL_CLAMP, GL_LINEAR, False);
Tex[5] := TTexture.Create(Name + '_dn.tex', GL_CLAMP, GL_LINEAR, False);
end;
procedure TSkybox.Render;
const
Size = 10;
begin
glPushMatrix;
glLoadIdentity;
Camera.Rotation;
Tex[0].Use(GL_REPLACE);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(-Size, Size, -Size);
glTexCoord2f(0, 1); glVertex3f(-Size, -Size, -Size);
glTexCoord2f(1, 1); glVertex3f(Size, -Size, -Size);
glTexCoord2f(1, 0); glVertex3f(Size, Size, -Size);
glEnd;
Tex[1].Use(GL_REPLACE);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(Size, Size, -Size);
glTexCoord2f(0, 1); glVertex3f(Size, -Size, -Size);
glTexCoord2f(1, 1); glVertex3f(Size, -Size, Size);
glTexCoord2f(1, 0); glVertex3f(Size, Size, Size);
glEnd;
Tex[2].Use(GL_REPLACE);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(Size, Size, Size);
glTexCoord2f(0, 1); glVertex3f(Size, -Size, Size);
glTexCoord2f(1, 1); glVertex3f(-Size, -Size, Size);
glTexCoord2f(1, 0); glVertex3f(-Size, Size, Size);
glEnd;
Tex[3].Use(GL_REPLACE);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(-Size, Size, Size);
glTexCoord2f(0, 1); glVertex3f(-Size, -Size, Size);
glTexCoord2f(1, 1); glVertex3f(-Size, -Size, -Size);
glTexCoord2f(1, 0); glVertex3f(-Size, Size, -Size);
glEnd;
{ Tex[4].Use(GL_REPLACE);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(x-Size, y+Size, z+Size);
glTexCoord2f(0, 1); glVertex3f(x-Size, y+Size, z-Size);
glTexCoord2f(1, 1); glVertex3f(x+Size, y+Size, z-Size);
glTexCoord2f(1, 0); glVertex3f(x+Size, y+Size, z+Size);
glEnd;
Tex[5].Use(GL_REPLACE);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(x-Size, y-Size, z-Size);
glTexCoord2f(0, 1); glVertex3f(x-Size, y-Size, z+Size);
glTexCoord2f(1, 1); glVertex3f(x+Size, y-Size, z+Size);
glTexCoord2f(1, 0); glVertex3f(x+Size, y-Size, z-Size);
glEnd;}
glPopMatrix;
glClear(GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
TNT.Tris := TNT.Tris + 4;
end;
destructor TSkybox.Destroy;
var
i: Integer;
begin
for i := 0 to 5 do
Tex[i].Free;
inherited Destroy;
end;
end.
|
unit RegisterAgency;
{This is the registration form logic for Agency.}
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.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
{This is the database unit used for the query}
dmAgency;
type
TRegAgency = class(TForm)
{This are simple text edit boxes, where the user`s inputed data are stored, before quering to database}
AgencyName: TEdit;
AgencyAddress: TEdit;
AgencyPhone: TEdit;
{This is used as a static text to indicate the user what has to input}
Name: TStaticText;
Address: TStaticText;
Phone: TStaticText;
{Button that has an event, that will register the data.}
RegisterButton: TButton;
{This is the procedure that is an event.}
procedure RegisterButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
RegAgency: TRegAgency;
implementation
{$R *.dfm}
{Executes Query to insert record!}
procedure TRegAgency.RegisterButtonClick(Sender: TObject);
begin
{Checks if empty string is pushed to the database}
if (AgencyName.Text<>'') and (AgencyPhone.Text <>'') and (AgencyAddress.Text<>'') then
begin
{From the dmAgency I`m Using qrAgency (Object that is used to query the database.)}
with dmAgency.Form3.qrAgency do
begin
{This is where the magic is happening.}
dmAgency.Form3.qrAgency.Close;
dmAgency.Form3.qrAgency.SQL.Clear;
dmAgency.Form3.qrAgency.SQL.Add('INSERT INTO AGENCY (AGENCY_NAME, AGENCY_ADDRESS, AGENCY_PHONE )');
dmAgency.Form3.qrAgency.SQL.Add('VALUES ('''+AgencyName.Text+''',');
dmAgency.Form3.qrAgency.SQL.Add(' '''+AgencyAddress.Text+''',');
dmAgency.Form3.qrAgency.SQL.Add(' '''+AgencyPhone.Text+''')');
dmAgency.Form3.qrAgency.ExecSQL;
{After inserting query executes the form will be closed.}
RegAgency.Close;
end;
end
else
begin
ShowMessage('No Empty Values!');
end;
end;
end.
|
unit BPLA;
interface
type TBPLA = class(TObject)
x,xprev:extended;
y,yprev:extended;
z,zprev:extended;
Vxy:extended;
Vz:extended;
Axy:extended;
Az:extended;
angle:extended;
procedure MoveX (t:extended;t0:extended);
// procedure MoveZ (t:extended);
constructor Create(x0,y0,z0,Vx0,Vy0,Axy0,Az0,angle0:extended);
destructor Destroy;
end;
implementation
constructor TBPLA.Create(x0,y0,z0,Vx0,Vy0,Axy0,Az0,angle0:extended);
begin
self.x:=x0;
self.y:=y0;
self.z:=z0;
self.Vxy:=Vx0;
self.Vz:=Vy0;
self.Axy:=Axy0;
self.Az:=Az0;
self.angle:=angle0;
end;
destructor TBPLA.Destroy;
begin
end;
Procedure TBPLA.MoveX(t: Extended; t0:Extended);
begin
self.Vxy:=self.Vxy+self.Az*(t-t0);
self.x:=self.xprev-self.Vxy*cos(angle)*(t-t0);
self.y:=self.yprev-self.Vxy*sin(angle)*(t-t0);
self.z:=self.zprev-self.Vz*(t-t0);
self.xprev:=x;
self.yprev:=y;
self.zprev:=z; //Впихнуть закон изменения ускорения
end;
end.
|
{
/**
* @package VerySimple.Lua
* @copyright Copyright (c) 2009-2015 Dennis D. Spreen (http://blog.spreendigital.de/)
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @author Dennis D. Spreen <dennis@spreendigital.de>
* @version 2.0
* @url http://blog.spreendigital.de/2015/02/18/verysimple-lua-2-0-a-cross-platform-lua-5-3-0-wrapper-for-delphi-xe5-xe7/
*/
History
2.0 DS Updated Lua Lib to 5.3.0
Rewrite of Delphi register functions
Removed Class only functions
Removed a lot of convenience overloaded functions
Support for mobile compiler
1.4 DS Rewrite of Lua function calls, they use now published static
methods, no need for a Callbacklist required anymore
Added Package functions
Added Class registering functions
1.3 DS Improved Callback, now uses pointer instead of object index
Modified RegisterFunctions to allow methods from other class
to be registered, moved object table into TLua class
1.2 DS Added example on how to extend lua with a delphi dll
1.1 DS Improved global object table, this optimizes the delphi
function calls
1.0 DS Initial Release
Copyright 2009-2015 Dennis D. Spreen (email: dennis@spreendigital.de)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
}
unit VerySimple.Lua;
interface
{$M+}
uses
{$IF defined(POSIX)}
Posix.Dlfcn, Posix.SysTypes, Posix.StdDef,
{$ENDIF}
{$IF defined(MSWINDOWS)}
Winapi.Windows,
{$ELSEIF defined(MACOS)}
{$IFDEF IOS}
{$DEFINE STATICLIBRARY}
{$ENDIF}
{$ELSEIF defined(ANDROID)}
{$ENDIF}
System.Rtti, System.Classes, System.SysUtils, System.IOUtils, Generics.Collections,
VerySimple.Lua.Lib
, uGlobal
;
type
TOnLuaPrint = procedure(Msg: String) of object;
ELuaLibraryNotFound = class(Exception);
ELuaLibraryLoadError = class(Exception);
ELuaLibraryMethodNotFound = class(Exception);
TVerySimpleLua = class(TObject)
private
FLuaState: Lua_State; // Lua instance
FOnPrint: TOnLuaPrint;
FFilePath: String;
FLibraryPath: String;
FAutoRegister: boolean;
FOpened: Boolean;
protected
procedure DoPrint(Msg: String); virtual;
class function ValidMethod(Method: TRttiMethod): Boolean; virtual;
// Internal package registration
class procedure RegisterPackage(L: lua_State; Data: Pointer; Code: Pointer; PackageName: String); overload; virtual;
public
// constructor with Autoregister published functions or without (default)
constructor Create; virtual;
destructor Destroy; override;
procedure Open; virtual;
procedure Close; virtual;
// Convenience Lua function(s)
function DoFile(Filename: String): Integer; virtual;// load file and execute
function DoString(Value: String): Integer; virtual;
function DoChunk(L: Lua_State; Status: Integer): Integer; virtual;
function DoCall(L: Lua_State; NArg, NRes: Integer): Integer; virtual;
function LoadFile(Filename: String): Integer; virtual;
function Run: Integer; virtual;
// functions for manually registering new lua functions
class procedure PushFunction(L: lua_State; Data, Code: Pointer; FuncName: String);
class procedure RegisterFunction(L: lua_State; Func: lua_CFunction; FuncName: String); overload; virtual;
procedure RegisterFunction(Func: lua_CFunction; FuncName: String); overload; virtual;
class procedure RegisterFunction(L: lua_State; Data: Pointer; Code: Pointer; FuncName: String); overload; virtual;
class procedure RegisterFunction(L: lua_State; AClass: TClass; Func, FuncName: String); overload; virtual;
class procedure RegisterFunction(L: lua_State; AObject: TObject; Func, FuncName: String); overload; virtual;
class procedure RegisterClassFunction(L: lua_State; AObject: TObject; Func, FuncName: String); overload; virtual;
procedure RegisterFunction(AClass: TClass; Func: String); overload; virtual;
procedure RegisterFunction(AClass: TClass; Func, FuncName: String); overload; virtual;
procedure RegisterFunction(AObject: TObject; Func, FuncName: String); overload; virtual;
procedure RegisterFunction(AObject: TObject; Func: String); overload; virtual;
procedure RegisterFunction(Func: String); overload; virtual;
procedure RegisterFunction(Func, FuncName: String); overload; virtual;
class procedure RegisterFunctions(L: lua_State; AClass: TClass); overload; virtual;
class procedure RegisterFunctions(L: lua_State; AObject: TObject); overload; virtual;
// automatically register all functions published by a class or an object
procedure RegisterFunctions(AClass: TClass); overload; virtual;
procedure RegisterFunctions(AObject: TObject); overload; virtual;
// ***
// package register functions
// ***
// Register all published functions for a Package table on the stack
class procedure RegisterPackageFunctions(L: lua_State; AObject: TObject); overload; virtual;
// Register a Package with a specific package loader (cdecl static function)
class procedure RegisterPackage(L: lua_State; PackageName: String; InitFunc: lua_CFunction); overload; virtual;
procedure RegisterPackage(PackageName: String; InitFunc: lua_CFunction); overload; inline;
// Register a Package with a specific object package loader
class procedure RegisterPackage(L: lua_State; PackageName: String; AObject: TObject; PackageLoader: String); overload; virtual;
procedure RegisterPackage(PackageName: String; AObject: TObject; PackageLoader: String); overload; inline;
// Register a Package with the default package loader (auto register all published functions)
class procedure RegisterPackage(L: lua_State; PackageName: String; AObject: TObject); overload; virtual;
procedure RegisterPackage(PackageName: String; AObject: TObject); overload; inline;
// ***
// library functions
// ***
class procedure LoadLuaLibrary(const LibraryPath: String); virtual;
class procedure FreeLuaLibrary; virtual;
class function LuaLibraryLoaded: Boolean; virtual;
// ***
// properties
// ***
property AutoRegister: Boolean read FAutoRegister write FAutoRegister;
property FilePath: String read FFilePath write FFilePath;
property LibraryPath: String read FLibraryPath write FLibraryPath;
property OnPrint: TOnLuaPrint read FOnPrint write FOnPrint;
property Opened: Boolean read FOpened;
property LuaState: Lua_State read FLuaState write FLuaState;
published
function print(L: Lua_State): Integer; virtual;
end;
implementation
uses
System.TypInfo, FMx.Dialogs;
type
TLuaProc = function(L: Lua_State): Integer of object; // Lua Function
var
LibraryHandle: HMODULE;
{*
** Message handler used to run all chunks
*}
function MsgHandler(L: Lua_State): Integer; cdecl;
var
Msg: MarshaledAString;
begin
Msg := lua_tostring(L, 1);
if (Msg = NIL) then //* is error object not a string?
if (luaL_callmeta(L, 1, '__tostring') <> 0) and //* does it have a metamethod */
(lua_type(L, -1) = LUA_TSTRING) then //* that produces a string? */
begin
Result := 1; //* that is the message */}
Exit;
end
else
Msg := lua_pushfstring(L, '(error object is a %s value)',
[luaL_typename(L, 1)]);
luaL_traceback(L, L, Msg, 1); //* append a standard traceback */
Result := 1; //* return the traceback */
end;
//
// This function is called by Lua, it extracts the object by
// pointer to the objects method by name, which is then called.
//
// @param Lua_State L Pointer to Lua instance
// @return Integer Number of result arguments on stack
//
function LuaCallBack(L: Lua_State): Integer; cdecl;
var
Routine: TMethod; // Code and Data for the call back method
begin
// Retrieve closure values (=object Pointer)
Routine.Data := lua_topointer(L, lua_upvalueindex(1));
Routine.Code := lua_topointer(L, lua_upvalueindex(2));
// Call object function
Result := TLuaProc(Routine)(L);
end;
function LuaLoadPackage(L: Lua_State): Integer; cdecl;
var
Obj: TObject;
begin
// Retrieve closure values (=object Pointer)
Obj := lua_topointer(L, lua_upvalueindex(1));
// Create new table
lua_newtable(L);
// Register Package functions
TVerySimpleLua.RegisterPackageFunctions(L, Obj);
// Return table
Result := 1;
end;
{ TVerySimpleLua }
procedure TVerySimpleLua.Close;
begin
if not FOpened then
Exit;
FOpened := False;
// Close instance
Lua_Close(LuaState);
end;
constructor TVerySimpleLua.Create;
begin
FAutoRegister := True;
{$IF defined(IOS)}
FilePath := TPath.GetDocumentsPath + PathDelim;
{$ELSEIF defined(ANDROID)}
LibraryPath := IncludeTrailingPathDelimiter(System.IOUtils.TPath.GetLibraryPath) + LUA_LIBRARY;
FilePath := TPath.GetDocumentsPath + PathDelim;
{$ENDIF}
end;
//
// Dispose Lua instance
//
destructor TVerySimpleLua.Destroy;
begin
Close;
inherited;
end;
//
// Wrapper for Lua File load and Execution
//
// @param String Filename Lua Script file name
// @return Integer
//
function TVerySimpleLua.DoChunk(L: Lua_State; Status: Integer): Integer;
begin
if Status = LUA_OK then
Status := DoCall(L, 0, 0);
Result := Status;
end;
{*
** Interface to 'lua_pcall', which sets appropriate message function
** and C-signal handler. Used to run all chunks.
*}
function TVerySimpleLua.DoCall(L: Lua_State; NArg, NRes: Integer): Integer;
var
Status: Integer;
Base: Integer;
begin
Base := lua_gettop(L) - NArg; // function index
lua_pushcfunction(L, msghandler); // push message handler
lua_insert(L, base); // put it under function and args
Status := lua_pcall(L, narg, nres, base);
lua_remove(L, base); // remove message handler from the stack */
Result := Status;
end;
function TVerySimpleLua.DoFile(Filename: String): Integer;
var
Marshall: TMarshaller;
Path: String;
begin
if not Opened then
Open;
Path := FilePath + FileName;
Result := dochunk(LuaState, lual_loadfile(LuaState, Marshall.AsAnsi(Path).ToPointer));
end;
procedure TVerySimpleLua.DoPrint(Msg: String);
begin
if Assigned(FOnPrint) then
FOnPrint(Msg)
else
Writeln(Msg);
end;
function TVerySimpleLua.DoString(Value: String): Integer;
var
Marshall: TMarshaller;
begin
if not Opened then
Open;
Result := luaL_dostring(LuaState, Marshall.AsAnsi(Value).ToPointer);
end;
function TVerySimpleLua.Run: Integer;
begin
Result := dochunk(LuaState, LUA_OK);
end;
class procedure TVerySimpleLua.RegisterFunction(L: lua_State; Func: lua_CFunction;
FuncName: String);
var
Marshall: TMarshaller;
begin
lua_register(L, Marshall.AsAnsi(FuncName).ToPointer, Func);
end;
class procedure TVerySimpleLua.PushFunction(L: lua_State; Data, Code: Pointer; FuncName: String);
var
Marshall: TMarshaller;
begin
// prepare Closure value (Method Name)
lua_pushstring(L, Marshall.AsAnsi(FuncName).ToPointer);
// prepare Closure value (CallBack Object Pointer)
lua_pushlightuserdata(L, Data);
lua_pushlightuserdata(L, Code);
// set new Lua function with Closure values
lua_pushcclosure(L, LuaCallBack, 2);
end;
class procedure TVerySimpleLua.RegisterFunction(L: lua_State; Data, Code: Pointer; FuncName: String);
var
Marshall: TMarshaller;
begin
PushFunction(L, Data, Code, FuncName);
// set table using the method's name
lua_setglobal(L, Marshall.AsAnsi(FuncName).ToPointer);
end;
class procedure TVerySimpleLua.RegisterFunction(L: lua_State; AObject: TObject; Func, FuncName: String);
begin
RegisterFunction(L, AObject, AObject.MethodAddress(Func), FuncName);
end;
class procedure TVerySimpleLua.RegisterClassFunction(L: lua_State; AObject: TObject; Func, FuncName: String);
begin
RegisterFunction(L, Pointer(AObject.ClassType), AObject.ClassType.MethodAddress(Func), FuncName);
end;
class procedure TVerySimpleLua.RegisterFunction(L: lua_State; AClass: TClass; Func, FuncName: String);
begin
RegisterFunction(L, AClass.MethodAddress(Func), FuncName);
end;
procedure TVerySimpleLua.RegisterFunction(Func: lua_CFunction;FuncName: String);
begin
RegisterFunction(LuaState, Func, FuncName);
end;
procedure TVerySimpleLua.RegisterFunction(AClass: TClass; Func: String);
begin
RegisterFunction(LuaState, AClass.MethodAddress(Func), Func);
end;
procedure TVerySimpleLua.RegisterFunction(AClass: TClass; Func, FuncName: String);
begin
RegisterFunction(LuaState, AClass.MethodAddress(Func), FuncName);
end;
procedure TVerySimpleLua.RegisterFunction(AObject: TObject; Func, FuncName: String);
begin
RegisterFunction(LuaState, AObject, Func, FuncName);
end;
procedure TVerySimpleLua.RegisterFunction(AObject: TObject; Func: String);
begin
RegisterFunction(LuaState, AObject, Func, Func);
end;
procedure TVerySimpleLua.RegisterFunction(Func: String);
begin
RegisterFunction(LuaState, self, Func, Func);
end;
procedure TVerySimpleLua.RegisterFunction(Func, FuncName: String);
begin
RegisterFunction(LuaState, self, Func, FuncName);
end;
class procedure TVerySimpleLua.RegisterFunctions(L: lua_State; AClass: TClass);
var
LContext: TRttiContext;
LType: TRttiType;
LMethod: TRttiMethod;
begin
LContext := TRttiContext.Create;
try
LType := LContext.GetType(AClass);
for LMethod in LType.GetMethods do
if ValidMethod(LMethod) then
RegisterFunction(L, AClass, LMethod.Name, LMethod.Name);
finally
LContext.Free;
end;
end;
class function TVerySimpleLua.ValidMethod(Method: TRttiMethod): Boolean;
var
Params: TArray<TRttiParameter>;
Param: TRttiParameter;
begin
Result := False;
// Only published functions with an Integer result allowed
if (Method.Visibility <> mvPublished) or (not Assigned(Method.ReturnType)) or
(Method.ReturnType.TypeKind <> tkInteger) then
Exit;
// Only functions with 1 parameter allowed
Params := Method.GetParameters;
if Length(Params) <> 1 then
Exit;
// Only functions with a Pointer as parameter allowed
Param := Params[0];
if Param.ParamType.TypeKind <> tkPointer then
Exit;
Result := True;
end;
class procedure TVerySimpleLua.RegisterFunctions(L: lua_State; AObject: TObject);
var
LContext: TRttiContext;
LType: TRttiType;
LMethod: TRttiMethod;
begin
LContext := TRttiContext.Create;
try
LType := LContext.GetType(AObject.ClassType);
for LMethod in LType.GetMethods do
begin
// Only published functions with an Integer result allowed
if not ValidMethod(LMethod) then
Continue;
// Register the method based on calling convention and method kind
if LMethod.MethodKind = mkFunction then
RegisterFunction(L, AObject, AObject.MethodAddress(LMethod.Name), LMethod.Name)
else
if LMethod.MethodKind = mkClassFunction then
if (LMethod.IsStatic) and (LMethod.CallingConvention = ccCdecl) then
RegisterFunction(L, lua_CFunction(AObject.MethodAddress(LMethod.Name)), LMethod.Name)
else
RegisterFunction(L, Pointer(AObject.ClassType), AObject.ClassType.MethodAddress(LMethod.Name), LMethod.Name);
end;
finally
LContext.Free;
end;
end;
class procedure TVerySimpleLua.RegisterPackageFunctions(L: lua_State; AObject: TObject);
var
LContext: TRttiContext;
LType: TRttiType;
LMethod: TRttiMethod;
begin
LContext := TRttiContext.Create;
try
LType := LContext.GetType(AObject.ClassType);
for LMethod in LType.GetMethods do
begin
// Only published functions with an Integer result allowed
if not ValidMethod(LMethod) then
Continue;
PushFunction(L, AObject, LMethod.CodeAddress, LMethod.Name);
lua_rawset(L, -3);
end;
finally
LContext.Free;
end;
end;
class procedure TVerySimpleLua.RegisterPackage(L: lua_State; PackageName: String; AObject: TObject);
var
Marshall: TMarshaller;
begin
lua_getglobal(L, 'package'); // get local package table
lua_getfield(L, -1 , 'preload'); // get preload field
// prepare Closure value (Object Object Pointer)
lua_pushlightuserdata(L, AObject);
// set new Lua function with Closure values
lua_pushcclosure(L, LuaLoadPackage, 1);
lua_setfield(L, -2 , Marshall.AsAnsi(PackageName).ToPointer);
lua_pop(L, 2);
end;
procedure TVerySimpleLua.RegisterFunctions(AClass: TClass);
begin
RegisterFunctions(LuaState, AClass);
end;
procedure TVerySimpleLua.RegisterFunctions(AObject: TObject);
begin
RegisterFunctions(LuaState, AObject);
end;
// *******************************
// Package registration procedures
// *******************************
class procedure TVerySimpleLua.RegisterPackage(L: lua_State; PackageName: String;
InitFunc: lua_CFunction);
var
Marshall: TMarshaller;
begin
lua_getglobal(L, 'package'); // get local package table
lua_getfield(L, -1 , 'preload'); // get preload field
lua_pushcfunction(L, InitFunc);
lua_setfield(L, -2 , Marshall.AsAnsi(PackageName).ToPointer);
lua_pop(L, 2);
end;
procedure TVerySimpleLua.RegisterPackage(PackageName: String; InitFunc: lua_CFunction);
begin
RegisterPackage(LuaState, PackageName, InitFunc);
end;
class procedure TVerySimpleLua.RegisterPackage(L: lua_State; Data, Code: Pointer; PackageName: String);
var
Marshall: TMarshaller;
begin
lua_getglobal(L, 'package'); // get local package table
lua_getfield(L, -1 , 'preload'); // get preload field
// prepare Closure value (CallBack Object Pointer)
lua_pushlightuserdata(L, Data);
lua_pushlightuserdata(L, Code);
// set new Lua function with Closure values
lua_pushcclosure(L, LuaCallBack, 2);
lua_setfield(L, -2 , Marshall.AsAnsi(PackageName).ToPointer);
lua_pop(L, 2);
end;
procedure TVerySimpleLua.RegisterPackage(PackageName: String; AObject: TObject);
begin
RegisterPackage(LuaState, PackageName, AObject);
end;
class procedure TVerySimpleLua.RegisterPackage(L: lua_State; PackageName: String; AObject: TObject;
PackageLoader: String);
var
LContext: TRttiContext;
LType: TRttiType;
LMethod: TRttiMethod;
Address: Pointer;
begin
LContext := TRttiContext.Create;
try
LType := LContext.GetType(AObject.ClassType);
LMethod := LType.GetMethod(PackageLoader);
Address := LMethod.CodeAddress;
RegisterPackage(L, AObject, Address, PackageName);
finally
LContext.Free;
end;
end;
procedure TVerySimpleLua.RegisterPackage(PackageName: String; AObject: TObject; PackageLoader: String);
begin
RegisterPackage(LuaState, PackageName, AObject, PackageLoader);
end;
(*
** Dynamic library manipulation
*)
function GetAddress(Name: String): Pointer;
begin
Result := GetProcAddress(LibraryHandle, PWideChar(Name));
if not Assigned(Result) then
raise ELuaLibraryMethodNotFound.Create('Entry point "' + QuotedStr(Name) + '" not found');
end;
function TVerySimpleLua.LoadFile(Filename: String): Integer;
var
Marshall: TMarshaller;
begin
Result := lual_loadfile(LuaState, Marshall.AsAnsi(Filename).ToPointer);
end;
class procedure TVerySimpleLua.LoadLuaLibrary(const LibraryPath: String);
var
LoadPath: String;
begin
FreeLuaLibrary;
if LibraryPath = '' then
LoadPath := LUA_LIBRARY
else
LoadPath := LibraryPath;
//LoadPath := ExtractFilePath(ParamStr(0)) + LUA_LIBRARY;
{$IFNDEF STATICLIBRARY}
// check if Library exists
if not FileExists(LoadPath) then
raise ELuaLibraryNotFound.Create('Lua library "' + QuotedStr(LoadPath) + '" not found');
// try to load the library
LibraryHandle := LoadLibrary(PChar(LoadPath));
if LibraryHandle = 0 then
raise ELuaLibraryLoadError.Create('Failed to load Lua library "' + QuotedStr(LoadPath) + '"'
{$IF defined(POSIX)} + (String(dlerror)){$ENDIF});
lua_newstate := GetAddress('lua_newstate');
lua_close := GetAddress('lua_close');
lua_newthread := GetAddress('lua_newthread');
lua_atpanic := GetAddress('lua_atpanic');
lua_version := GetAddress('lua_version');
lua_absindex := GetAddress('lua_absindex');
lua_gettop := GetAddress('lua_gettop');
lua_settop := GetAddress('lua_settop');
lua_pushvalue := GetAddress('lua_pushvalue');
lua_rotate := GetAddress('lua_rotate');
lua_copy := GetAddress('lua_copy');
lua_checkstack := GetAddress('lua_checkstack');
lua_xmove := GetAddress('lua_xmove');
lua_isnumber := GetAddress('lua_isnumber');
lua_isstring := GetAddress('lua_isstring');
lua_iscfunction := GetAddress('lua_iscfunction');
lua_isinteger := GetAddress('lua_isinteger');
lua_isuserdata := GetAddress('lua_isuserdata');
lua_type := GetAddress('lua_type');
lua_typename := GetAddress('lua_typename');
lua_tonumberx := GetAddress('lua_tonumberx');
lua_tointegerx := GetAddress('lua_tointegerx');
lua_toboolean := GetAddress('lua_toboolean');
lua_tolstring := GetAddress('lua_tolstring');
lua_rawlen := GetAddress('lua_rawlen');
lua_tocfunction := GetAddress('lua_tocfunction');
lua_touserdata := GetAddress('lua_touserdata');
lua_tothread := GetAddress('lua_tothread');
lua_topointer := GetAddress('lua_topointer');
lua_arith := GetAddress('lua_arith');
lua_rawequal := GetAddress('lua_rawequal');
lua_compare := GetAddress('lua_compare');
lua_pushnil := GetAddress('lua_pushnil');
lua_pushnumber := GetAddress('lua_pushnumber');
lua_pushinteger := GetAddress('lua_pushinteger');
lua_pushlstring := GetAddress('lua_pushlstring');
lua_pushstring := GetAddress('lua_pushstring');
lua_pushvfstring := GetAddress('lua_pushvfstring');
lua_pushfstring := GetAddress('lua_pushfstring');
lua_pushcclosure := GetAddress('lua_pushcclosure');
lua_pushboolean := GetAddress('lua_pushboolean');
lua_pushlightuserdata := GetAddress('lua_pushlightuserdata');
lua_pushthread := GetAddress('lua_pushthread');
lua_getglobal := GetAddress('lua_getglobal');
lua_gettable := GetAddress('lua_gettable');
lua_getfield := GetAddress('lua_getfield');
lua_geti := GetAddress('lua_geti');
lua_rawget := GetAddress('lua_rawget');
lua_rawgeti := GetAddress('lua_rawgeti');
lua_rawgetp := GetAddress('lua_rawgetp');
lua_createtable := GetAddress('lua_createtable');
lua_newuserdata := GetAddress('lua_newuserdata');
lua_getmetatable := GetAddress('lua_getmetatable');
lua_getuservalue := GetAddress('lua_getuservalue');
lua_setglobal := GetAddress('lua_setglobal');
lua_settable := GetAddress('lua_settable');
lua_setfield := GetAddress('lua_setfield');
lua_seti := GetAddress('lua_seti');
lua_rawset := GetAddress('lua_rawset');
lua_rawseti := GetAddress('lua_rawseti');
lua_rawsetp := GetAddress('lua_rawsetp');
lua_setmetatable := GetAddress('lua_setmetatable');
lua_setuservalue := GetAddress('lua_setuservalue');
lua_callk := GetAddress('lua_callk');
lua_pcallk := GetAddress('lua_pcallk');
lua_load := GetAddress('lua_load');
lua_dump := GetAddress('lua_dump');
lua_yieldk := GetAddress('lua_yieldk');
lua_resume := GetAddress('lua_resume');
lua_status := GetAddress('lua_status');
lua_isyieldable := GetAddress('lua_isyieldable');
lua_gc := GetAddress('lua_gc');
lua_error := GetAddress('lua_error');
lua_next := GetAddress('lua_next');
lua_concat := GetAddress('lua_concat');
lua_len := GetAddress('lua_len');
lua_stringtonumber := GetAddress('lua_stringtonumber');
lua_getallocf := GetAddress('lua_getallocf');
lua_setallocf := GetAddress('lua_setallocf');
lua_getstack := GetAddress('lua_getstack');
lua_getinfo := GetAddress('lua_getinfo');
lua_getlocal := GetAddress('lua_getlocal');
lua_setlocal := GetAddress('lua_setlocal');
lua_getupvalue := GetAddress('lua_getupvalue');
lua_setupvalue := GetAddress('lua_setupvalue');
lua_upvalueid := GetAddress('lua_upvalueid');
lua_upvaluejoin := GetAddress('lua_upvaluejoin');
lua_sethook := GetAddress('lua_sethook');
lua_gethook := GetAddress('lua_gethook');
lua_gethookmask := GetAddress('lua_gethookmask');
lua_gethookcount := GetAddress('lua_gethookcount');
luaopen_base := GetAddress('luaopen_base');
luaopen_coroutine := GetAddress('luaopen_coroutine');
luaopen_table := GetAddress('luaopen_table');
luaopen_io := GetAddress('luaopen_io');
luaopen_os := GetAddress('luaopen_os');
luaopen_string := GetAddress('luaopen_string');
luaopen_utf8 := GetAddress('luaopen_utf8');
luaopen_bit32 := GetAddress('luaopen_bit32');
luaopen_math := GetAddress('luaopen_math');
luaopen_debug := GetAddress('luaopen_debug');
luaopen_package := GetAddress('luaopen_package');
luaL_openlibs := GetAddress('luaL_openlibs');
luaL_checkversion_ := GetAddress('luaL_checkversion_');
luaL_getmetafield := GetAddress('luaL_getmetafield');
luaL_callmeta := GetAddress('luaL_callmeta');
luaL_tolstring := GetAddress('luaL_tolstring');
luaL_argerror := GetAddress('luaL_argerror');
luaL_checklstring := GetAddress('luaL_checklstring');
luaL_optlstring := GetAddress('luaL_optlstring');
luaL_checknumber := GetAddress('luaL_checknumber');
luaL_optnumber := GetAddress('luaL_optnumber');
luaL_checkinteger := GetAddress('luaL_checkinteger');
luaL_optinteger := GetAddress('luaL_optinteger');
luaL_checkstack := GetAddress('luaL_checkstack');
luaL_checktype := GetAddress('luaL_checktype');
luaL_checkany := GetAddress('luaL_checkany');
luaL_newmetatable := GetAddress('luaL_newmetatable');
luaL_setmetatable := GetAddress('luaL_setmetatable');
luaL_testudata := GetAddress('luaL_testudata');
luaL_checkudata := GetAddress('luaL_checkudata');
luaL_where := GetAddress('luaL_where');
luaL_error := GetAddress('luaL_error');
luaL_checkoption := GetAddress('luaL_checkoption');
luaL_fileresult := GetAddress('luaL_fileresult');
luaL_execresult := GetAddress('luaL_execresult');
luaL_ref := GetAddress('luaL_ref');
luaL_unref := GetAddress('luaL_unref');
luaL_loadfilex := GetAddress('luaL_loadfilex');
luaL_loadbufferx := GetAddress('luaL_loadbufferx');
luaL_loadstring := GetAddress('luaL_loadstring');
luaL_newstate := GetAddress('luaL_newstate');
luaL_len := GetAddress('luaL_len');
luaL_gsub := GetAddress('luaL_gsub');
luaL_setfuncs := GetAddress('luaL_setfuncs');
luaL_getsubtable := GetAddress('luaL_getsubtable');
luaL_traceback := GetAddress('luaL_traceback');
luaL_requiref := GetAddress('luaL_requiref');
luaL_buffinit := GetAddress('luaL_buffinit');
luaL_prepbuffsize := GetAddress('luaL_prepbuffsize');
luaL_addlstring := GetAddress('luaL_addlstring');
luaL_addstring := GetAddress('luaL_addstring');
luaL_addvalue := GetAddress('luaL_addvalue');
luaL_pushresult := GetAddress('luaL_pushresult');
luaL_pushresultsize := GetAddress('luaL_pushresultsize');
luaL_buffinitsize := GetAddress('luaL_buffinitsize');
{$ENDIF}
end;
class function TVerySimpleLua.LuaLibraryLoaded: Boolean;
begin
Result := (LibraryHandle <> 0);
end;
procedure TVerySimpleLua.Open;
begin
if FOpened then
Exit;
FOpened := True;
// Load Lua Lib if not already done
if not LuaLibraryLoaded then
LoadLuaLibrary(LibraryPath);
// Open Library
LuaState := lual_newstate; // opens Lua
lual_openlibs(LuaState); // load all libs
// register all published functions
if FAutoRegister then
RegisterFunctions(Self);
end;
class procedure TVerySimpleLua.FreeLuaLibrary;
begin
if LibraryHandle <> 0 then
begin
FreeLibrary(LibraryHandle);
LibraryHandle := 0;
end;
end;
function TVerySimpleLua.Print(L: Lua_State): Integer;
var
N, I: Integer;
S: MarshaledAString;
Sz: size_t;
Msg: String;
begin
Msg := '';
N := lua_gettop(L); //* number of arguments */
lua_getglobal(L, 'tostring');
for I := 1 to N do
begin
lua_pushvalue(L, -1); //* function to be called */
lua_pushvalue(L, i); //* value to print */
lua_call(L, 1, 1);
S := lua_tolstring(L, -1, @Sz); //* get result */
if S = NIL then
begin
Result := luaL_error(L, '"tostring" must return a string to "print"',[]);
Exit;
end;
if I > 1 then
Msg := Msg + #9;
Msg := Msg + String(S);
lua_pop(L, 1); //* pop result */
end;
Result := 0;
DoPrint(Msg);
end;
initialization
LibraryHandle := 0;
finalization
if LibraryHandle <> 0 then
TVerySimpleLua.FreeLuaLibrary;
end.
|
{
Дано натур. число N. Определить кол-во 8 значных чисел,
у которых сумма цифр в цифровой записи числа меньше, чем N.
Если таких чисел нет, выводим НЕТ.
}
program _8digits;
function SumOfDigits (x: longint): integer;
var
rem,
sum: integer;
begin
sum := 0;
While X <> 0 Do
Begin
rem := X Mod 10;
inc (sum, rem);
X:=X Div 10;
End;
SumOfDigits := sum;
end;
var
n, count: integer;
i : longint;
begin
write ('Enter 1 <= n <= 72 : '); readln (n);
count := 0;
for i := 10000000 to 99999999 do
begin
if i mod 10000 = 0 then
writeln (i);
if SumOfDigits (i) < N then
inc(count);
end;
if count = 0 then
writeln('none')
else
writeln('count = ', count);
readln;
end.
|
unit Gerenciador.TorreHanoi;
interface
uses
Vcl.ExtCtrls, Vcl.Graphics, Desenha.Discos, Vcl.StdCtrls;
type
TTorreHanoi = class
strict private
PinoOrigem, PinoAuxiliar, PinoDestino: TDesenjaDiscos.TPino;
QuantidadeDiscos: Integer;
public
procedure DesenharDiscos(const AQuantidadeDiscos: Integer);
procedure Executar();
function VerificarSeOsDiscosForamCriados(): Boolean;
constructor Create(const APainelOrigem, APainelAuxiliar,
APainelDestino: TPanel);
end;
implementation
uses
Algoritmo.TorreDeHanoi, System.SysUtils;
{ TTorreHanoi }
constructor TTorreHanoi.Create(const APainelOrigem, APainelAuxiliar,
APainelDestino: TPanel);
begin
PinoOrigem.Painel := APainelOrigem;
PinoAuxiliar.Painel := APainelAuxiliar;
PinoDestino.Painel := APainelDestino;
end;
procedure TTorreHanoi.Executar;
var
Algoritmo: TAlgoritmo;
begin
TDesenjaDiscos.Apagar(PinoAuxiliar.Painel);
TDesenjaDiscos.Apagar(PinoDestino.Painel);
Algoritmo := TAlgoritmo.Create();
try
Algoritmo.Hanoi(QuantidadeDiscos, PinoOrigem, PinoDestino, PinoAuxiliar);
finally
FreeAndNil(Algoritmo);
end;
end;
function TTorreHanoi.VerificarSeOsDiscosForamCriados: Boolean;
begin
// Se o vetor estiver preenchido
// indica que já foi inicializado
Result := Length(PinoOrigem.Discos) > 0;
end;
procedure TTorreHanoi.DesenharDiscos( const AQuantidadeDiscos: Integer);
var
Indice: Integer;
Tamanho: Integer;
begin
TDesenjaDiscos.Apagar(PinoOrigem.Painel);
TDesenjaDiscos.Apagar(PinoDestino.Painel);
TDesenjaDiscos.Apagar(PinoAuxiliar.Painel);
Tamanho := 0;
QuantidadeDiscos := AQuantidadeDiscos;
SetLength(PinoOrigem.Discos, AQuantidadeDiscos);
for Indice := High(PinoOrigem.Discos) downto 0 do
begin
Inc(Tamanho);
PinoOrigem.Discos[Indice].Cor := Random(256 * 256 * 256);
// define as corres dos discos
PinoOrigem.Discos[Indice].Tamanho := Tamanho; // é um sequencial
end;
SetLength(PinoAuxiliar.Discos, 0);
SetLength(PinoDestino.Discos, 0);
TDesenjaDiscos.DesenharDiscos(PinoOrigem.Painel, PinoOrigem.Discos);
end;
end.
|
unit Core;
interface
uses System.SysUtils, Vcl.Graphics, System.Types, WinApi.GDIPApi, WinApi.GDIPOBJ;
const LINE_LEN = 8;
FIG_COUNT = 16;
type
TDirection = (dN, dNE, dE, dSE, dS, dSW, dW, dNW);
TFigType = (tPawn, tLKnight, tRKnight, tLBishop, tRBishop, tLRook, tRRook, tQueen, tKing);
TMoveResult = (mrProccess, mrShach, mrPat, mrMat, mrIllegal);
TMoveType = (mCover, mAttack, mCastlingShort, mCastlingLong, mUpgrade);
TPlayer = record
Name : string;
Color : byte;
Active : Boolean;
end;
PCell = ^TCell;
TCell = record
x,y : word;
Rect : TGPRectF;
Color : TGPColor;
end;
PFigure = ^TFigure;
TFigure = record
id : byte;
ch : AnsiChar;
FigType : TFigType;
Home : TDirection;
Color : byte; // index of a color array
CountMove : word;
Cell : PCell;
Dead : boolean;
end;
TField = array [0 .. LINE_LEN - 1, 0 .. LINE_LEN - 1] of PCell;
TAllFigures = array [0 .. FIG_COUNT * 2 - 1] of PFigure;
TFigures = array [0 .. FIG_COUNT - 1] of PFigure;
PMove = ^TMove;
TMove = record
Next : PMove;
MoveType : set of TMoveType;
Figure,
KCC_Figure : PFigure; // Used for Attacked, Castling Rook, Cover Figures;
FromCell,
ToCell : PCell;
Enabled : boolean;
end;
TMoveHistory = record
Reverse : Boolean;
Move : TMove
end;
TCallback = reference to procedure(Figure: PFigure);
var cntmoves : cardinal = 0;
selected_cell : PCell = nil;
choosen_figure : PFigure = nil;
player1, player2 : TPlayer;
is_reverse : boolean = false;
posible_moves : PMove = nil;
pic : TPicture;
pic_rect : TGPRectF;
procedure SetColor(id: byte; NewColor:TColor; alpha: byte);
function GetColor(id: byte): TColor;
{Return last move}
procedure Back();
procedure Render_Scene(width: integer);
procedure CreateChess(Width: integer);
function MoveFigure(Move : PMove): TMoveResult;
procedure UnMoveFigure(Move: PMove);
procedure ShowWayFor(Figure : PFigure);
function GetSelectedCell(gx,gy : integer): PCell;
function GetFigureAtCell(Cell : PCell) : PFigure;
function GetMoveAtCell(Cell : PCell; Source : PMove) : PMove;
function CellUnderAttack(Cell: PCell; By: TDirection;
Mode: byte; var CallBack: TCallBack): boolean;
function MoveToStr(Move: PMove): string;
function StrToMove(const NewPositions : string): TMove;
procedure ReversePlay();
function GetActivePlayer(): TPlayer;
procedure SetAcivePlayerTo(var Player: TPlayer);
function GetFigure(id: byte): PFigure;
function GetKilledFigures(): TAllFigures;
function FigureToStr(Figure: PFigure): string;
function StrToFigure(const Str: string): TFigure;
function StrToPlayer(const Str: string): TPlayer;
procedure ClearMoves(var Start : PMove);
function FindAllMoves(Figure : PFigure; CalcCastling,Disabling: Boolean) : PMove;overload;
function FindAllMoves(color: byte): PMove;overload;
procedure LoadGame(const FileName: string);
procedure SaveGame(const FileName: string);
procedure StopGame();
implementation
uses Classes;
var field : TField;
figures : TAllFigures;
colors : array[0..1] of TGPColor = (aclPurple, aclSilver);
mirror : array[0 .. 7] of integer = (7, 6, 5, 4, 3, 2, 1, 0);
move_history : array of TMoveHistory;
ihis : integer = 0;
Sep : set of AnsiChar = [',', ';'];
procedure SetColor(id: byte; NewColor:TColor; alpha: byte);
var r,g,b:byte;
begin
if id > 1 then
begin
Colors[0] := aclPurple;
Colors[1] := aclSilver
end
else begin
r := NewColor;
g := NewColor shr 8;
b := NewColor shr 16;
Colors[id] := (DWORD(b) or
(DWORD(g) shl 8) or
(DWORD(r) shl 16) or
(DWORD(alpha) shl 24))
end;
end;
function GetColor(id: byte): TColor;
var r,g,b: byte;
begin
r := Colors[id] shr 16;
g := Colors[id] shr 8;
b := Colors[id];
result := DWORD(r) or
(DWORD(g) shl 8) or
(DWORD(b) shl 16);
end;
// Returns the player who has to move figure now
function GetActivePlayer(): TPlayer;
begin
if Player1.Active and not Player2.Active then result := Player1
else if Player2.Active and not Player1.Active then result := Player2
else raise Exception.Create('INVALID PLAYER ACTIVE STATUS.');
end;
procedure SetAcivePlayerTo(var Player: TPlayer);
begin
Player.Active := true;
if Player.Color = Player1.Color then Player2.Active := false
else if Player.Color = Player2.Color then Player1.Active := false;
end;
function GetCell(x,y: word): PCell;inline;
begin
if (x in [0..LINE_LEN - 1]) and (y in [0..LINE_LEN - 1])
then result := Field[x,y]
else result := nil;
end;
procedure LoadGame(const FileName: string);
var i: integer;
List: TStringList;
F : TFigure;
PF : PFigure;
reverse: Boolean;
begin
ihis := 0;
List := TStringList.Create;
List.LoadFromFile(FileName);
i := 0;
Reverse := StrToBool(List.Strings[i]);
inc(i);
cntmoves := StrToInt(List.Strings[i]);
inc(i);
while i <= List.Count - 3 do
begin
F := StrToFigure(List.Strings[i]);
if (Reverse xor is_reverse)then
begin
F.Cell := GetCell(F.Cell.x, Mirror[F.Cell.y]);
if (F.Home = dN) then F.Home := dS else F.Home := dN;
end;
PF := GetFigure(F.id);
PF^ := F;
inc(i);
end;
Player1 := StrToPlayer(List.Strings[i]);
inc(i);
Player2 := StrToPlayer(List.Strings[i]);
List.Free;
end;
procedure SaveGame(const FileName: string);
var i: integer;
List: TStringList;
begin
List := TStringList.Create;
List.Append(BoolToStr(is_reverse));
List.Append(IntToStr(cntmoves));
for i := 0 to FIG_COUNT * 2 - 1 do
List.Append(FigureToStr(GetFigure(i)));
List.Append(Player1.Name + ',' + IntToStr(Player1.Color) + ',' + BoolToStr(Player1.Active) + ';');
List.Append(Player2.Name + ',' + IntToStr(Player2.Color) + ',' + BoolToStr(Player2.Active) + ';');
List.SaveToFile(FileName);
List.Free;
end;
procedure Back();
var cl,cl2: byte;
c: cardinal;
M: TMove;
begin
if ihis = 0 then exit;
cl := GetActivePlayer.Color;
c := cntmoves;
repeat
M := move_history[ihis].Move;
with move_history[ihis] do
if (Reverse xor is_reverse) then
begin
M.FromCell := GetCell(Move.FromCell.x, Mirror[Move.FromCell.y]);
M.ToCell := GetCell(Move.ToCell.x, Mirror[Move.ToCell.y]);
end;
UnMoveFigure(@M);
cl2 := move_history[ihis].Move.Figure.Color;
dec(ihis)
until (cl = cl2) or (ihis = 0);
if c = 1 then
begin
cntmoves := 0;
if Player1.Color = 1 then SetAcivePlayerTo(Player1) else SetAcivePlayerTo(Player2);
end
else cntmoves := c - 2;
end;
procedure AppendHistory(Move: PMove);
begin
inc(ihis);
if ihis mod 100 = 0 then
SetLength(move_history, length(move_history) + 100);
move_history[ihis].Move := Move^;
move_history[ihis].Move.Next := nil;
move_history[ihis].Reverse := is_reverse;
end;
function Prev(): TMoveHistory; inline;
begin
result := move_history[ihis];
end;
function GetKilledFigures(): TAllFigures;
var i : PFigure;
j : integer;
begin
FillChar(result, sizeof(result), 0);
j := 0;
for i in Figures do
begin
if i.Dead then
begin
Result[j] := i;
inc(j)
end;
end;
end;
function GetFigure(id: byte): PFigure;
begin
if id in [0..FIG_COUNT * 2 - 1] then result := Figures[id] else Result := nil;
end;
procedure ReversePlay();
var i: PFigure;
begin
for i in Figures do
begin
if i.Home = dN then i.Home := dS else i.Home := dN;
i.Cell := GetCell(i.Cell.x, Mirror[i.Cell.y]);
end;
is_reverse := not is_reverse;
end;
function StrToPlayer(const Str: string): TPlayer;
var i, param: integer;
s: string;
begin
s := '';
param := 1;
for i := 1 to length(Str) do
begin
if (AnsiChar(Str[i]) in Sep) then
begin
case param of
1: result.Name := s;
2: result.Color := StrToInt(s);
3: result.Active := StrToBool(s);
end;
s := '';
inc(param);
end
else s := s + Str[i];
end;
end;
function FigureToStr(Figure: PFigure): string;
begin
result := '';
result := result + IntToStr(Figure.id) + ',' +
Char(Figure.ch) + ',' +
IntToStr(ord(Figure.FigType)) + ',' +
IntToStr(ord(Figure.Home)) + ',' +
IntToStr(Figure.Color) + ',' +
IntToStr(Figure.CountMove) + ',' +
IntToStr(Figure.Cell.x) + ',' +
IntToStr(Figure.Cell.y) + ',' +
BoolToStr(Figure.Dead) + ';'
end;
function StrToFigure(const Str: string): TFigure;
var i,param,x,y: integer;
s : string;
begin
s := '';
x := 0;
param := 1;
for i := 1 to length(Str) do
begin
if (AnsiChar(Str[i]) in Sep) then
begin
case param of
1: result.id := StrToint(s);
2: result.ch := AnsiChar(s[1]);
3: result.FigType := TFigType(StrToInt(s));
4: result.Home := TDirection(StrToInt(s));
5: result.Color := StrToInt(s);
6: result.CountMove := StrToInt(s);
7: x := StrToInt(s);
8: begin
y := StrToInt(s);
result.Cell := GetCell(x,y);
end;
9: result.Dead := StrToBool(s);
end;
s := '';
inc(param)
end
else s := s + Str[i];
end;
end;
function MoveToStr(Move: PMove): string;
begin
result := '';
if not Assigned(Move.Figure) then exit();
result := result + IntToStr(Move.Figure.id) + ',' +
BoolToStr(Move.Figure.Dead) + ',' +
IntToStr(Move.FromCell.x) + ',' +
IntToStr(Move.FromCell.y) + ',' +
IntToStr(Move.ToCell.x) + ',' +
IntToStr(Move.ToCell.y) + ',' +
IntToStr(PByte(@Move.MoveType)^) + ',';
if Assigned(Move.KCC_Figure)
then result := result + IntToStr(Move.KCC_Figure.id) + ','
else result := result + '-1,';
result := result + BoolToStr(is_reverse) + ';';
end;
function CreateMove():PMove;
begin
result := AllocMem(sizeof(TMove));
result.MoveType := [];
result.Enabled := true;
end;
function GetFigureAtCell(Cell : PCell) : PFigure;
var i : PFigure;
begin
Result := nil;
if not Assigned(Cell) then exit();
for i in Figures do
if (not i.Dead) and (i.Cell = Cell) then exit(i)
end;
function StrToMove(const NewPositions : string): TMove;
var i, param, xf, yf, xt, yt: word;
s: string;
OponentPlayReverse: boolean;
p : PMove;
begin
p := CreateMove();
result := p^;
param := 1;
s := '';
xf := 0; yf := 0; xt := 0; yt := 0;
for i := 1 to Length(NewPositions) do
begin
if AnsiChar(NewPositions[i]) in Sep then
begin
case param of
1: result.Figure := Figures[StrToInt(s)];
2: result.Figure.Dead := StrToBool(s);
3: xf := StrToInt(s);
4: yf := StrToint(s);
5: xt := StrToInt(s);
6: yt := StrToint(s);
7: PByte(@result.MoveType)^ := StrToInt(s);
8: result.KCC_Figure := GetFigure(StrToInt(s));
9: begin
OponentPlayReverse := StrToBool(s);
if OponentPlayReverse xor is_reverse then
begin
yf := Mirror[yf];
yt := Mirror[yt];
end;
result.ToCell := GetCell(xt,yt);
result.FromCell := GetCell(xf, yf);
param := 0;
end;
end;
s := '';
inc(param);
end
else if AnsiChar(NewPositions[i]) in ['0'..'9'] then
s := s + NewPositions[i];
end;
FreeMem(p);
end;
procedure ClearMoves(var Start : PMove);
var Node : PMove;
begin
Node := Start;
while Node <> nil do
begin
FreeMem(Node);
Node := Node.Next;
end;
Start := nil;
end;
function GetSelectedCell(gx,gy : integer): PCell;
var i: PCell;
begin
result := nil;
for i in Field do
with i.Rect do
begin
if (gx >= X) and (gx <= X + Width) and
(gy >= Y) and (gy <= Y + Height) then
begin
result := i;
selected_cell := result;
exit(result);
end;
end;
end;
function GetMoveAtCell(Cell : PCell; Source : PMove) : PMove;
var Node : PMove;
begin
result := nil;
Node := Source;
while Node <> nil do
begin
if (Node.ToCell = Cell) then exit(Node);
Node := Node.Next;
end;
end;
function GetNextCell(d: TDirection; out x, y: word; knight: boolean = false): PCell;
begin
case d of
dN: if knight then begin dec(y, 2); dec(x) end else dec(y);
dNE: if knight then begin dec(y, 2); inc(x) end else begin dec(y); inc(x) end;
dE: if knight then begin dec(y); inc(x, 2) end else inc(x);
dSE: if knight then begin inc(y); inc(x, 2) end else begin inc(y); inc(x) end;
dS: if knight then begin inc(y, 2); inc(x) end else inc(y);
dSW: if knight then begin inc(y, 2); dec(x) end else begin inc(y); dec(x) end;
dW: if knight then begin inc(y); dec(x, 2) end else dec(x);
dNW: if knight then begin dec(y); dec(x, 2) end else begin dec(y); dec(x) end;
end;
result := GetCell(x, y);
end;
function FindWayForPawn(Direction: TDirection; Figure : PFigure) : PMove;
var i,x,y : word;
Node, ParentNode : PMove;
Cell : PCell;
F : PFigure;
Last : TMoveHistory;
procedure NewMove;
begin
Node := CreateMove();
if Assigned(ParentNode) then ParentNode.Next := Node;
Node.Figure := Figure;
Node.FromCell := GetCell(Figure.Cell.x, Figure.Cell.y);
Node.ToCell := Cell;
ParentNode := Node;
if (F <> nil) then
begin
Node.KCC_Figure := F;
if (Node.Figure.Home = F.Home)
then include(Node.MoveType, mCover)
else include(Node.MoveType, mAttack);
end;
if (byte(Node.ToCell.y) in [0, 7]) then include(Node.MoveType, mUpgrade);
if not Assigned(result) then result := Node;
end;
begin
result := nil; ParentNode := nil; F := nil;
x := Figure.Cell.x; y := Figure.Cell.y;
case Direction of
dN, dS : for i := 1 to 2 do
begin
if (Direction = Figure.Home) then exit;
Cell := GetNextCell(Direction, x, y);
if (i < 2) or ((Figure.CountMove = 0) and (i = 2)) then
begin
if Assigned(GetFigureAtCell(Cell)) then exit;
NewMove();
end;
end;
dE, dW : begin
Cell := GetNextCell(Direction, x, y);
F := GetFigureAtCell(Cell);
Last := Prev();
with Last.Move do
if (F = nil) or (F <> Figure) or (Figure.FigType <> tPawn) or
(abs(FromCell.y - ToCell.y) <> 2) then exit();
NewMove;
end;
dSW,dSE, dNE, dNW:
begin
if ((Figure.Home = dN) and (Direction in [dNE, dNW])) or
((Figure.Home = dS) and (Direction in [dSE, dSW])) then exit;
Cell := GetNextCell(Direction, x,y);
F := GetFigureAtCell(Cell);
if (F <> nil) then
begin
NewMove();
Result.KCC_Figure := F;
if (result.Figure.Home = F.Home)
then include(result.MoveType, mCover)
else include(Result.MoveType, mAttack);
end;
end;
end;
end;
function FindWayForKnight(Direction : TDirection; Figure : PFigure) : PMove;
var x,y : word;
Cell : PCell;
F : PFigure;
begin
result := nil;
x := Figure.Cell.x;
y := Figure.Cell.y;
Cell := GetNextCell(Direction, x, y, true);
if Assigned(Cell) then
begin
result := CreateMove();
result.Figure := Figure;
result.FromCell := GetCell(Figure.Cell.x, Figure.Cell.y);
result.ToCell := Cell;
F := GetFigureAtCell(Cell);
if (F <> nil) then
begin
Result.KCC_Figure := F;
if (result.Figure.Home = F.Home)
then include(result.MoveType, mCover)
else include(Result.MoveType, mAttack);
end;
end;
end;
function FindWayForRook(Direction : TDirection; Figure : PFigure; lim : byte = 255) : PMove;
var x,y : word;
Node, ParentNode : PMove;
F : PFigure;
Cell : PCell;
begin
result := nil;
if not (Direction in [dN, dS, dE, dW]) then exit;
ParentNode := nil; F := nil;
x := Figure.Cell.x;
y := Figure.Cell.y;
Cell := GetNextCell(Direction, x, y);
while Assigned(Cell) and (F = nil) and (lim > 0) do
begin
F := GetFigureAtCell(Cell);
Node := CreateMove();
if Assigned(ParentNode) then ParentNode.Next := Node;
Node.Figure := Figure;
Node.FromCell := GetCell(Figure.Cell.x, Figure.Cell.y);
Node.ToCell := Cell;
ParentNode := Node;
if (F <> nil) then
begin
Node.KCC_Figure := F;
if (Node.Figure.Home = F.Home)
then include(Node.MoveType, mCover)
else include(Node.MoveType, mAttack);
end;
if not Assigned(result) then result := Node;
Cell := GetNextCell(Direction, x, y);
dec(lim);
end;
end;
function FindWayForBishop(Direction : TDirection; Figure : PFigure; lim : byte = 255) : PMove;
var x,y : word;
Node, ParentNode : PMove;
F : PFigure;
Cell : PCell;
begin
result := nil;
if (Direction in [dN, dS, dE, dW]) then exit;
ParentNode := nil; F := nil;
x := Figure.Cell.x;
y := Figure.Cell.y;
Cell := GetNextCell(Direction, x, y);
while Assigned(Cell) and (F = nil) and (lim > 0) do
begin
F := GetFigureAtCell(Cell);
Node := CreateMove();
if Assigned(ParentNode) then ParentNode.Next := Node;
Node.Figure := Figure;
Node.FromCell := GetCell(Figure.Cell.x, Figure.Cell.y);
Node.ToCell := Cell;
ParentNode := Node;
if (F <> nil) then
begin
Node.KCC_Figure := F;
if (Node.Figure.Home = F.Home)
then include(Node.MoveType, mCover)
else include(Node.MoveType, mAttack);
end;
if not Assigned(result) then result := Node;
Cell := GetNextCell(Direction, x, y);
dec(lim);
end;
end;
function FindWayForQueen(Direction : TDirection; Figure : PFigure) : PMove;
begin
if Direction in [dN, dE, dS, dW] then
result := FindWayForRook(Direction, Figure)
else
result := FindWayForBishop(Direction, Figure);
end;
function CastlingEnabled(Direction: TDirection; King : PFigure): boolean;
var x,y : word;
Rook, Figure: PFigure;
NextCell : PCell;
op: TDirection;
c: TCallBack;
begin
c := nil;
result := false;
if Direction = dE
then Rook := Figures[King.Color * FIG_COUNT + 3]
else Rook := Figures[King.Color * FIG_COUNT + 2];
if (King.CountMove > 0) or (Rook.CountMove > 0) then exit;
x := King.Cell.x;
y := King.Cell.y;
op := TDirection(abs(ord(King.Home) + -4));
NextCell := GetCell(x, y);
repeat
if CellUnderAttack(NextCell, op, 0, c) then exit;
if Direction = dE then inc(x) else dec(x);
NextCell := GetCell(x, y);
Figure := GetFigureAtCell(NextCell);
result := Assigned(Figure) and (Figure = Rook);
until (NextCell = nil) or (Figure <> nil);
end;
function FindWayForKing(Direction : TDirection; Figure : PFigure; CalcCastling: boolean) : PMove;
var p : PMove;
begin
if Direction in [dN, dE, dS, dW] then
begin
if CalcCastling and
(Direction in [dE, dW]) and
CastlingEnabled(Direction, Figure) then
begin
result := FindWayForRook(Direction, Figure, 2);
if (result = nil) or (Result.Next = nil) then exit;
p := Result.Next;
if (p.ToCell.x - p.FromCell.x > 1) then
begin
include(p.MoveType, mCastlingShort);
p.KCC_Figure := Figures[p.Figure.Color * FIG_COUNT + 3];
end;
if (p.ToCell.x - p.FromCell.x < -1) then
begin
include(p.MoveType, mCastlingLong);
p.KCC_Figure := Figures[p.Figure.Color * FIG_COUNT + 2];
end;
end
else result := FindWayForRook(Direction, Figure, 1)
end
else result := FindWayForBishop(Direction, Figure, 1);
end;
procedure DisableMoves(Moves: Pmove; King: PFigure);
var Node : PMove;
Cell : PCell;
op : TDirection;
c: TCallBack;
begin
if Moves = nil then exit;
c := nil;
op := TDirection(abs(ord(King.Home) + -4));
Node := Moves;
while (Node <> nil) do
begin
if not (mCover in Node.MoveType) then
begin
Cell := Node.Figure.Cell;
Node.Figure.Cell := Node.ToCell;
if mAttack in Node.MoveType then Node.KCC_Figure.Dead := true;
Node.Enabled := not CellUnderAttack(King.Cell, op, 0, c);
if mAttack in Node.MoveType then Node.KCC_Figure.Dead := false;
Node.Figure.Cell := Cell;
end;
Node := Node.Next;
end;
end;
function FindAllMoves(Figure : PFigure; CalcCastling,Disabling: Boolean) : PMove;overload;
var d : TDirection;
Node, Last : PMove;
begin
result := nil;
Last := nil;
if Assigned(Figure) and not Figure.Dead then
begin
for d := dN to dNW do
begin
case Figure.FigType of
tPawn : Node := FindWayForPawn(d, Figure);
tLKnight, tRKnight : Node := FindWayForKnight(d, Figure);
tLRook, tRRook : Node := FindWayForRook(d, Figure);
tLBishop, tRBishop : Node := FindWayForBishop(d, Figure);
tQueen : Node := FindWayForQueen(d, Figure);
tKing : Node := FindWayForKing(d, Figure, CalcCastling);
else Node := nil;
end;
if Assigned(Node) then
begin
if result = nil then result := Node else Last.Next := Node;
Last := Node;
while Assigned(Last.Next) do Last := Last.Next;
end;
end;
if (result <> nil) and (Disabling) then
DisableMoves(result, Figures[result.Figure.Color * FIG_COUNT]);
end;
end;
function FindAllMoves(color: byte): PMove;overload;
var i: integer;
Node, Last: PMove;
begin
result := nil;
Last := nil;
for i := color * FIG_COUNT to color * FIG_COUNT + 15 do
begin
Node := FindAllMoves(Figures[i], true, true);
if Assigned(Node) then
begin
if result = nil then result := Node else Last.Next := Node;
Last := Node;
while Assigned(Last.Next) do Last := Last.Next;
end;
end;
end;
function DetectDirection(FromCell, ToCell: PCell): TDirection;
var f: integer;
const q:single = 180;
asm
{ALGORITHM:
f := trunc(arctan2(ToCell.y - FromCell.y,
ToCell.x - FromCell.x) * 180 / pi);
case f of
-90: result := dN;
90: result := dS;
-89..-1: result := dNE;
0: result := dE;
1..89: result := dSE;
91..179: result := dSW;
180: result := dW;
else result := dNW;
end;}
MOV EAX, dword ptr [EAX]
MOV EDX, dword ptr [EDX]
SUB DX, AX
ROR EDX, 16
ROR EAX, 16
SUB DX, AX
MOV f, EDX
FILD word ptr [f]
FILD word ptr [f + $02]
FPATAN
FMUL q
FLDPI
FDIV
FISTP f
WAIT
MOV EAX, f
TEST EAX, EAX
JL @lower
JG @greate
MOV result, dE // 0
JMP @exit
@greate: // 1..89
CMP EAX, 89
JG @next1
MOV result, dSE
JMP @exit
@next1: // 90
CMP EAX, 90
JG @next2
MOV result, &dS
JMP @exit
@next2: // 91..179
CMP EAX, 179
JG @next3
MOV result, dSW
JMP @exit
@next3: // 180
MOV result, &dW
JMP @exit
@lower: // -89..-1
CMP EAX, -89
JL @next4
MOV result, dNE
JMP @exit
@next4: // -90
CMP EAX, -90
JL @next5
MOV result, dN
JMP @exit
@next5: // -179..-91
MOV result, dNW
@exit:
end;
procedure Swap(var p1, p2: cardinal);inline;
begin
p1 := p1 xor p2;
p2 := p2 xor p1;
p1 := p1 xor p2;
end;
// mode = 0 -- Attack; mode = 1 -- cover
function CellUnderAttack(Cell: PCell; By: TDirection; Mode: byte; var CallBack: TCallBack): boolean;
var d : TDirection;
x,y, kx, ky : word;
dist,i : word;
NextCell : PCell;
Figure : PFigure;
r : boolean;
begin
r := false;
result := false;
if Cell = nil then exit;
for d := dN to dNW do
begin
dist := 0; x := Cell.x; y := Cell.y; kx := x; ky := y;
repeat
inc(dist);
for i := 0 to 1 do // One cycle for Knight and one for others
begin
if i = 0
then NextCell := GetNextCell(d, kx, ky, true)
else NextCell := GetNextCell(d, x, y);
Figure := GetFigureAtCell(NextCell);
if (Assigned(Figure) and (Figure.Home = By)) then
begin
case Figure.FigType of
tKing : r := (i = 1) and (dist = 1);
tQueen : r := (i = 1);
tLKnight, tRKnight: r := (i = 0) and (dist = 1);
tLRook, tRRook : r := (i = 1) and (d in [dN, dE, dS, dW]);
tLBishop,tRBishop : r := (i = 1) and not(d in [dN, dE, dS, dW]);
tPawn :
if (i = 1) and
(((Figure.Home = dN) and (y < Cell.y)) or
((Figure.Home = dS) and (y > Cell.y))) then
begin
if mode = 0 then
r := (dist = 1) and (Cell.x <> x)
else begin
if (Cell.x <> x) then
r := (dist = 1) and Assigned(GetFigureAtCell(Cell))
else
r := ((dist = 1) or ((dist = 2) and (Figure.CountMove = 0)));
end
end
end;
if r then
begin
result := true;
if Assigned(CallBack) then CallBack(Figure);
if not Assigned(CallBack) then exit; // Withot elseif because we need to exit when CallBack find result
end;
r := false;
end;
end;
until (NextCell = nil) or (Figure <> nil);
end;
end;
function Escape(King: PFigure): boolean;
var d,op: TDirection;
x,y: word;
NextCell: PCell;
F: PFigure;
c: TCallBack;
begin
result := false;
c := nil;
op := TDirection(abs(ord(King.Home) + -4));
for d := dN to dNW do
begin
x := King.Cell.x; y := King.Cell.y;
NextCell := GetNextCell(d, x, y);
F := GetFigureAtCell(NextCell);
if Assigned(F) and (f.Home = King.Home) then Continue;
if Assigned(NextCell) then
begin
Swap(cardinal(King.Cell), cardinal(NextCell));
result := not CellUnderAttack(King.Cell, op, 0, c);
Swap(cardinal(King.Cell), cardinal(NextCell));
if result then exit;
end;
end;
end;
function DefeatThreat(Attacker, King: PFigure): boolean;
var op:TDirection;
p: TCallBack;
r: boolean;
begin
r := false;
p := procedure (Figure:PFigure)
var c: TCallBack;
begin
c := nil;
op := TDirection(abs(ord(King.Home) + -4));
Swap(cardinal(Figure.Cell), cardinal(Attacker.Cell));
Attacker.Dead := true;
r := not CellUnderAttack(King.Cell, op, 0, c);
Attacker.Dead := false;
Swap(cardinal(Figure.Cell), cardinal(Attacker.Cell));
if r then p := nil;
end;
result := CellUnderAttack(Attacker.Cell, King.Home, 0, p) and r;
end;
function Cover(Attacker, King: PFigure): boolean;
var x,y : word;
op,d : TDirection;
NextCell : PCell;
r : boolean;
p : TCallBack;
begin
result := false;
if (Attacker = nil) or (Attacker.FigType in [tLKnight, tRKnight]) then exit;
r := false;
x := King.Cell.x; y := King.Cell.y;
op := TDirection(abs(ord(King.Home) + -4));
d := DetectDirection(King.Cell, Attacker.Cell); // Detect attack direction
p := procedure (Figure: PFigure)
var c: TCallBack;
begin
Swap(cardinal(Figure.Cell), cardinal(NextCell));
c := nil;
r := not CellUnderAttack(King.Cell, op, 0, c);
Swap(cardinal(Figure.Cell), cardinal(NextCell));
if r then p := nil;
end;
repeat
NextCell := GetNextCell(d, x, y);
result := CellUnderAttack(NextCell, King.Home, 1, p) and r;
until result or (NextCell = nil) or (NextCell = Attacker.Cell);
end;
function Shakh(King : PFigure): TMoveResult;
var res: boolean;
op : TDirection;
p : TCallBack;
r : TMoveResult;
function Pat(): boolean;
var i: integer;
PosibleMoves,t1 : PMove;
begin
result := true;
for i := King.Color * FIG_COUNT to King.Color * FIG_COUNT + 15 do
begin
if Figures[i].Dead then Continue;
t1 := FindAllMoves(Figures[i], false, true);
PosibleMoves := t1;
while PosibleMoves <> nil do
begin
if not (mCover in PosibleMoves.MoveType) and PosibleMoves.Enabled then
begin
ClearMoves(t1);
exit(false)
end;
PosibleMoves := PosibleMoves.Next;
end;
ClearMoves(t1);
end;
end;
begin
r := mrProccess;
op := TDirection(abs(ord(King.Home) + -4));
p := procedure(Figure:PFigure)
begin
r := mrShach;
res := Escape(King);
if not res then res := DefeatThreat(Figure, King);
if not res then res := Cover(Figure, King);
if res then p := nil;
end;
if CellUnderAttack(King.Cell, op, 0, p) then
begin
if not res then exit(mrMat);
end
else if Pat() then exit(mrPat);
result := r;
end;
procedure UnMoveFigure(Move: PMove);
begin
Move.Figure.Cell := Move.FromCell;
if mAttack in Move.MoveType then Move.KCC_Figure.Dead := false;
if mUpgrade in Move.MoveType then
begin
Move.Figure.FigType := tPawn;
Move.Figure.ch := '#';
end;
// If King Make Castling, Unmove a Rook too
if (mCastlingShort in Move.MoveType)
then Move.KCC_Figure.Cell := GetCell(LINE_LEN - 1, Move.Figure.Cell.y)
else if (mCastlingLong in Move.MoveType)
then Move.KCC_Figure.Cell := GetCell(0, Move.Figure.Cell.y);
dec(Move.Figure.CountMove);
dec(cntmoves);
end;
function MoveFigure(Move : PMove): TMoveResult;
begin
result := mrIllegal;
if (mCover in Move.MoveType) or not Move.Enabled then exit;
if mAttack in Move.MoveType then Move.KCC_Figure.Dead := true;
if mUpgrade in Move.MoveType then
begin
Move.Figure.ch := '3';
Move.Figure.FigType := tQueen;
end;
Move.Figure.Cell := Move.ToCell;
inc(Move.Figure.CountMove);
// If King Make Castling, Move a Rook too
if (mCastlingShort in Move.MoveType) then
begin
Move.KCC_Figure.Cell := GetCell(Move.ToCell.x - 1, Move.ToCell.y)
end
else if (mCastlingLong in Move.MoveType) then
begin
Move.KCC_Figure.Cell := GetCell(Move.ToCell.x + 1, Move.ToCell.y)
end;
if (Move.Figure.FigType = tPawn) then
begin
if (mUpgrade in Move.MoveType) then Move.Figure.FigType := tQueen;
// If beat the pawn which jumped
if (Move.FromCell.y - Move.ToCell.y = 0) then
begin
if Move.Figure.Home = dN
then Move.ToCell := GetCell(Move.ToCell.x, Move.ToCell.y + 1)
else Move.ToCell := GetCell(Move.ToCell.x, Move.ToCell.y - 1);
Move.Figure.Cell := Move.ToCell;
end;
end;
AppendHistory(Move);
result := Shakh(Figures[abs(Move.Figure.Color + -1) * FIG_COUNT]);
inc(cntmoves);
end;
procedure ShowWayFor(Figure : PFigure);
begin
if Assigned(Figure) then
begin
ClearMoves(posible_moves);
posible_moves := FindAllMoves(Figure, true, true);
end;
end;
procedure FreeChess();
var i : PCell;
j : PFigure;
begin
for i in Field do FreeMem(i);
for j in Figures do FreeMem(j);
ClearMoves(posible_moves);
end;
procedure Create_Figures();
var i : integer;
begin
for i := 0 to FIG_COUNT * 2 - 1 do
begin
Figures[i] := AllocMem(sizeof(TFigure));
Figures[i].CountMove := 0;
Figures[i].Dead := false;
Figures[i].id := i;
case i of
00,16 : begin
Figures[i].ch := '7';
Figures[i].FigType := tKing;
case i of
00 : Figures[i].Cell := Field[4,0];
16 : Figures[i].Cell := Field[4,7];
end;
end;
01,17 : begin
Figures[i].ch := '3';
Figures[i].FigType := tQueen;
case i of
01 : Figures[i].Cell := Field[3,0];
17 : Figures[i].Cell := Field[3,7];
end;
end;
2,3,18,19 : begin
Figures[i].ch := '/';
if i in [2,18]
then Figures[i].FigType := tLRook
else Figures[i].FigType := tRRook;
case i of
02 : Figures[i].Cell := Field[0,0];
03 : Figures[i].Cell := Field[7,0];
18 : Figures[i].Cell := Field[0,7];
19 : Figures[i].Cell := Field[7,7];
end;
end;
4,5,20,21 : begin
Figures[i].ch := '''';
if i in [4,20]
then Figures[i].FigType := tLKnight
else Figures[i].FigType := tRKnight;
case i of
04 : Figures[i].Cell := Field[1,0];
05 : Figures[i].Cell := Field[6,0];
20 : Figures[i].Cell := Field[1,7];
21 : Figures[i].Cell := Field[6,7];
end;
end;
6,7,22,23 : begin
Figures[i].ch := '+';
if i in [6,22]
then Figures[i].FigType := tLBishop
else Figures[i].FigType := tRBishop;
case i of
06 : Figures[i].Cell := Field[2,0];
07 : Figures[i].Cell := Field[5,0];
22 : Figures[i].Cell := Field[2,7];
23 : Figures[i].Cell := Field[5,7];
end;
end;
else begin
Figures[i].ch := '#';
Figures[i].FigType := tPawn;
if i < 16
then Figures[i].Cell := Field[i and 7, 1]
else Figures[i].Cell := Field[i and 7, 6]
end;
end;
if i < FIG_COUNT then
begin
Figures[i].Home := dN;
Figures[i].Color := 0;
end
else begin
Figures[i].Home := dS;
Figures[i].Color := 1;
end;
end;
end;
procedure Create_Board(width : integer; Border: integer);
var i,j : word;
p,m : single;
l : boolean;
begin
p := (Width - border) / LINE_LEN;
m := border / 2;
l := true;
for i := 0 to LINE_LEN - 1 do
begin
for j := 0 to LINE_LEN - 1 do
begin
Field[i,j] := AllocMem(sizeof(TCell));
Field[i,j].x := i;
Field[i,j].y := j;
Field[i,j].Rect.X := i * p + m;
Field[i,j].Rect.Y := j * p + m;
Field[i,j].Rect.Width := p;
Field[i,j].Rect.Height := p;
case l of
false : if odd(j) then
Field[i, j].Color := aclWhite
else
Field[i, j].Color := aclBlack;
true : if odd(j) then
Field[i, j].Color := aclBlack
else
Field[i, j].Color := aclWhite;
end;
end;
l := not l;
end;
end;
procedure CreateChess(Width: integer);
begin
FreeChess;
cntmoves := 0;
is_reverse := false;
SetLength(move_history, 100);
ihis := 0;
Create_Board(Width, 40);
Create_Figures();
end;
procedure DrawArrow(Canvas: THandle);
var Gr : TGPGraphics;
Pen : TGPPen;
SB : TGPSolidBrush;
d: TDirection;
Last: TMoveHistory;
FR,TR: TGPRectF;
CF,CT: PCell;
Arrow: array[0..4] of TGPPointF;
c: TGPColor;
procedure Rotate(angle: single; PArrow:pointer);
const q:single = 180;
asm
{ALGORITHM:
angle := angle * pi / 180;
for i := 1 to 4 do
begin
len := Sqrt(sqr(points[i].X - points[0].X) + sqr(points[i].Y - points[0].Y));
at := ArcTan2(points[i].Y - points[0].Y, points[i].X - points[0].X);
SinCos(angle + at, s, c);
points[i].X := points[0].X + len * c;
points[i].Y := points[0].Y + len * s;
end; }
FLDPI
FMUL angle
FDIV q
MOV ECX, 4
@loop:
FLD dword ptr [EAX + ECX * 8] // x
FSUB dword ptr [EAX]
FMUL st(0), st(0)
FLD dword ptr [EAX + ECX * 8 + $04] // y
FSUB dword ptr [EAX + $04]
FMUL st(0), st(0)
FADDP
FSQRT
FLD dword ptr [EAX + ECX * 8 + $04]
FSUB dword ptr [EAX + $04]
FLD dword ptr [EAX + ECX * 8]
FSUB dword ptr [EAX]
FPATAN
FADD st(0), st(2)
FSINCOS // st 0 - cos; st 1 - sin st 2 len
FMUL st(0), st(2)
FXCH
FMUL st(0), st(2)
FXCH
FADD dword ptr [EAX]
FXCH
FADD dword ptr [EAX + $04]
FSTP dword ptr [EAX + ECX * 8 + $04]
FSTP dword ptr [EAX + ECX * 8]
FXCH
FFREE st(1)
DEC ECX
JNZ @loop;
FFREE st(0)
end;
procedure CreateDefaultArrow(FromRect, ToRect, PArrow: pointer);
var t: single;
const adx:single = 8;
ady:single = 10;
two: single = 2;
asm
FLD dword ptr [EAX + 8]
FDIV two
FSTP t
// length
FLD dword ptr [EDX]
FSUB dword ptr [EAX]
FMUL st(0), st(0)
FLD dword ptr [EDX + 4]
FSUB dword ptr [EAX + 4]
FMUL st(0), st(0)
FADD
FSQRT
FSUB t
// point 0 Arrow[0] := MakePoint(FR.X + FR.Width / 2, FR.Y + FR.Height / 2);
FLD dword ptr [EAX + 4] // y
FADD t
FLD dword ptr [EAX] // x
FADD t
FSTP dword ptr [ECX]
FSTP dword ptr [ECX + 4]
// point 1 Arrow[1] := MakePoint(Arrow[0].X - len, Arrow[0].Y);
FSUBR dword ptr [ECX] // x
FLD dword ptr [ECX + 4] // y
FSTP dword ptr [ECX + 8 + 4]
FST dword ptr [ECX + 8]
// point 2 Arrow[2] := MakePoint(Arrow[1].X - ay, Arrow[1].Y);
FSUB adx // x
FSUB adx
FLD dword ptr [ECX + 8 + 4] // y
FSTP dword ptr [ECX + 16 + 4]
FSTP dword ptr [ECX + 16]
// point 3 Arrow[3] := MakePoint(Arrow[1].X + ax, Arrow[1].Y - ay);
FLD dword ptr [ECX + 8]
FLD dword ptr [ECX + 8 + 4]
FSUB ady
FSTP dword ptr [ECX + 24 + 4]
FSTP dword ptr [ECX + 24]
// point 4 Arrow[4] := MakePoint(Arrow[1].X + ax, Arrow[1].Y + ay);
FLD dword ptr [ECX + 8]
FLD dword ptr [ECX + 8 + 4]
FADD ady
FSTP dword ptr [ECX + 32 + 4]
FSTP dword ptr [ECX + 32]
end;
begin
if ihis = 0 then exit;
c := cardinal(200 shl 24) or $000000FF;// MakeColor(200, 0, 0, 255);
Gr := TGPGraphics.Create(Canvas);
Pen := TGPPen.Create(c, 3);
SB := TGPSolidBrush.Create(c);
Gr.SetSmoothingMode(SmoothingModeHighQuality);
Last := Prev();
with Last.Move do
if (Last.Reverse xor is_reverse) then
begin
CF := GetCell(FromCell.x, Mirror[FromCell.y]);
CT := GetCell(ToCell.x, Mirror[ToCell.y]);
d := DetectDirection(CF, CT);
FR := CF.Rect;
TR := CT.Rect;
end
else begin
d := DetectDirection(FromCell, ToCell);
FR := FromCell.Rect;
TR := ToCell.Rect;
end;
CreateDefaultArrow(@FR, @TR, @Arrow[0]);
with Last.Move.Figure^ do
case d of
dN : Rotate(90, @Arrow[0]);
dNE : if FigType in [tLKnight, tRKnight] then
begin
if abs(Last.Move.FromCell.x - Last.Move.ToCell.x) = 2
then Rotate(150, @Arrow[0])
else Rotate(120, @Arrow[0])
end
else Rotate(135, @Arrow[0]);
dE : Rotate(180, @Arrow[0]);
dSE : if FigType in [tLKnight, tRKnight] then
begin
if abs(Last.Move.FromCell.x - Last.Move.ToCell.x) = 2
then Rotate(210, @Arrow[0])
else Rotate(240, @Arrow[0])
end
else Rotate(225, @Arrow[0]);
dS : Rotate(270, @Arrow[0]);
dSW : if FigType in [tLKnight, tRKnight] then
begin
if abs(Last.Move.FromCell.x - Last.Move.ToCell.x) = 2
then Rotate(330, @Arrow[0])
else Rotate(300, @Arrow[0])
end
else Rotate(315, @Arrow[0]);
dW : ;
dNW : if FigType in [tLKnight, tRKnight] then
begin
if abs(Last.move.FromCell.x - Last.Move.ToCell.x) = 2
then Rotate(25, @Arrow[0])
else Rotate(60, @Arrow[0])
end
else Rotate(45, @Arrow[0]);
end;
Gr.DrawLine(Pen, Arrow[0], Arrow[1]);
Gr.FillPolygon(SB, PGPPointF(@Arrow[2]), 3);
SB.Free;
Pen.Free;
Gr.Free;
end;
procedure DrawCells(Canvas: THandle; PosibleMoves: PMove);
var Gr: TGPGraphics;
Pen: TGPPen;
Node : PMove;
FigureAtCell : PFigure;
begin
Gr := TGPGraphics.Create(Canvas);
Pen := TGPPen.Create(aclRed, 2);
Node := PosibleMoves;
while Node <> nil do
begin
FigureAtCell := GetFigureAtCell(Node.ToCell);
if Node.Enabled then
begin
if Assigned(FigureAtCell) and (FigureAtCell.Home = Node.Figure.Home)
then Pen.SetColor(aclGreen)
else Pen.SetColor(aclRed);
Gr.DrawRectangle(Pen, Node.ToCell.Rect);
end;
Node := Node.Next;
end;
if Assigned(choosen_figure) then
begin
Pen.SetColor(aclRed);
Pen.SetWidth(2.5);
Gr.DrawRectangle(Pen, choosen_figure.Cell.Rect);
end;
if Assigned(selected_cell) then
begin
Pen.SetColor(aclAqua);
Gr.DrawRectangle(Pen, selected_cell.Rect);
end;
Pen.Free;
Gr.Free;
end;
procedure RenderFigures(Canvas: THandle);
var i : PFigure;
Gr: TGPGraphics;
SB: TGPSolidBrush;
Point: TGPPointF;
FISDiagram : TGPFont;
begin
Gr := TGPGraphics.Create(Canvas);
SB := TGPSolidBrush.Create(aclWhite);
FISDiagram := TGPFont.Create('ISDiagram', 32, 1);
Gr.SetSmoothingMode(SmoothingModeHighQuality);
for i in Figures do
begin
if i.Dead then Continue;
SB.SetColor(Colors[i.Color]);
Point.X := i.Cell.Rect.X;
Point.Y := i.Cell.Rect.Y + 5;
case i.FigType of
tPawn : Gr.DrawString(Char(i.ch), -1, FISDiagram, Point, SB);
tLKnight, tRKnight : Gr.DrawString(Char(i.ch), -1, FISDiagram, Point, SB);
tLBishop, tRBishop : Gr.DrawString(Char(i.ch), -1, FISDiagram, Point, SB);
tLRook, tRRook : Gr.DrawString(Char(i.ch), -1, FISDiagram, Point, SB);
tQueen : Gr.DrawString(Char(i.ch), -1, FISDiagram, Point, SB);
tKing : Gr.DrawString(Char(i.ch), -1, FISDiagram, Point, SB);
end;
end;
FISDiagram.Free;
SB.Free;
Gr.Free;
end;
function InverseColor(Color:TGPColor):TGPColor;
begin
case Color of
aclWhite: result := aclBlack;
aclBlack: result := aclWhite;
else result := Color;
end;
end;
procedure Render_Board(Canvas: THandle);
var i,j : word;
Cell: PCell;
Gr: TGPGraphics;
SB: TGPSolidBrush;
GB: TGPLinearGradientBrush;
Point: TGPPointF;
FCourier : TGPFont;
begin
Gr := TGPGraphics.Create(Canvas);
SB := TGPSolidBrush.Create(aclWhite);
GB := TGPLinearGradientBrush.Create(pic_rect, aclPeru, aclBurlyWood, 4);
FCourier := TGPFont.Create('Courier New', 12, 1);
Gr.FillRectangle(GB, pic_rect);
Gr.SetSmoothingMode(SmoothingModeHighQuality);
for i := 0 to LINE_LEN - 1 do
begin
for j := 0 to LINE_LEN - 1 do
begin
Cell := GetCell(i,j);
if is_reverse
then SB.SetColor(InverseColor(Cell.Color))
else SB.SetColor(Cell.Color);
Gr.FillRectangle(SB, Cell.Rect);
if i = 0 then
begin
Point.Y := Cell.Rect.Y + (Cell.Rect.Width / 2.5);
Point.X := 0;
SB.SetColor(aclBlack);
if is_reverse
then Gr.DrawString(WideString(IntToStr(j + 1)), -1, FCourier, Point, SB)
else Gr.DrawString(WideString(IntToStr(LINE_LEN - j)), -1, FCourier, Point, SB);
end;
end;
SB.SetColor(aclBlack);
Point.Y := Cell.Rect.Y + Cell.Rect.Height;
Point.X := Cell.Rect.X + (Cell.Rect.Width / 2.5);
Gr.DrawString(WideString(chr(ord('a') + i)), -1, FCourier, Point, SB);
end;
FCourier.Free;
GB.Free;
SB.Free;
Gr.Free
end;
procedure Render_Scene(width: integer);
begin
Pic.Bitmap.Width := width;
Pic.Bitmap.Height := Width;
pic_rect.X := 0; pic_rect.Y := 0;
pic_rect.Width := width; pic_rect.Height := width;
with Pic.Bitmap.Canvas do
begin
Render_Board(Handle);
RenderFigures(Handle);
DrawCells(Handle, posible_moves);
DrawArrow(Handle);
end;
// Pic.Bitmap.SaveToFile('R:\Messanger\Win32\Debug\bm.bmp');
end;
procedure StopGame();
begin
Pic.Free;
FreeChess();
end;
initialization
Pic := TPicture.Create;
Player1.Name := 'First';
Player1.Color := 1;
Player1.Active := true;
Player2.Name := 'Second';
Player2.Color := 0;
Player2.Active := false;
end.
|
unit Model.Estados;
interface
type
TEstados = class
private
FUF: System.string;
FNome: System.string;
public
property UF: System.String read FUF write FUF;
property Nome: System.string read FNome write FNome;
constructor Create; overload;
constructor Create(pFUF: System.String; pFNome: System.string); overload;
end;
implementation
constructor TEstados.Create;
begin
inherited Create;
end;
constructor TEstados.Create(pFUF: String; pFNome: string);
begin
FUF := pFUF;
FNome := pFNome;
end;
end.
|
unit CatRegex;
{
Catarinka - Regular Expression functions
Copyright (c) 2003-2014 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
Uses the RegExpr library by Andrey V. Sorokin.
}
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
System.Classes, System.SysUtils;
{$ELSE}
Classes, SysUtils;
{$ENDIF}
function RegExpFind(const s, re: string): string;
function RegExpReplace(const s, re, sreplacement: string): string;
function CatMatch(const substr, s: string): boolean;
implementation
uses CatStrings, RegExpr;
function RegExpReplace(const s, re, sreplacement: string): string;
var
r: TRegExpr;
begin
r := TRegExpr.Create;
try
r.Expression := re;
result := r.Replace(s, sreplacement, true);
finally
r.Free;
end;
end;
function RegExpFind(const s, re: string): string;
var
r: TRegExpr;
begin
result := emptystr;
r := TRegExpr.Create;
try
r.Expression := re;
if r.Exec(s) then
repeat
result := result + r.Match[0] + ', ';
until not r.ExecNext;
finally
r.Free;
end;
end;
function CatMatch(const substr, s: string): boolean;
const
cReEx = 'regexp:';
var
tmpsub: string;
begin
result := false;
tmpsub := substr;
if (pos(cReEx, tmpsub) <> 0) then
begin
tmpsub := after(tmpsub, cReEx);
if (RegExpFind(s, tmpsub) <> emptystr) then
result := true;
end
else
begin
if (pos(tmpsub, s) <> 0) then
result := true;
end;
end;
// ------------------------------------------------------------------------//
end.
|
unit UOpAppearance;
interface
uses UOptionBox, UCommPanels, UxlComboBox, UOptionManager;
type
TOpAppearance = class (TOptionPanel)
private
FCmbLanguage, FCmbAdjustLevel, FCmbTransparency, FCmbSplitterWidth: TxlcomboBox;
protected
procedure OnInitialize (); override;
procedure OnOpen (); override;
procedure OnClose (); override;
procedure OnCommand (ctrlID: integer); override;
public
procedure Load (const op: TOptions); override;
procedure Save (var op: TOptions); override;
end;
TOpTreeView = class (TOptionPanel)
private
FTreeFontDemo: TFontColorPanel;
protected
procedure OnInitialize (); override;
procedure OnOpen (); override;
procedure OnClose (); override;
public
procedure Load (const op: TOptions); override;
procedure Save (var op: TOptions); override;
end;
TOpTabControl = class (TOptionPanel)
private
FTabFontDemo: TFontColorPanel;
FTabWidth: TxlComboBox;
protected
procedure OnInitialize (); override;
procedure OnOpen (); override;
procedure OnClose (); override;
procedure OnCommand (ctrlID: integer); override;
public
procedure Load (const op: TOptions); override;
procedure Save (var op: TOptions); override;
end;
TOpListView = class (TOptionPanel)
private
FListFontDemo, FBlogFontDemo, FBlogTitleFontDemo, FBlogSelTitleFontDemo: TFontColorPanel;
protected
procedure OnInitialize (); override;
procedure OnOpen (); override;
procedure OnClose (); override;
public
procedure Load (const op: TOptions); override;
procedure Save (var op: TOptions); override;
end;
TOpEditor = class (TOptionPanel)
private
FEditorFontDemo, FLineNumberColorDemo, FSelLineColorDemo, FHLColorDemo: TFontColorPanel;
FHLList: TxlListBox;
FCmbMargins: TxlComboBox;
FOptions: TOptions;
procedure f_OnHLListSelChange (Sender: TObject);
procedure f_OnHLColorChange (Sender: TObject);
protected
procedure OnInitialize (); override;
procedure OnOpen (); override;
procedure OnClose (); override;
procedure OnCommand (ctrlID: integer); override;
public
procedure Load (const op: TOptions); override;
procedure Save (var op: TOptions); override;
end;
TOpOtherControls = class (TOptionPanel)
private
FMininoteFontDemo: TFontColorPanel;
protected
procedure OnInitialize (); override;
procedure OnOpen (); override;
procedure OnClose (); override;
public
procedure Load (const op: TOptions); override;
procedure Save (var op: TOptions); override;
end;
implementation
uses Windows, ULangManager, UxlCommDlgs, UxlFunctions, UxlMath, UTypeDef, UxlStrUtils, UxlList, UGlobalObj, Resource;
procedure TOpAppearance.OnInitialize ();
begin
SetTemplate (ob_appearance);
end;
const c_OpAppearance: array[0..8] of word = (st_language, chk_toolwindowstyle, chk_captionpagename, chk_showmenubar, chk_showtoolbar,
st_transparency, chk_autoadjust, st_sensitivity, st_splitterwidth);
procedure TOpAppearance.OnOpen ();
var i: integer;
o_list: TxlStrList;
begin
RefreshItemText (self, c_OpAppearance);
o_list := TxlStrList.Create;
FindFiles (LangDir + '*.lng', o_list, false);
FCmbLanguage := TxlComboBox.create(self, ItemHandle[cmb_language]);
with FCmbLanguage.Items do
begin
Add ('Chinese');
Add ('English');
for i := o_list.Low to o_list.High do
if (not IsSameStr(o_list[i], 'Chinese')) and (not IsSameStr(o_list[i], 'English')) then
Add (o_list[i]);
end;
o_list.free;
FCmbTransparency := TxlComboBox.create(self, ItemHandle[cmb_transparency]);
for i := 1 to 10 do
FCmbTransparency.Items.Add (i);
FCmbAdjustLevel := TxlComboBox.create(self, ItemHandle[cmb_adjustlevel]);
for i := 1 to 5 do
FCmbAdjustLevel.Items.Add (i);
FCmbSplitterWidth := TxlComboBox.Create (self, ItemHandle[cmb_splitterwidth]);
for i := 1 to 10 do
FCmbSplitterWidth.Items.Add (i);
end;
procedure TOpAppearance.OnClose ();
begin
FCmbTransparency.free;
FCmbLanguage.free;
FCmbAdjustLevel.free;
FCmbSplitterWidth.free;
end;
procedure TOpAppearance.Load (const op: TOptions);
begin
FCmbLanguage.Text := op.Language;
ItemChecked[chk_toolwindowstyle] := op.ToolWindowStyle;
ItemChecked[chk_captionpagename] := op.captionpagename;
ItemChecked[chk_showmenubar] := op.showmenubar;
ItemChecked[chk_showtoolbar] := op.ShowToolBar;
FCmbtransparency.Items.SelIndex := op.Transparency - 1;
ItemChecked[chk_autoadjust] := op.AutoAdjust;
FCmbadjustlevel.Items.SelIndex := op.AutoAdjustLevel - 1;
ItemEnabled[cmb_adjustlevel] := ItemChecked[chk_autoadjust];
FCmbSplitterWidth.Items.SelIndex := op.SplitterWidth - 1;
end;
procedure TOpAppearance.Save (var op: TOptions);
begin
with op do
begin
language := FCmblanguage.Text;
ToolWindowStyle := ItemChecked[chk_toolwindowstyle];
Captionpagename := ItemChecked[chk_captionpagename];
ShowMenuBar := ItemChecked[chk_showmenubar];
ShowToolBar := ItemChecked[chk_showtoolbar];
AutoAdjust := ItemChecked[chk_autoadjust];
AutoAdjustLevel := FCmbadjustlevel.Items.SelIndex + 1;
Transparency := FCmbtransparency.Items.SelIndex + 1;
SplitterWidth := FCmbSplitterWidth.Items.SelIndex + 1;
end;
end;
procedure TOpAppearance.OnCommand (ctrlID: integer);
begin
case ctrlID of
chk_autoadjust:
ItemEnabled[cmb_adjustlevel] := ItemChecked[chk_autoadjust];
end;
end;
//-----------------------------
const c_OpTreeView: array[0..8] of word = (st_tree, cb_settreefont, cb_settreecolor, chk_treehorzscroll, chk_linesatroot,
chk_nodebuttons, chk_nodelines, chk_shownodeimages, chk_treeonright);
procedure TOpTreeView.OnInitialize ();
begin
SetTemplate (ob_treeview);
end;
procedure TOpTreeView.OnOpen ();
begin
RefreshItemText (self, c_OpTreeView);
FTreeFontDemo := TFontColorPanel.create (self, ItemHandle[st_treefontdemo], ItemHandle[cb_settreefont], ItemHandle[cb_settreecolor]);
end;
procedure TOpTreeView.OnClose ();
begin
FTreeFontDemo.free;
end;
procedure TOpTreeView.Load (const op: TOptions);
begin
FTreeFontDemo.Font := op.TreeFont;
FTreeFontDemo.Color := op.TreeColor;
ItemChecked[chk_treehorzscroll] := op.TreeHorzScroll;
ItemChecked[chk_nodebuttons] := op.NodeButtons;
ItemChecked[chk_nodelines] := op.NodeLines;
ItemChecked[chk_linesatroot] := op.LinesAtRoot;
ItemChecked[chk_shownodeimages] := op.ShowNodeImages;
ItemChecked[chk_treeonright] := op.TreeOnRight;
end;
procedure TOpTreeView.Save (var op: TOptions);
begin
with op do
begin
TreeHorzScroll := Itemchecked[chk_treehorzscroll];
NodeButtons := ItemChecked[chk_nodebuttons];
NodeLines := ItemChecked[chk_nodelines];
LinesAtRoot := ItemChecked[chk_linesatroot];
ShowNodeImages := ItemChecked[chk_shownodeimages];
TreeOnRight := ItemChecked[chk_treeonright];
TreeFont.assign (FTreeFontDemo.Font);
TreeColor := FTreeFontDemo.Color;
end;
end;
//------------------------
procedure TOpTabControl.OnInitialize ();
begin
SetTemplate (ob_tabcontrol);
end;
procedure TOpTabControl.OnOpen ();
const c_OpTabControl: array[0..6] of word = (st_tabpage, cb_settabfont, chk_showtabimages, chk_tabonbottom, chk_multilinetab,
chk_fixedtabwidth, chk_highlightcurrenttab);
var i: integer;
begin
RefreshItemText (self, c_OpTabControl);
FTabWidth := TxlComboBox.create(self, ItemHandle[cmb_tabwidth]);
for i := 1 to 10 do
FTabWidth.Items.add (i);
FTabFontDemo := TFontColorPanel.Create (self, ItemHandle[st_tabfontdemo], ItemHandle[cb_settabfont], 0);
end;
procedure TOpTabControl.OnClose ();
begin
FTabWidth.free;
FTabFontDemo.free;
end;
procedure TOpTabControl.Load (const op: TOptions);
begin
ItemChecked[chk_showtabimages] := op.ShowTabImages;
ItemChecked[chk_tabonbottom] := op.TabOnBottom;
ItemChecked[chk_multilinetab] := op.multilinetab;
ItemChecked[chk_fixedtabwidth] := (op.tabwidth <> 0);
ItemChecked[chk_highlightcurrenttab] := op.HighlightCurrentTab;
FTabWidth.enabled := ItemChecked[chk_fixedtabwidth];
if op.tabwidth <> 0 then
FTabWidth.Text := IntToStr(op.tabwidth)
else
FTabWidth.text := '5';
FTabFontDemo.Font := op.TabFont;
end;
procedure TOpTabControl.Save (var op: TOptions);
begin
with op do
begin
ShowTabImages := ItemChecked[chk_showtabimages];
TabOnBottom := ItemChecked[chk_tabonbottom];
multilinetab := ItemChecked[chk_multilinetab];
HighlightCurrentTab := ItemChecked[chk_highlightcurrenttab];
end;
if not ItemChecked[chk_fixedtabwidth] then
op.tabwidth := 0
else
op.tabwidth := StrToInt(Ftabwidth.text);
op.TabFont.assign (FTabFontDemo.Font);
end;
procedure TOpTabControl.OnCommand (ctrlID: integer);
begin
case ctrlID of
chk_fixedtabwidth:
ItemEnabled[cmb_tabwidth] := ItemChecked[chk_fixedtabwidth];
end;
end;
//---------------------------------
const c_OpListView: array[0..11] of word = (st_list, cb_setlistfont, cb_setlistcolor, st_blog, cb_setblogfont, cb_setblogcolor,
st_blogtitle, cb_setblogtitlefont, cb_setblogtitlecolor, st_blogseltitle, cb_setblogseltitlefont, cb_setblogseltitlecolor);
procedure TOpListView.OnInitialize ();
begin
SetTemplate (ob_listview);
end;
procedure TOpListView.OnOpen ();
begin
RefreshItemText (self, c_OpListView);
FListFontDemo := TFontColorPanel.create (self, ItemHandle[st_listfontdemo], ItemHandle[cb_setlistfont], ItemHandle[cb_setlistcolor]);
FBlogFontDemo := TFontColorPanel.create (self, ItemHandle[st_blogfontdemo], ItemHandle[cb_setblogfont], ItemHandle[cb_setblogcolor]);
FBlogTitleFontDemo := TFontColorPanel.create (self, ItemHandle[st_blogtitlefontdemo], ItemHandle[cb_setblogtitlefont], ItemHandle[cb_setblogtitlecolor]);
FBlogSelTitleFontDemo := TFontColorPanel.create (self, ItemHandle[st_blogseltitlefontdemo], ItemHandle[cb_setblogseltitlefont], ItemHandle[cb_setblogseltitlecolor]);
end;
procedure TOpListView.OnClose ();
begin
FListFontDemo.free;
FBlogFontDemo.free;
FBlogTitleFontDemo.free;
FBlogSelTitleFontDemo.free;
end;
procedure TOpListView.Load (const op: TOptions);
begin
FListFontDemo.Font := op.ListFont;
FListFontDemo.Color := op.ListColor;
FBlogFontDemo.Font := op.BlogFont;
FBlogFontDemo.Color := op.BlogColor;
FBlogTitleFontDemo.Font := op.BlogTitleFont;
FBlogTitleFontDemo.Color := op.BlogTitleColor;
FBlogSelTitleFontDemo.Font := op.BlogSelTitleFont;
FBlogSelTitleFontDemo.Color := op.BlogSelTitleColor;
end;
procedure TOpListView.Save (var op: TOptions);
begin
op.ListFont.assign (FListFontDemo.Font);
op.ListColor := FListFontDemo.Color;
op.BlogFont.assign (FBlogFontDemo.Font);
op.BlogColor := FBlogFontDemo.Color;
op.BlogTitleFont.assign (FBlogTitleFontDemo.Font);
op.BlogTitleColor := FBlogTitleFontDemo.Color;
op.BlogSelTitleFont.assign (FBlogSelTitleFontDemo.Font);
op.BlogSelTitleColor := FBlogSelTitleFontDemo.Color;
end;
//-------------------------------
const c_OpEditor: array[0..10] of word = (chk_showlinenumber, cb_setlinenumbercolor, chk_highlightselline, cb_setsellinecolor,
st_margins, st_editor, cb_seteditorfont, cb_seteditorcolor, chk_useunderline, st_HLText, cb_HLColor);
procedure TOpEditor.OnInitialize ();
begin
SetTemplate (ob_editor);
end;
procedure TOpEditor.OnOpen ();
var i: integer;
begin
RefreshItemText (self, c_OpEditor);
FEditorFontDemo := TFontColorPanel.create (self, ItemHandle[st_editorfontdemo], ItemHandle[cb_seteditorfont], ItemHandle[cb_seteditorcolor]);
FCmbMargins := TxlComboBox.Create (self, ItemHandle[cmb_margins]);
for i := 0 to 10 do
FCmbMargins.Items.Add (i);
FLineNumberColorDemo := TFontColorPanel.Create (self, ItemHandle[st_linenumberdemo], 0, ItemHandle[cb_setlinenumbercolor]);
FSelLineColorDemo := TFontColorPanel.Create (self, ItemHandle[st_sellinedemo], 0, ItemHandle[cb_setsellinecolor]);
FHLColorDemo := TFontColorPanel.Create (self, ItemHandle[st_HLdemo], 0, ItemHandle[cb_HLColor]);
FHLColorDemo.OnColorChange := f_OnHLColorChange;
FHLList := TxlListBox.Create (self, ItemHandle[lst_hltext]);
with FHLList.Items do
begin
Add (LangMan.GetItem (m_highlightmatch));
Add (LangMan.GetItem (m_highlight1));
Add (LangMan.GEtItem (m_highlight2));
Add (LangMan.GetItem (m_highlight3));
Add (LangMan.GetItem (m_highlight4));
OnSelChange := f_OnHLListSelChange;
SelIndex := 0;
end;
end;
procedure TOpEditor.OnClose ();
begin
FEditorFontDemo.free;
FLineNumberColorDemo.free;
FCmbMargins.free;
FSelLineColorDemo.free;
FHLColorDemo.free;
FHLList.free;
end;
procedure TOpEditor.Load (const op: TOptions);
begin
FEditorFontDemo.Font := op.EditorFont;
FEditorFontDemo.Color := op.EditorColor;
FCmbmargins.Items.SelIndex := op.margins;
ItemChecked[chk_showlinenumber] := op.showlinenumber;
FLineNumberColorDemo.Color := op.LineNumberColor;
ItemChecked[chk_highlightselline] := op.HighLightSelLine;
FSelLineColorDemo.Color := op.SelLineColor;
FOptions := op;
f_OnHLListSelChange (self);
end;
procedure TOpEditor.Save (var op: TOptions);
begin
with FOptions do
begin
Margins := Fcmbmargins.Items.SelIndex;
Showlinenumber := ItemChecked[chk_showlinenumber];
HighLightSelLine := ItemChecked[chk_highlightselline];
LineNumberColor := FLineNumberColorDemo.Color;
SelLineColor := FSelLineColorDemo.Color;
EditorFont.assign (FEditorFontDemo.Font);
EditorColor := FEditorFontDemo.Color;
end;
op := FOptions;
end;
procedure TOpEditor.OnCommand (ctrlID: integer);
begin
if ctrlID = chk_useunderline then
FOptions.HLUnderline[FHLList.Items.SelIndex] := ItemChecked[chk_useunderline];
end;
procedure TOpEditor.f_OnHLListSelChange (Sender: TObject);
var i: integer;
begin
i := FHLList.Items.SelIndex;
FHLColorDemo.Color := FOptions.HLColor[i];
ItemChecked[chk_useunderline] := FOptions.HlUnderline[i];
end;
procedure TOpEditor.f_OnHLColorChange (Sender: TObject);
var i: integer;
begin
i := FHLList.Items.SelIndex;
FOptions.HLColor[i] := FHLColorDemo.Color;
end;
//--------------------------------------
const c_OpOtherControls: array[0..2] of word = (st_mininote, cb_setmininotefont, cb_setmininotecolor);
procedure TOpOtherControls.OnInitialize ();
begin
SetTemplate (ob_othercontrols);
end;
procedure TOpOtherControls.OnOpen ();
begin
RefreshItemText (self, c_OpOtherControls);
FMininoteFontDemo := TFontColorPanel.create (self, ItemHandle[st_mininotefontdemo], ItemHandle[cb_setmininotefont], ItemHandle[cb_setmininotecolor]);
end;
procedure TOpOtherControls.OnClose ();
begin
FMininoteFontDemo.free;
end;
procedure TOpOtherControls.Load (const op: TOptions);
begin
FMininoteFontDemo.Font := op.MininoteFont;
FMininoteFontDemo.Color := op.MininoteColor;
end;
procedure TOpOtherControls.Save (var op: TOptions);
begin
op.MiniNoteFont.assign (FMiniNoteFontDemo.Font);
op.MiniNoteColor := FMininoteFontDemo.Color;
end;
end.
|
PROGRAM SortFile(INPUT, OUTPUT);
CONST
SwitchOn = '1';
SwitchOff = '2';
VAR
F: TEXT;
PROCEDURE CopyFile(VAR F1, F2: TEXT);
VAR
Ch: CHAR;
BEGIN
RESET(F1);
REWRITE(F2);
WHILE NOT(EOLN(F1))
DO
BEGIN
READ(F1, Ch);
WRITE(F2, Ch)
END;
WRITELN(F2)
END;
PROCEDURE Split(VAR F1, F2, F3: TEXT);
{Разбивает F1 на F2, F3}
VAR
Ch, Switch: CHAR;
BEGIN {Split}
RESET(F1);
REWRITE(F2);
REWRITE(F3);
Switch := SwitchOn;
WHILE NOT (EOLN(F1))
DO
BEGIN
READ(F1, Ch);
IF (Switch = SwitchOn)
THEN
BEGIN
WRITE(F2, Ch);
Switch := SwitchOff
END
ELSE
BEGIN
WRITE(F3, Ch);
Switch := SwitchOn
END
END;
WRITELN(F2);
WRITELN(F3);
CopyFile(F2, OUTPUT);
CopyFile(F3, OUTPUT);
END; {Split}
PROCEDURE RecursiveSort(VAR F1: TEXT);
VAR
F2, F3: TEXT;
{Ch: CHAR;
}{PROCEDURE Split(VAR F1, F2, F3: TEXT)
Разбивает F1 на F2 и F3}
{PROCEDURE Merge(VAR F1, F2, F3: TEXT)
Сливает F2 и F3 в F1}
BEGIN {RecursiveSort}
RESET(F1);
IF NOT (EOLN(F1))
THEN
BEGIN
IF NOT (EOLN(F1))
THEN {Файл имеет как минимум 2 символа}
BEGIN
Split(F1, F2, F3);
{RecursiveSort(F2);
RecursiveSort(F3);
Merge(F1, F2, F3);}
END
END
END; {RecursiveSort}
BEGIN {SortFile}
CopyFile(INPUT, F);
RecursiveSort(F);
CopyFile(F, OUTPUT)
END. {SortFile}
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgement in the product documentation would be *
* appreciated but is not required. *
* 2. Altered source versions must be plainly marked as such, and must not be *
* misrepresented as being the original software. *
* 3. This notice may not be removed or altered from any source distribution. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Scene3D.Renderer.Instance;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
{$m+}
{$undef UseSphereBasedCascadedShadowMaps}
interface
uses Classes,
SysUtils,
Math,
PasMP,
Vulkan,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Framework,
PasVulkan.Application,
PasVulkan.Resources,
PasVulkan.FrameGraph,
PasVulkan.TimerQuery,
PasVulkan.Collections,
PasVulkan.CircularDoublyLinkedList,
PasVulkan.VirtualReality,
PasVulkan.Scene3D,
PasVulkan.Scene3D.Renderer.Globals,
PasVulkan.Scene3D.Renderer.CameraPreset,
PasVulkan.Scene3D.Renderer,
PasVulkan.Scene3D.Renderer.Array2DImage,
PasVulkan.Scene3D.Renderer.MipmappedArray2DImage,
PasVulkan.Scene3D.Renderer.OrderIndependentTransparencyBuffer,
PasVulkan.Scene3D.Renderer.OrderIndependentTransparencyImage,
PasVulkan.Scene3D.Renderer.ImageBasedLighting.ReflectionProbeCubeMaps;
type { TpvScene3DRendererInstance }
TpvScene3DRendererInstance=class(TpvScene3DRendererBaseObject)
public
const CountCascadedShadowMapCascades=4;
CountOrderIndependentTransparencyLayers=8;
type { TInFlightFrameState }
TInFlightFrameState=record
Ready:TPasMPBool32;
CountViews:TpvSizeInt;
FinalViewIndex:TpvSizeInt;
CountFinalViews:TpvSizeInt;
HUDViewIndex:TpvSizeInt;
CountHUDViews:TpvSizeInt;
ReflectionProbeViewIndex:TpvSizeInt;
CountReflectionProbeViews:TpvSizeInt;
ReflectiveShadowMapViewIndex:TpvSizeInt;
CountReflectiveShadowMapProbeViews:TpvSizeInt;
CascadedShadowMapViewIndex:TpvSizeInt;
CountCascadedShadowMapViews:TpvSizeInt;
ReflectionProbeRenderPassIndex:TpvSizeInt;
ReflectiveShadowMapRenderPassIndex:TpvSizeInt;
ViewRenderPassIndex:TpvSizeInt;
CascadedShadowMapRenderPassIndex:TpvSizeInt;
ZNear:TpvFloat;
ZFar:TpvFloat;
Jitter:TpvVector4;
end;
PInFlightFrameState=^TInFlightFrameState;
TInFlightFrameStates=array[0..MaxInFlightFrames+1] of TInFlightFrameState;
PInFlightFrameStates=^TInFlightFrameStates;
TFrustumClusterGridPushConstants=packed record
public
TileSizeX:TpvUInt32;
TileSizeY:TpvUInt32;
ZNear:TpvFloat;
ZFar:TpvFloat;
////
ViewRect:TpvVector4;
////
CountLights:TpvUInt32;
ViewIndex:TpvUInt32;
Size:TpvUInt32;
OffsetedViewIndex:TpvUInt32;
////
ClusterSizeX:TpvUInt32;
ClusterSizeY:TpvUInt32;
ClusterSizeZ:TpvUInt32;
Reversed0:TpvUInt32;
//
ZScale:TpvFloat;
ZBias:TpvFloat;
ZMax:TpvFloat;
Reversed1:TpvUInt32;
end;
PFrustumClusterGridPushConstants=^TFrustumClusterGridPushConstants;
{ TCascadedShadowMap }
TCascadedShadowMap=record
public
View:TpvScene3D.TView;
CombinedMatrix:TpvMatrix4x4;
SplitDepths:TpvVector2;
Scales:TpvVector2;
end;
{ TLockOrderIndependentTransparentViewPort }
TLockOrderIndependentTransparentViewPort=packed record
x:TpvInt32;
y:TpvInt32;
z:TpvInt32;
w:TpvInt32;
end;
{ TLockOrderIndependentTransparentUniformBuffer }
TLockOrderIndependentTransparentUniformBuffer=packed record
ViewPort:TLockOrderIndependentTransparentViewPort;
end;
{ TLoopOrderIndependentTransparentViewPort }
TLoopOrderIndependentTransparentViewPort=packed record
x:TpvInt32;
y:TpvInt32;
z:TpvInt32;
w:TpvInt32;
end;
{ TLoopOrderIndependentTransparentUniformBuffer }
TLoopOrderIndependentTransparentUniformBuffer=packed record
ViewPort:TLoopOrderIndependentTransparentViewPort;
end;
{ TApproximationOrderIndependentTransparentUniformBuffer }
TApproximationOrderIndependentTransparentUniformBuffer=packed record
ZNearZFar:TpvVector4;
end;
PCascadedShadowMap=^TCascadedShadowMap;
TCascadedShadowMaps=array[0..CountCascadedShadowMapCascades-1] of TCascadedShadowMap;
PCascadedShadowMaps=^TCascadedShadowMaps;
TInFlightFrameCascadedShadowMaps=array[0..MaxInFlightFrames-1] of TCascadedShadowMaps;
TCascadedShadowMapUniformBuffer=packed record
Matrices:array[0..CountCascadedShadowMapCascades-1] of TpvMatrix4x4;
SplitDepthsScales:array[0..CountCascadedShadowMapCascades-1] of TpvVector4;
ConstantBiasNormalBiasSlopeBiasClamp:array[0..CountCascadedShadowMapCascades-1] of TpvVector4;
MetaData:array[0..3] of TpvUInt32;
end;
PCascadedShadowMapUniformBuffer=^TCascadedShadowMapUniformBuffer;
TCascadedShadowMapUniformBuffers=array[0..MaxInFlightFrames-1] of TCascadedShadowMapUniformBuffer;
TCascadedShadowMapVulkanUniformBuffers=array[0..MaxInFlightFrames-1] of TpvVulkanBuffer;
TVulkanBuffers=array[0..MaxInFlightFrames-1] of TpvVulkanBuffer;
TArray2DImages=array[0..MaxInFlightFrames-1] of TpvScene3DRendererArray2DImage;
TMipmappedArray2DImages=array[0..MaxInFlightFrames-1] of TpvScene3DRendererMipmappedArray2DImage;
TOrderIndependentTransparencyBuffers=array[0..MaxInFlightFrames-1] of TpvScene3DRendererOrderIndependentTransparencyBuffer;
TOrderIndependentTransparencyImages=array[0..MaxInFlightFrames-1] of TpvScene3DRendererOrderIndependentTransparencyImage;
TLuminanceVulkanBuffers=array[0..MaxInFlightFrames-1] of TpvVulkanBuffer;
TLuminancePushConstants=record
MinLogLuminance:TpvFloat;
LogLuminanceRange:TpvFloat;
InverseLogLuminanceRange:TpvFloat;
TimeCoefficient:TpvFloat;
MinLuminance:TpvFloat;
MaxLuminance:TpvFloat;
CountPixels:TpvUInt32;
end;
PLuminancePushConstants=^TLuminancePushConstants;
{ TMeshFragmentSpecializationConstants }
TMeshFragmentSpecializationConstants=record
public
UseReversedZ:TVkBool32;
procedure SetPipelineShaderStage(const aVulkanPipelineShaderStage:TpvVulkanPipelineShaderStage);
end;
{ TCascadedShadowMapBuilder }
TCascadedShadowMapBuilder=class
public
const CascadeNearPlaneOffset=-512.0;
CascadeFarPlaneOffset=512.0;
FrustumCorners:array[0..7] of TpvVector3=
(
(x:-1.0;y:-1.0;z:0.0),
(x:1.0;y:-1.0;z:0.0),
(x:-1.0;y:1.0;z:0.0),
(x:1.0;y:1.0;z:0.0),
(x:-1.0;y:-1.0;z:1.0),
(x:1.0;y:-1.0;z:1.0),
(x:-1.0;y:1.0;z:1.0),
(x:1.0;y:1.0;z:1.0)
);
private
fInstance:TpvScene3DRendererInstance;
fSceneWorldSpaceBoundingBox:TpvAABB;
fSceneWorldSpaceSphere:TpvSphere;
fLightForwardVector:TpvVector3;
fLightSideVector:TpvVector3;
fLightUpVector:TpvVector3;
fFrustumCenter:TpvVector3;
fOrigin:TpvVector3;
fShadowOrigin:TpvVector2;
fRoundedOrigin:TpvVector2;
fRoundOffset:TpvVector2;
fViewMatrix:TpvMatrix4x4;
fProjectionMatrix:TpvMatrix4x4;
fLightViewMatrix:TpvMatrix4x4;
fTemporaryMatrix:TpvMatrix4x4;
fLightProjectionMatrix:TpvMatrix4x4;
fLightViewProjectionMatrix:TpvMatrix4x4;
fInverseLightViewProjectionMatrix:TpvMatrix4x4;
fInverseViewProjectionMatrices:array[0..7] of TpvMatrix4x4;
fWorldSpaceFrustumCorners:array[0..7,0..7] of TpvVector3;
fTemporaryFrustumCorners:array[0..7,0..7] of TpvVector3;
fFrustumAABB:TpvAABB;
protected
procedure SnapLightFrustum(var aScale,aOffset:TpvVector2;const aMatrix:TpvMatrix4x4;const aWorldOrigin:TpvVector3;const aShadowMapResolution:TpvVector2);
public
constructor Create(const aInstance:TpvScene3DRendererInstance); reintroduce;
destructor Destroy; override;
procedure Calculate(const aInFlightFrameIndex:TpvInt32);
end;
{ THUDRenderPass }
THUDRenderPass=class(TpvFrameGraph.TRenderPass)
protected
fRendererInstance:TpvScene3DRendererInstance;
fParent:TObject;
public
constructor Create(const aFrameGraph:TpvFrameGraph;const aRendererInstance:TpvScene3DRendererInstance;const aParent:TObject); reintroduce; virtual;
end;
THUDRenderPassClass=class of THUDRenderPass;
private
fFrameGraph:TpvFrameGraph;
fVirtualReality:TpvVirtualReality;
fExternalImageFormat:TVkFormat;
fExternalOutputImageData:TpvFrameGraph.TExternalImageData;
fHasExternalOutputImage:boolean;
fReflectionProbeWidth:TpvInt32;
fReflectionProbeHeight:TpvInt32;
fReflectiveShadowMapWidth:TpvInt32;
fReflectiveShadowMapHeight:TpvInt32;
fCascadedShadowMapWidth:TpvInt32;
fCascadedShadowMapHeight:TpvInt32;
fCountSurfaceViews:TpvInt32;
fSurfaceMultiviewMask:TpvUInt32;
fLeft:TpvInt32;
fTop:TpvInt32;
fWidth:TpvInt32;
fHeight:TpvInt32;
fHUDWidth:TpvInt32;
fHUDHeight:TpvInt32;
fFrustumClusterGridSizeX:TpvInt32;
fFrustumClusterGridSizeY:TpvInt32;
fFrustumClusterGridSizeZ:TpvInt32;
fFrustumClusterGridTileSizeX:TpvInt32;
fFrustumClusterGridTileSizeY:TpvInt32;
fFrustumClusterGridCountTotalViews:TpvInt32;
fFOV:TpvFloat;
fZNear:TpvFloat;
fZFar:TpvFloat;
fCameraViewMatrix:TpvMatrix4x4;
fPointerToCameraViewMatrix:PpvMatrix4x4;
fInFlightFrameStates:TInFlightFrameStates;
fPointerToInFlightFrameStates:PInFlightFrameStates;
fMeshFragmentSpecializationConstants:TMeshFragmentSpecializationConstants;
fCameraPreset:TpvScene3DRendererCameraPreset;
fUseDebugBlit:boolean;
private
fViews:TpvScene3D.TViews;
fCountRealViews:TpvInt32;
private
fVulkanRenderSemaphores:array[0..MaxInFlightFrames-1] of TpvVulkanSemaphore;
private
fNearestFarthestDepthVulkanBuffers:TVulkanBuffers;
fDepthOfFieldAutoFocusVulkanBuffers:TVulkanBuffers;
fDepthOfFieldBokenShapeTapVulkanBuffers:TVulkanBuffers;
private
fFrustumClusterGridPushConstants:TpvScene3DRendererInstance.TFrustumClusterGridPushConstants;
fFrustumClusterGridGlobalsVulkanBuffers:TVulkanBuffers;
fFrustumClusterGridAABBVulkanBuffers:TVulkanBuffers;
fFrustumClusterGridIndexListCounterVulkanBuffers:TVulkanBuffers;
fFrustumClusterGridIndexListVulkanBuffers:TVulkanBuffers;
fFrustumClusterGridDataVulkanBuffers:TVulkanBuffers;
private
fInFlightFrameCascadedShadowMaps:TInFlightFrameCascadedShadowMaps;
fCascadedShadowMapUniformBuffers:TCascadedShadowMapUniformBuffers;
fCascadedShadowMapVulkanUniformBuffers:TCascadedShadowMapVulkanUniformBuffers;
private
fCountLockOrderIndependentTransparencyLayers:TpvInt32;
fLockOrderIndependentTransparentUniformBuffer:TLockOrderIndependentTransparentUniformBuffer;
fLockOrderIndependentTransparentUniformVulkanBuffer:TpvVulkanBuffer;
fLockOrderIndependentTransparencyABufferBuffers:TOrderIndependentTransparencyBuffers;
fLockOrderIndependentTransparencyAuxImages:TOrderIndependentTransparencyImages;
fLockOrderIndependentTransparencySpinLockImages:TOrderIndependentTransparencyImages;
private
fCountLoopOrderIndependentTransparencyLayers:TpvInt32;
fLoopOrderIndependentTransparentUniformBuffer:TLoopOrderIndependentTransparentUniformBuffer;
fLoopOrderIndependentTransparentUniformVulkanBuffer:TpvVulkanBuffer;
fLoopOrderIndependentTransparencyABufferBuffers:TOrderIndependentTransparencyBuffers;
fLoopOrderIndependentTransparencyZBufferBuffers:TOrderIndependentTransparencyBuffers;
fLoopOrderIndependentTransparencySBufferBuffers:TOrderIndependentTransparencyBuffers;
private
fApproximationOrderIndependentTransparentUniformBuffer:TApproximationOrderIndependentTransparentUniformBuffer;
fApproximationOrderIndependentTransparentUniformVulkanBuffer:TpvVulkanBuffer;
private
fDeepAndFastApproximateOrderIndependentTransparencyFragmentCounterImages:TOrderIndependentTransparencyImages;
fDeepAndFastApproximateOrderIndependentTransparencyAccumulationImages:TOrderIndependentTransparencyImages;
fDeepAndFastApproximateOrderIndependentTransparencyAverageImages:TOrderIndependentTransparencyImages;
fDeepAndFastApproximateOrderIndependentTransparencyBucketImages:TOrderIndependentTransparencyImages;
fDeepAndFastApproximateOrderIndependentTransparencySpinLockImages:TOrderIndependentTransparencyImages;
private
fDepthMipmappedArray2DImages:TMipmappedArray2DImages;
fSceneMipmappedArray2DImages:TMipmappedArray2DImages;
fHUDMipmappedArray2DImages:TMipmappedArray2DImages;
private
fLuminanceHistogramVulkanBuffers:TLuminanceVulkanBuffers;
fLuminanceVulkanBuffers:TLuminanceVulkanBuffers;
public
fMinimumLuminance:TpvScalar;
fMaximumLuminance:TpvScalar;
fLuminancePushConstants:TLuminancePushConstants;
fLuminanceEvents:array[0..MaxInFlightFrames-1] of TpvVulkanEvent;
fLuminanceEventReady:array[0..MaxInFlightFrames-1] of boolean;
private
fTAAHistoryColorImages:TArray2DImages;
fTAAHistoryDepthImages:TArray2DImages;
public
fTAAEvents:array[0..MaxInFlightFrames-1] of TpvVulkanEvent;
fTAAEventReady:array[0..MaxInFlightFrames-1] of boolean;
private
fImageBasedLightingReflectionProbeCubeMaps:TpvScene3DRendererImageBasedLightingReflectionProbeCubeMaps;
private
fPasses:TObject;
fLastOutputResource:TpvFrameGraph.TPass.TUsedImageResource;
fCascadedShadowMapBuilder:TCascadedShadowMapBuilder;
fHUDSize:TpvFrameGraph.TImageSize;
fHUDRenderPassClass:THUDRenderPassClass;
fHUDRenderPassParent:TObject;
procedure CalculateCascadedShadowMaps(const aInFlightFrameIndex:TpvInt32);
procedure AddCameraReflectionProbeViews(const aInFlightFrameIndex:TpvInt32);
public
constructor Create(const aParent:TpvScene3DRendererBaseObject;const aVirtualReality:TpvVirtualReality=nil;const aExternalImageFormat:TVkFormat=VK_FORMAT_UNDEFINED); reintroduce;
destructor Destroy; override;
procedure Prepare;
procedure AcquirePersistentResources;
procedure ReleasePersistentResources;
procedure AcquireVolatileResources;
procedure ReleaseVolatileResources;
procedure Update(const aInFlightFrameIndex:TpvInt32;const aFrameCounter:TpvInt64);
procedure Reset;
function AddView(const aView:TpvScene3D.TView):TpvInt32;
function AddViews(const aViews:array of TpvScene3D.TView):TpvInt32;
function GetJitterOffset(const aFrameCounter:TpvInt64):TpvVector2;
function AddTemporalAntialiasingJitter(const aProjectionMatrix:TpvMatrix4x4;const aFrameCounter:TpvInt64):TpvMatrix4x4;
procedure DrawUpdate(const aInFlightFrameIndex:TpvInt32;const aFrameCounter:TpvInt64);
procedure Draw(const aSwapChainImageIndex,aInFlightFrameIndex:TpvInt32;const aFrameCounter:TpvInt64;var aWaitSemaphore:TpvVulkanSemaphore;const aWaitFence:TpvVulkanFence=nil);
public
property CameraViewMatrix:TpvMatrix4x4 read fCameraViewMatrix write fCameraViewMatrix;
property PointerToCameraViewMatrix:PpvMatrix4x4 read fPointerToCameraViewMatrix;
property InFlightFrameStates:PInFlightFrameStates read fPointerToInFlightFrameStates;
property Views:TpvScene3D.TViews read fViews;
property MeshFragmentSpecializationConstants:TMeshFragmentSpecializationConstants read fMeshFragmentSpecializationConstants;
published
property CameraPreset:TpvScene3DRendererCameraPreset read fCameraPreset;
public
property NearestFarthestDepthVulkanBuffers:TVulkanBuffers read fNearestFarthestDepthVulkanBuffers;
property DepthOfFieldAutoFocusVulkanBuffers:TVulkanBuffers read fDepthOfFieldAutoFocusVulkanBuffers;
property DepthOfFieldBokenShapeTapVulkanBuffers:TVulkanBuffers read fDepthOfFieldBokenShapeTapVulkanBuffers;
public
property FrustumClusterGridSizeX:TpvInt32 read fFrustumClusterGridSizeX;
property FrustumClusterGridSizeY:TpvInt32 read fFrustumClusterGridSizeY;
property FrustumClusterGridSizeZ:TpvInt32 read fFrustumClusterGridSizeZ;
property FrustumClusterGridTileSizeX:TpvInt32 read fFrustumClusterGridTileSizeX;
property FrustumClusterGridTileSizeY:TpvInt32 read fFrustumClusterGridTileSizeY;
property FrustumClusterGridCountTotalViews:TpvInt32 read fFrustumClusterGridCountTotalViews;
property FrustumClusterGridPushConstants:TpvScene3DRendererInstance.TFrustumClusterGridPushConstants read fFrustumClusterGridPushConstants;
property FrustumClusterGridGlobalsVulkanBuffers:TVulkanBuffers read fFrustumClusterGridGlobalsVulkanBuffers;
property FrustumClusterGridAABBVulkanBuffers:TVulkanBuffers read fFrustumClusterGridAABBVulkanBuffers;
property FrustumClusterGridIndexListCounterVulkanBuffers:TVulkanBuffers read fFrustumClusterGridIndexListCounterVulkanBuffers;
property FrustumClusterGridIndexListVulkanBuffers:TVulkanBuffers read fFrustumClusterGridIndexListVulkanBuffers;
property FrustumClusterGridDataVulkanBuffers:TVulkanBuffers read fFrustumClusterGridDataVulkanBuffers;
public
property CascadedShadowMapUniformBuffers:TCascadedShadowMapUniformBuffers read fCascadedShadowMapUniformBuffers;
property CascadedShadowMapVulkanUniformBuffers:TCascadedShadowMapVulkanUniformBuffers read fCascadedShadowMapVulkanUniformBuffers;
public
property CountLockOrderIndependentTransparencyLayers:TpvInt32 read fCountLockOrderIndependentTransparencyLayers;
property LockOrderIndependentTransparentUniformBuffer:TLockOrderIndependentTransparentUniformBuffer read fLockOrderIndependentTransparentUniformBuffer;
property LockOrderIndependentTransparentUniformVulkanBuffer:TpvVulkanBuffer read fLockOrderIndependentTransparentUniformVulkanBuffer;
property LockOrderIndependentTransparencyABufferBuffers:TOrderIndependentTransparencyBuffers read fLockOrderIndependentTransparencyABufferBuffers;
property LockOrderIndependentTransparencyAuxImages:TOrderIndependentTransparencyImages read fLockOrderIndependentTransparencyAuxImages;
property LockOrderIndependentTransparencySpinLockImages:TOrderIndependentTransparencyImages read fLockOrderIndependentTransparencySpinLockImages;
public
property CountLoopOrderIndependentTransparencyLayers:TpvInt32 read fCountLoopOrderIndependentTransparencyLayers;
property LoopOrderIndependentTransparentUniformBuffer:TLoopOrderIndependentTransparentUniformBuffer read fLoopOrderIndependentTransparentUniformBuffer;
property LoopOrderIndependentTransparentUniformVulkanBuffer:TpvVulkanBuffer read fLoopOrderIndependentTransparentUniformVulkanBuffer;
property LoopOrderIndependentTransparencyABufferBuffers:TOrderIndependentTransparencyBuffers read fLoopOrderIndependentTransparencyABufferBuffers;
property LoopOrderIndependentTransparencyZBufferBuffers:TOrderIndependentTransparencyBuffers read fLoopOrderIndependentTransparencyZBufferBuffers;
property LoopOrderIndependentTransparencySBufferBuffers:TOrderIndependentTransparencyBuffers read fLoopOrderIndependentTransparencySBufferBuffers;
public
property ApproximationOrderIndependentTransparentUniformBuffer:TApproximationOrderIndependentTransparentUniformBuffer read fApproximationOrderIndependentTransparentUniformBuffer;
property ApproximationOrderIndependentTransparentUniformVulkanBuffer:TpvVulkanBuffer read fApproximationOrderIndependentTransparentUniformVulkanBuffer;
public
property DeepAndFastApproximateOrderIndependentTransparencyFragmentCounterFragmentDepthsSampleMaskImages:TOrderIndependentTransparencyImages read fDeepAndFastApproximateOrderIndependentTransparencyFragmentCounterImages;
property DeepAndFastApproximateOrderIndependentTransparencyAccumulationImages:TOrderIndependentTransparencyImages read fDeepAndFastApproximateOrderIndependentTransparencyAccumulationImages;
property DeepAndFastApproximateOrderIndependentTransparencyAverageImages:TOrderIndependentTransparencyImages read fDeepAndFastApproximateOrderIndependentTransparencyAverageImages;
property DeepAndFastApproximateOrderIndependentTransparencyBucketImages:TOrderIndependentTransparencyImages read fDeepAndFastApproximateOrderIndependentTransparencyBucketImages;
property DeepAndFastApproximateOrderIndependentTransparencySpinLockImages:TOrderIndependentTransparencyImages read fDeepAndFastApproximateOrderIndependentTransparencySpinLockImages;
public
property DepthMipmappedArray2DImages:TMipmappedArray2DImages read fDepthMipmappedArray2DImages;
property SceneMipmappedArray2DImages:TMipmappedArray2DImages read fSceneMipmappedArray2DImages;
property HUDMipmappedArray2DImages:TMipmappedArray2DImages read fHUDMipmappedArray2DImages;
public
property LuminanceHistogramVulkanBuffers:TLuminanceVulkanBuffers read fLuminanceHistogramVulkanBuffers;
property LuminanceVulkanBuffers:TLuminanceVulkanBuffers read fLuminanceVulkanBuffers;
property MinimumLuminance:TpvScalar read fMinimumLuminance write fMinimumLuminance;
property MaximumLuminance:TpvScalar read fMaximumLuminance write fMaximumLuminance;
public
property TAAHistoryColorImages:TArray2DImages read fTAAHistoryColorImages;
property TAAHistoryDepthImages:TArray2DImages read fTAAHistoryDepthImages;
public
property LastOutputResource:TpvFrameGraph.TPass.TUsedImageResource read fLastOutputResource write fLastOutputResource;
property HUDSize:TpvFrameGraph.TImageSize read fHUDSize;
property HUDRenderPassClass:THUDRenderPassClass read fHUDRenderPassClass write fHUDRenderPassClass;
property HUDRenderPassParent:TObject read fHUDRenderPassParent write fHUDRenderPassParent;
public
property ImageBasedLightingReflectionProbeCubeMaps:TpvScene3DRendererImageBasedLightingReflectionProbeCubeMaps read fImageBasedLightingReflectionProbeCubeMaps;
published
property FrameGraph:TpvFrameGraph read fFrameGraph;
property VirtualReality:TpvVirtualReality read fVirtualReality;
property ExternalImageFormat:TVkFormat read fExternalImageFormat write fExternalImageFormat;
property ExternalOutputImageData:TpvFrameGraph.TExternalImageData read fExternalOutputImageData;
property HasExternalOutputImage:boolean read fHasExternalOutputImage;
property ReflectionProbeWidth:TpvInt32 read fReflectionProbeWidth write fReflectionProbeWidth;
property ReflectionProbeHeight:TpvInt32 read fReflectionProbeHeight write fReflectionProbeHeight;
property ReflectiveShadowMapWidth:TpvInt32 read fReflectionProbeWidth write fReflectiveShadowMapWidth;
property ReflectiveShadowMapHeight:TpvInt32 read fReflectionProbeHeight write fReflectiveShadowMapHeight;
property CascadedShadowMapWidth:TpvInt32 read fCascadedShadowMapWidth write fCascadedShadowMapWidth;
property CascadedShadowMapHeight:TpvInt32 read fCascadedShadowMapHeight write fCascadedShadowMapHeight;
property Left:TpvInt32 read fLeft write fLeft;
property Top:TpvInt32 read fTop write fTop;
property Width:TpvInt32 read fWidth write fWidth;
property Height:TpvInt32 read fHeight write fHeight;
property HUDWidth:TpvInt32 read fHUDWidth write fHUDWidth;
property HUDHeight:TpvInt32 read fHUDHeight write fHUDHeight;
property CountSurfaceViews:TpvInt32 read fCountSurfaceViews write fCountSurfaceViews;
property SurfaceMultiviewMask:TpvUInt32 read fSurfaceMultiviewMask write fSurfaceMultiviewMask;
property FOV:TpvFloat read fFOV write fFOV;
property ZNear:TpvFloat read fZNear write fZNear;
property ZFar:TpvFloat read fZFar write fZFar;
property UseDebugBlit:boolean read fUseDebugBlit write fUseDebugBlit;
end;
implementation
uses PasVulkan.Scene3D.Renderer.Passes.MeshComputePass,
PasVulkan.Scene3D.Renderer.Passes.DepthVelocityNormalsRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DepthMipMapComputePass,
PasVulkan.Scene3D.Renderer.Passes.DepthOfFieldAutoFocusComputePass,
PasVulkan.Scene3D.Renderer.Passes.FrustumClusterGridBuildComputePass,
PasVulkan.Scene3D.Renderer.Passes.FrustumClusterGridAssignComputePass,
PasVulkan.Scene3D.Renderer.Passes.CascadedShadowMapRenderPass,
PasVulkan.Scene3D.Renderer.Passes.CascadedShadowMapResolveRenderPass,
PasVulkan.Scene3D.Renderer.Passes.CascadedShadowMapBlurRenderPass,
PasVulkan.Scene3D.Renderer.Passes.SSAORenderPass,
PasVulkan.Scene3D.Renderer.Passes.SSAOBlurRenderPass,
PasVulkan.Scene3D.Renderer.Passes.ReflectionProbeRenderPass,
PasVulkan.Scene3D.Renderer.Passes.ReflectionProbeMipMapComputePass,
PasVulkan.Scene3D.Renderer.Passes.ReflectionProbeComputePass,
PasVulkan.Scene3D.Renderer.Passes.ForwardRenderPass,
PasVulkan.Scene3D.Renderer.Passes.ForwardResolveRenderPass,
PasVulkan.Scene3D.Renderer.Passes.ForwardRenderMipMapComputePass,
PasVulkan.Scene3D.Renderer.Passes.DirectTransparencyRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DirectTransparencyResolveRenderPass,
PasVulkan.Scene3D.Renderer.Passes.LockOrderIndependentTransparencyClearCustomPass,
PasVulkan.Scene3D.Renderer.Passes.LockOrderIndependentTransparencyRenderPass,
PasVulkan.Scene3D.Renderer.Passes.LockOrderIndependentTransparencyBarrierCustomPass,
PasVulkan.Scene3D.Renderer.Passes.LockOrderIndependentTransparencyResolveRenderPass,
PasVulkan.Scene3D.Renderer.Passes.LoopOrderIndependentTransparencyClearCustomPass,
PasVulkan.Scene3D.Renderer.Passes.LoopOrderIndependentTransparencyPass1RenderPass,
PasVulkan.Scene3D.Renderer.Passes.LoopOrderIndependentTransparencyPass1BarrierCustomPass,
PasVulkan.Scene3D.Renderer.Passes.LoopOrderIndependentTransparencyPass2RenderPass,
PasVulkan.Scene3D.Renderer.Passes.LoopOrderIndependentTransparencyPass2BarrierCustomPass,
PasVulkan.Scene3D.Renderer.Passes.LoopOrderIndependentTransparencyResolveRenderPass,
PasVulkan.Scene3D.Renderer.Passes.MomentBasedOrderIndependentTransparencyAbsorbanceRenderPass,
PasVulkan.Scene3D.Renderer.Passes.MomentBasedOrderIndependentTransparencyTransmittanceRenderPass,
PasVulkan.Scene3D.Renderer.Passes.MomentBasedOrderIndependentTransparencyResolveRenderPass,
PasVulkan.Scene3D.Renderer.Passes.WeightBlendedOrderIndependentTransparencyRenderPass,
PasVulkan.Scene3D.Renderer.Passes.WeightBlendedOrderIndependentTransparencyResolveRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DeepAndFastApproximateOrderIndependentTransparencyClearCustomPass,
PasVulkan.Scene3D.Renderer.Passes.DeepAndFastApproximateOrderIndependentTransparencyRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DeepAndFastApproximateOrderIndependentTransparencyResolveRenderPass,
PasVulkan.Scene3D.Renderer.Passes.OrderIndependentTransparencyResolveRenderPass,
PasVulkan.Scene3D.Renderer.Passes.AntialiasingTAAPreCustomPass,
PasVulkan.Scene3D.Renderer.Passes.AntialiasingTAARenderPass,
PasVulkan.Scene3D.Renderer.Passes.AntialiasingTAAPostCustomPass,
PasVulkan.Scene3D.Renderer.Passes.DepthOfFieldPrepareRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DepthOfFieldBokehComputePass,
PasVulkan.Scene3D.Renderer.Passes.DepthOfFieldPrefilterRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DepthOfFieldBlurRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DepthOfFieldBruteforceRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DepthOfFieldPostBlurRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DepthOfFieldCombineRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DepthOfFieldGatherPass1RenderPass,
PasVulkan.Scene3D.Renderer.Passes.DepthOfFieldGatherPass2RenderPass,
PasVulkan.Scene3D.Renderer.Passes.DepthOfFieldResolveRenderPass,
PasVulkan.Scene3D.Renderer.Passes.LensDownsampleComputePass,
PasVulkan.Scene3D.Renderer.Passes.LensUpsampleComputePass,
PasVulkan.Scene3D.Renderer.Passes.LensResolveRenderPass,
PasVulkan.Scene3D.Renderer.Passes.LuminanceHistogramComputePass,
PasVulkan.Scene3D.Renderer.Passes.LuminanceAverageComputePass,
PasVulkan.Scene3D.Renderer.Passes.TonemappingRenderPass,
PasVulkan.Scene3D.Renderer.Passes.AntialiasingNoneRenderPass,
PasVulkan.Scene3D.Renderer.Passes.AntialiasingDSAARenderPass,
PasVulkan.Scene3D.Renderer.Passes.AntialiasingFXAARenderPass,
PasVulkan.Scene3D.Renderer.Passes.AntialiasingSMAAEdgesRenderPass,
PasVulkan.Scene3D.Renderer.Passes.AntialiasingSMAAWeightsRenderPass,
PasVulkan.Scene3D.Renderer.Passes.AntialiasingSMAABlendRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DitheringRenderPass,
PasVulkan.Scene3D.Renderer.Passes.HUDMipMapCustomPass,
PasVulkan.Scene3D.Renderer.Passes.ContentProjectionRenderPass,
PasVulkan.Scene3D.Renderer.Passes.DebugBlitRenderPass,
PasVulkan.Scene3D.Renderer.Passes.BlitRenderPass;
type TpvScene3DRendererInstancePasses=class
private
fMeshComputePass:TpvScene3DRendererPassesMeshComputePass;
fDepthVelocityNormalsRenderPass:TpvScene3DRendererPassesDepthVelocityNormalsRenderPass;
fDepthMipMapComputePass:TpvScene3DRendererPassesDepthMipMapComputePass;
fDepthOfFieldAutoFocusComputePass:TpvScene3DRendererPassesDepthOfFieldAutoFocusComputePass;
fFrustumClusterGridBuildComputePass:TpvScene3DRendererPassesFrustumClusterGridBuildComputePass;
fFrustumClusterGridAssignComputePass:TpvScene3DRendererPassesFrustumClusterGridAssignComputePass;
fCascadedShadowMapRenderPass:TpvScene3DRendererPassesCascadedShadowMapRenderPass;
fCascadedShadowMapResolveRenderPass:TpvScene3DRendererPassesCascadedShadowMapResolveRenderPass;
fCascadedShadowMapBlurRenderPasses:array[0..1] of TpvScene3DRendererPassesCascadedShadowMapBlurRenderPass;
fSSAORenderPass:TpvScene3DRendererPassesSSAORenderPass;
fSSAOBlurRenderPasses:array[0..1] of TpvScene3DRendererPassesSSAOBlurRenderPass;
fReflectionProbeRenderPass:TpvScene3DRendererPassesReflectionProbeRenderPass;
fReflectionProbeMipMapComputePass:TpvScene3DRendererPassesReflectionProbeMipMapComputePass;
fReflectionProbeComputePassGGX:TpvScene3DRendererPassesReflectionProbeComputePass;
fReflectionProbeComputePassCharlie:TpvScene3DRendererPassesReflectionProbeComputePass;
fReflectionProbeComputePassLambertian:TpvScene3DRendererPassesReflectionProbeComputePass;
fForwardRenderPass:TpvScene3DRendererPassesForwardRenderPass;
fForwardResolveRenderPass:TpvScene3DRendererPassesForwardResolveRenderPass;
fForwardRenderMipMapComputePass:TpvScene3DRendererPassesForwardRenderMipMapComputePass;
fDirectTransparencyRenderPass:TpvScene3DRendererPassesDirectTransparencyRenderPass;
fDirectTransparencyResolveRenderPass:TpvScene3DRendererPassesDirectTransparencyResolveRenderPass;
fLockOrderIndependentTransparencyClearCustomPass:TpvScene3DRendererPassesLockOrderIndependentTransparencyClearCustomPass;
fLockOrderIndependentTransparencyRenderPass:TpvScene3DRendererPassesLockOrderIndependentTransparencyRenderPass;
fLockOrderIndependentTransparencyBarrierCustomPass:TpvScene3DRendererPassesLockOrderIndependentTransparencyBarrierCustomPass;
fLockOrderIndependentTransparencyResolveRenderPass:TpvScene3DRendererPassesLockOrderIndependentTransparencyResolveRenderPass;
fLoopOrderIndependentTransparencyClearCustomPass:TpvScene3DRendererPassesLoopOrderIndependentTransparencyClearCustomPass;
fLoopOrderIndependentTransparencyPass1RenderPass:TpvScene3DRendererPassesLoopOrderIndependentTransparencyPass1RenderPass;
fLoopOrderIndependentTransparencyPass1BarrierCustomPass:TpvScene3DRendererPassesLoopOrderIndependentTransparencyPass1BarrierCustomPass;
fLoopOrderIndependentTransparencyPass2RenderPass:TpvScene3DRendererPassesLoopOrderIndependentTransparencyPass2RenderPass;
fLoopOrderIndependentTransparencyPass2BarrierCustomPass:TpvScene3DRendererPassesLoopOrderIndependentTransparencyPass2BarrierCustomPass;
fLoopOrderIndependentTransparencyResolveRenderPass:TpvScene3DRendererPassesLoopOrderIndependentTransparencyResolveRenderPass;
fWeightBlendedOrderIndependentTransparencyRenderPass:TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass;
fWeightBlendedOrderIndependentTransparencyResolveRenderPass:TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyResolveRenderPass;
fMomentBasedOrderIndependentTransparencyAbsorbanceRenderPass:TpvScene3DRendererPassesMomentBasedOrderIndependentTransparencyAbsorbanceRenderPass;
fMomentBasedOrderIndependentTransparencyTransmittanceRenderPass:TpvScene3DRendererPassesMomentBasedOrderIndependentTransparencyTransmittanceRenderPass;
fMomentBasedOrderIndependentTransparencyResolveRenderPass:TpvScene3DRendererPassesMomentBasedOrderIndependentTransparencyResolveRenderPass;
fDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass:TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass;
fDeepAndFastApproximateOrderIndependentTransparencyRenderPass:TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyRenderPass;
fDeepAndFastApproximateOrderIndependentTransparencyResolveRenderPass:TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyResolveRenderPass;
fOrderIndependentTransparencyResolveRenderPass:TpvScene3DRendererPassesOrderIndependentTransparencyResolveRenderPass;
fAntialiasingTAAPreCustomPass:TpvScene3DRendererPassesAntialiasingTAAPreCustomPass;
fAntialiasingTAARenderPass:TpvScene3DRendererPassesAntialiasingTAARenderPass;
fAntialiasingTAAPostCustomPass:TpvScene3DRendererPassesAntialiasingTAAPostCustomPass;
fDepthOfFieldPrepareRenderPass:TpvScene3DRendererPassesDepthOfFieldPrepareRenderPass;
fDepthOfFieldBokehComputePass:TpvScene3DRendererPassesDepthOfFieldBokehComputePass;
fDepthOfFieldPrefilterRenderPass:TpvScene3DRendererPassesDepthOfFieldPrefilterRenderPass;
fDepthOfFieldBlurRenderPass:TpvScene3DRendererPassesDepthOfFieldBlurRenderPass;
fDepthOfFieldBruteforceRenderPass:TpvScene3DRendererPassesDepthOfFieldBruteforceRenderPass;
fDepthOfFieldPostBlurRenderPass:TpvScene3DRendererPassesDepthOfFieldPostBlurRenderPass;
fDepthOfFieldCombineRenderPass:TpvScene3DRendererPassesDepthOfFieldCombineRenderPass;
fDepthOfFieldGatherPass1RenderPass:TpvScene3DRendererPassesDepthOfFieldGatherPass1RenderPass;
fDepthOfFieldGatherPass2RenderPass:TpvScene3DRendererPassesDepthOfFieldGatherPass2RenderPass;
fDepthOfFieldResolveRenderPass:TpvScene3DRendererPassesDepthOfFieldResolveRenderPass;
fLensDownsampleComputePass:TpvScene3DRendererPassesLensDownsampleComputePass;
fLensUpsampleComputePass:TpvScene3DRendererPassesLensUpsampleComputePass;
fLensResolveRenderPass:TpvScene3DRendererPassesLensResolveRenderPass;
fLuminanceHistogramComputePass:TpvScene3DRendererPassesLuminanceHistogramComputePass;
fLuminanceAverageComputePass:TpvScene3DRendererPassesLuminanceAverageComputePass;
fTonemappingRenderPass:TpvScene3DRendererPassesTonemappingRenderPass;
fAntialiasingNoneRenderPass:TpvScene3DRendererPassesAntialiasingNoneRenderPass;
fAntialiasingDSAARenderPass:TpvScene3DRendererPassesAntialiasingDSAARenderPass;
fAntialiasingFXAARenderPass:TpvScene3DRendererPassesAntialiasingFXAARenderPass;
fAntialiasingSMAAEdgesRenderPass:TpvScene3DRendererPassesAntialiasingSMAAEdgesRenderPass;
fAntialiasingSMAAWeightsRenderPass:TpvScene3DRendererPassesAntialiasingSMAAWeightsRenderPass;
fAntialiasingSMAABlendRenderPass:TpvScene3DRendererPassesAntialiasingSMAABlendRenderPass;
fDitheringRenderPass:TpvScene3DRendererPassesDitheringRenderPass;
fHUDRenderPass:TpvScene3DRendererInstance.THUDRenderPass;
fHUDMipMapCustomPass:TpvScene3DRendererPassesHUDMipMapCustomPass;
fContentProjectionRenderPass:TpvScene3DRendererPassesContentProjectionRenderPass;
fDebugBlitRenderPass:TpvScene3DRendererPassesDebugBlitRenderPass;
fBlitRenderPass:TpvScene3DRendererPassesBlitRenderPass;
end;
const CountJitterOffsets=128;
JitterOffsetMask=CountJitterOffsets-1;
var JitterOffsets:array[0..CountJitterOffsets-1] of TpvVector2;
{ TpvScene3DRendererInstance.TMeshFragmentSpecializationConstants }
procedure TpvScene3DRendererInstance.TMeshFragmentSpecializationConstants.SetPipelineShaderStage(const aVulkanPipelineShaderStage:TpvVulkanPipelineShaderStage);
begin
{aVulkanPipelineShaderStage.AddSpecializationMapEntry(0,TVkPtrUInt(pointer(@UseReversedZ))-TVkPtrUInt(pointer(@self)),SizeOf(TVkBool32));
aVulkanPipelineShaderStage.AddSpecializationDataFromMemory(@self,SizeOf(TpvScene3DRendererInstance.TMeshFragmentSpecializationConstants),true);//}
end;
{ TpvScene3DRendererInstance.TCascadedShadowMapBuilder }
constructor TpvScene3DRendererInstance.TCascadedShadowMapBuilder.Create(const aInstance:TpvScene3DRendererInstance);
begin
inherited Create;
fInstance:=aInstance;
end;
destructor TpvScene3DRendererInstance.TCascadedShadowMapBuilder.Destroy;
begin
inherited Destroy;
end;
procedure TpvScene3DRendererInstance.TCascadedShadowMapBuilder.SnapLightFrustum(var aScale,aOffset:TpvVector2;const aMatrix:TpvMatrix4x4;const aWorldOrigin:TpvVector3;const aShadowMapResolution:TpvVector2);
var Resolution,LightSpaceOrigin:TpvVector2;
begin
Resolution:=aShadowMapResolution*2.0;
aOffset:=aOffset-TpvVector2.InlineableCreate(Modulo(aOffset.x,Resolution.x),Modulo(aOffset.y,Resolution.y));
LightSpaceOrigin:=aMatrix.MulHomogen(aWorldOrigin).xy*aScale;
aOffset:=aOffset-TpvVector2.InlineableCreate(Modulo(LightSpaceOrigin.x,Resolution.x),Modulo(LightSpaceOrigin.y,Resolution.y));
end;
procedure TpvScene3DRendererInstance.TCascadedShadowMapBuilder.Calculate(const aInFlightFrameIndex:TpvInt32);
var CascadedShadowMapIndex,Index,ViewIndex:TpvSizeInt;
CascadedShadowMaps:PCascadedShadowMaps;
CascadedShadowMap:PCascadedShadowMap;
CascadedShadowMapSplitLambda,
CascadedShadowMapSplitOverlap,
MinZ,MaxZ,
Ratio,SplitValue,UniformSplitValue,LogSplitValue,
FadeStartValue,LastValue,Value,TexelSizeAtOneMeter,
zNear,zFar,RealZNear,RealZFar:TpvScalar;
DoNeedRefitNearFarPlanes:boolean;
InFlightFrameState:PInFlightFrameState;
Renderer:TpvScene3DRenderer;
FrustumCenterX,FrustumCenterY,FrustumCenterZ:TpvDouble;
FrustumRadius:TpvScalar;
begin
Renderer:=fInstance.Renderer;
fSceneWorldSpaceBoundingBox:=Renderer.Scene3D.InFlightFrameBoundingBoxes[aInFlightFrameIndex];
fSceneWorldSpaceSphere:=TpvSphere.CreateFromAABB(fSceneWorldSpaceBoundingBox);
InFlightFrameState:=@fInstance.fInFlightFrameStates[aInFlightFrameIndex];
if IsInfinite(fInstance.fZFar) then begin
RealZNear:=0.1;
RealZFar:=16.0;
for Index:=0 to fInstance.fCountRealViews-1 do begin
fViewMatrix:=fInstance.fViews.Items[Index].ViewMatrix.SimpleInverse;
if fSceneWorldSpaceSphere.Contains(fViewMatrix.Translation.xyz) then begin
if fSceneWorldSpaceSphere.RayIntersection(fViewMatrix.Translation.xyz,-fViewMatrix.Forwards.xyz,Value) then begin
Value:=Value*2.0;
end else begin
Value:=fSceneWorldSpaceSphere.Radius;
end;
end else begin
Value:=fSceneWorldSpaceSphere.Center.DistanceTo(fViewMatrix.Translation.xyz)+fSceneWorldSpaceSphere.Radius;
end;
RealZFar:=Max(RealZFar,Value);
end;
{ RealZNear:=0.1;
RealZFar:=1024.0;}
zNear:=RealZNear;
zFar:=RealZFar;
DoNeedRefitNearFarPlanes:=true;
end else begin
zNear:=abs(fInstance.fZNear);
zFar:=abs(fInstance.fZFar);
RealZNear:=zNear;
RealZFar:=zFar;
DoNeedRefitNearFarPlanes:=fInstance.fZFar<0.0;
end;
InFlightFrameState^.ZNear:=Min(RealZNear,1e-4);
InFlightFrameState^.ZFar:=RealZFar;
CascadedShadowMapSplitLambda:=0.95;
CascadedShadowMapSplitOverlap:=0.1;
CascadedShadowMaps:=@fInstance.fInFlightFrameCascadedShadowMaps[aInFlightFrameIndex];
CascadedShadowMaps^[0].SplitDepths.x:=Min(zNear,RealZNear);
Ratio:=zFar/zNear;
LastValue:=0.0;
for CascadedShadowMapIndex:=1 to CountCascadedShadowMapCascades-1 do begin
SplitValue:=CascadedShadowMapIndex/CountCascadedShadowMapCascades;
UniformSplitValue:=((1.0-SplitValue)*zNear)+(SplitValue*zFar);
LogSplitValue:=zNear*power(Ratio,SplitValue);
Value:=((1.0-CascadedShadowMapSplitLambda)*UniformSplitValue)+(CascadedShadowMapSplitLambda*LogSplitValue);
FadeStartValue:=Min(Max((Value*(1.0-CascadedShadowMapSplitOverlap))+(LastValue*CascadedShadowMapSplitOverlap),Min(zNear,RealZNear)),Max(zFar,RealZFar));
LastValue:=Value;
CascadedShadowMaps^[CascadedShadowMapIndex].SplitDepths.x:=Min(Max(FadeStartValue,Min(zNear,RealZNear)),Max(zFar,RealZFar));
CascadedShadowMaps^[CascadedShadowMapIndex-1].SplitDepths.y:=Min(Max(Value,Min(zNear,RealZNear)),Max(zFar,RealZFar));
end;
CascadedShadowMaps^[CountCascadedShadowMapCascades-1].SplitDepths.y:=Max(ZFar,RealZFar);
for ViewIndex:=0 to fInstance.fCountRealViews-1 do begin
fProjectionMatrix:=fInstance.fViews.Items[ViewIndex].ProjectionMatrix;
if DoNeedRefitNearFarPlanes then begin
fProjectionMatrix[2,2]:=RealZFar/(RealZNear-RealZFar);
fProjectionMatrix[3,2]:=(-(RealZNear*RealZFar))/(RealZFar-RealZNear);
end;
fInverseViewProjectionMatrices[ViewIndex]:=(fInstance.fViews.Items[ViewIndex].ViewMatrix*fProjectionMatrix).Inverse;
end;
fLightForwardVector:=-Renderer.Scene3D.PrimaryShadowMapLightDirection.xyz.Normalize;
//fLightForwardVector:=-Renderer.SkyCubeMap.LightDirection.xyz.Normalize;
fLightSideVector:=fLightForwardVector.Perpendicular;
{fLightSideVector:=TpvVector3.InlineableCreate(-fViews.Items[0].ViewMatrix.RawComponents[0,2],
-fViews.Items[0].ViewMatrix.RawComponents[1,2],
-fViews.Items[0].ViewMatrix.RawComponents[2,2]).Normalize;
if abs(fLightForwardVector.Dot(fLightSideVector))>0.5 then begin
if abs(fLightForwardVector.Dot(TpvVector3.YAxis))<0.9 then begin
fLightSideVector:=TpvVector3.YAxis;
end else begin
fLightSideVector:=TpvVector3.ZAxis;
end;
end;}
fLightUpVector:=(fLightForwardVector.Cross(fLightSideVector)).Normalize;
fLightSideVector:=(fLightUpVector.Cross(fLightForwardVector)).Normalize;
fLightViewMatrix.RawComponents[0,0]:=fLightSideVector.x;
fLightViewMatrix.RawComponents[0,1]:=fLightUpVector.x;
fLightViewMatrix.RawComponents[0,2]:=fLightForwardVector.x;
fLightViewMatrix.RawComponents[0,3]:=0.0;
fLightViewMatrix.RawComponents[1,0]:=fLightSideVector.y;
fLightViewMatrix.RawComponents[1,1]:=fLightUpVector.y;
fLightViewMatrix.RawComponents[1,2]:=fLightForwardVector.y;
fLightViewMatrix.RawComponents[1,3]:=0.0;
fLightViewMatrix.RawComponents[2,0]:=fLightSideVector.z;
fLightViewMatrix.RawComponents[2,1]:=fLightUpVector.z;
fLightViewMatrix.RawComponents[2,2]:=fLightForwardVector.z;
fLightViewMatrix.RawComponents[2,3]:=0.0;
fLightViewMatrix.RawComponents[3,0]:=0.0;
fLightViewMatrix.RawComponents[3,1]:=0.0;
fLightViewMatrix.RawComponents[3,2]:=0.0;
fLightViewMatrix.RawComponents[3,3]:=1.0;
for ViewIndex:=0 to fInstance.fCountRealViews-1 do begin
for Index:=0 to 7 do begin
fWorldSpaceFrustumCorners[ViewIndex,Index]:=fInverseViewProjectionMatrices[ViewIndex].MulHomogen(TpvVector4.InlineableCreate(FrustumCorners[Index],1.0)).xyz;
end;
end;
for CascadedShadowMapIndex:=0 to CountCascadedShadowMapCascades-1 do begin
CascadedShadowMap:=@CascadedShadowMaps^[CascadedShadowMapIndex];
MinZ:=CascadedShadowMap^.SplitDepths.x;
MaxZ:=CascadedShadowMap^.SplitDepths.y;
for ViewIndex:=0 to fInstance.fCountRealViews-1 do begin
for Index:=0 to 3 do begin
fTemporaryFrustumCorners[ViewIndex,Index]:=fWorldSpaceFrustumCorners[ViewIndex,Index].Lerp(fWorldSpaceFrustumCorners[ViewIndex,Index+4],(MinZ-RealZNear)/(RealZFar-RealZNear));
fTemporaryFrustumCorners[ViewIndex,Index+4]:=fWorldSpaceFrustumCorners[ViewIndex,Index].Lerp(fWorldSpaceFrustumCorners[ViewIndex,Index+4],(MaxZ-RealZNear)/(RealZFar-RealZNear));
end;
end;
FrustumCenterX:=0.0;
FrustumCenterY:=0.0;
FrustumCenterZ:=0.0;
for ViewIndex:=0 to fInstance.fCountRealViews-1 do begin
for Index:=0 to 7 do begin
FrustumCenterX:=FrustumCenterX+fTemporaryFrustumCorners[ViewIndex,Index].x;
FrustumCenterY:=FrustumCenterY+fTemporaryFrustumCorners[ViewIndex,Index].y;
FrustumCenterZ:=FrustumCenterZ+fTemporaryFrustumCorners[ViewIndex,Index].z;
end;
end;
fFrustumCenter.x:=FrustumCenterX/(8.0*fInstance.fCountRealViews);
fFrustumCenter.y:=FrustumCenterY/(8.0*fInstance.fCountRealViews);
fFrustumCenter.z:=FrustumCenterZ/(8.0*fInstance.fCountRealViews);
FrustumRadius:=0.0;
for ViewIndex:=0 to fInstance.fCountRealViews-1 do begin
for Index:=0 to 7 do begin
FrustumRadius:=Max(FrustumRadius,fTemporaryFrustumCorners[ViewIndex,Index].DistanceTo(fFrustumCenter));
end;
end;
FrustumRadius:=ceil(FrustumRadius*16.0)/16.0;
fFrustumAABB.Min:=TpvVector3.InlineableCreate(-FrustumRadius,-FrustumRadius,-FrustumRadius);
fFrustumAABB.Max:=TpvVector3.InlineableCreate(FrustumRadius,FrustumRadius,FrustumRadius);
fOrigin:=fFrustumCenter-(fLightForwardVector*fFrustumAABB.Min.z);
fLightViewMatrix.RawComponents[3,0]:=-fLightSideVector.Dot(fOrigin);
fLightViewMatrix.RawComponents[3,1]:=-fLightUpVector.Dot(fOrigin);
fLightViewMatrix.RawComponents[3,2]:=-fLightForwardVector.Dot(fOrigin);
fLightProjectionMatrix:=TpvMatrix4x4.CreateOrthoRightHandedZeroToOne(fFrustumAABB.Min.x,
fFrustumAABB.Max.x,
fFrustumAABB.Min.y,
fFrustumAABB.Max.y,
CascadeNearPlaneOffset,
(fFrustumAABB.Max.z-fFrustumAABB.Min.z)+CascadeFarPlaneOffset);
fLightViewProjectionMatrix:=fLightViewMatrix*fLightProjectionMatrix;
//fShadowOrigin:=(fLightViewProjectionMatrix.MulHomogen(TpvVector3.Origin)).xy*TpvVector2.InlineableCreate(fInstance.CascadedShadowMapWidth*0.5,fInstance.CascadedShadowMapHeight*0.5);
fShadowOrigin:=(fLightViewProjectionMatrix*TpvVector4.InlineableCreate(0.0,0.0,0.0,1.0)).xy*TpvVector2.InlineableCreate(fInstance.fCascadedShadowMapWidth*0.5,fInstance.fCascadedShadowMapHeight*0.5);
fRoundedOrigin.x:=round(fShadowOrigin.x);
fRoundedOrigin.y:=round(fShadowOrigin.y);
fRoundOffset:=(fRoundedOrigin-fShadowOrigin)*TpvVector2.InlineableCreate(2.0/fInstance.fCascadedShadowMapWidth,2.0/fInstance.fCascadedShadowMapHeight);
fLightProjectionMatrix[3,0]:=fLightProjectionMatrix[3,0]+fRoundOffset.x;
fLightProjectionMatrix[3,1]:=fLightProjectionMatrix[3,1]+fRoundOffset.y;
fLightViewProjectionMatrix:=fLightViewMatrix*fLightProjectionMatrix;
if IsNaN(fLightViewProjectionMatrix.m00) then begin
CascadedShadowMap^.View.ProjectionMatrix:=fLightProjectionMatrix;
end;
CascadedShadowMap^.View.ViewMatrix:=fLightViewMatrix;
CascadedShadowMap^.View.ProjectionMatrix:=fLightProjectionMatrix;
CascadedShadowMap^.View.InverseViewMatrix:=fLightViewMatrix.Inverse;
CascadedShadowMap^.View.InverseProjectionMatrix:=fLightProjectionMatrix.Inverse;
CascadedShadowMap^.CombinedMatrix:=fLightViewProjectionMatrix;
fInverseLightViewProjectionMatrix:=fLightViewProjectionMatrix.Inverse;
TexelSizeAtOneMeter:=Max(TpvVector3.InlineableCreate(fInverseLightViewProjectionMatrix[0,0],fInverseLightViewProjectionMatrix[0,1],fInverseLightViewProjectionMatrix[0,2]).Length/fInstance.CascadedShadowMapWidth,
TpvVector3.InlineableCreate(fInverseLightViewProjectionMatrix[1,0],fInverseLightViewProjectionMatrix[1,1],fInverseLightViewProjectionMatrix[1,2]).Length/fInstance.CascadedShadowMapHeight);
CascadedShadowMap^.Scales.x:=TexelSizeAtOneMeter;
CascadedShadowMap^.Scales.y:=Max(4.0,(1.0*0.02)/TexelSizeAtOneMeter);
fInstance.fCascadedShadowMapUniformBuffers[aInFlightFrameIndex].Matrices[CascadedShadowMapIndex]:=fLightViewProjectionMatrix;
fInstance.fCascadedShadowMapUniformBuffers[aInFlightFrameIndex].SplitDepthsScales[CascadedShadowMapIndex]:=TpvVector4.Create(CascadedShadowMap^.SplitDepths,CascadedShadowMap^.Scales.x,CascadedShadowMap^.Scales.y);
fInstance.fCascadedShadowMapUniformBuffers[aInFlightFrameIndex].ConstantBiasNormalBiasSlopeBiasClamp[CascadedShadowMapIndex]:=TpvVector4.Create(1e-3,1.0*TexelSizeAtOneMeter,5.0*TexelSizeAtOneMeter,0.0);
end;
fInstance.fCascadedShadowMapUniformBuffers[aInFlightFrameIndex].MetaData[0]:=TpvUInt32(Renderer.ShadowMode);
fInstance.fCascadedShadowMapUniformBuffers[aInFlightFrameIndex].MetaData[1]:=0;
fInstance.fCascadedShadowMapUniformBuffers[aInFlightFrameIndex].MetaData[2]:=0;
fInstance.fCascadedShadowMapUniformBuffers[aInFlightFrameIndex].MetaData[3]:=0;
InFlightFrameState^.CascadedShadowMapViewIndex:={Renderer.Scene3D}fInstance.AddView(CascadedShadowMaps^[0].View);
for CascadedShadowMapIndex:=1 to CountCascadedShadowMapCascades-1 do begin
{Renderer.Scene3D}fInstance.AddView(CascadedShadowMaps^[CascadedShadowMapIndex].View);
end;
InFlightFrameState^.CountCascadedShadowMapViews:=CountCascadedShadowMapCascades;
end;
{ TpvScene3DRendererInstance.THUDRenderPass }
constructor TpvScene3DRendererInstance.THUDRenderPass.Create(const aFrameGraph:TpvFrameGraph;const aRendererInstance:TpvScene3DRendererInstance;const aParent:TObject);
begin
inherited Create(aFrameGraph);
fRendererInstance:=aRendererInstance;
fParent:=aParent;
end;
{ TpvScene3DRendererInstance }
constructor TpvScene3DRendererInstance.Create(const aParent:TpvScene3DRendererBaseObject;const aVirtualReality:TpvVirtualReality;const aExternalImageFormat:TVkFormat);
var InFlightFrameIndex:TpvSizeInt;
begin
inherited Create(aParent);
fPasses:=TpvScene3DRendererInstancePasses.Create;
fExternalImageFormat:=aExternalImageFormat;
fVirtualReality:=aVirtualReality;
fCameraPreset:=TpvScene3DRendererCameraPreset.Create;
fUseDebugBlit:=false;
fFrustumClusterGridSizeX:=16;
fFrustumClusterGridSizeY:=16;
fFrustumClusterGridSizeZ:=16;
if assigned(fVirtualReality) then begin
fFOV:=fVirtualReality.FOV;
fZNear:=fVirtualReality.ZNear;
fZFar:=fVirtualReality.ZFar;
fCountSurfaceViews:=fVirtualReality.CountImages;
fSurfaceMultiviewMask:=fVirtualReality.MultiviewMask;
end else begin
fFOV:=53.13010235415598;
fZNear:=-0.01;
fZFar:=-Infinity;
fCountSurfaceViews:=1;
fSurfaceMultiviewMask:=1 shl 0;
end;
fHUDRenderPassClass:=nil;
fHUDRenderPassParent:=nil;
fReflectionProbeWidth:=256;
fReflectionProbeHeight:=256;
fReflectiveShadowMapWidth:=2048;
fReflectiveShadowMapHeight:=2048;
if Renderer.ShadowMode=TpvScene3DRendererShadowMode.None then begin
fCascadedShadowMapWidth:=64;
fCascadedShadowMapHeight:=64;
end else begin
fCascadedShadowMapWidth:=Renderer.ShadowMapSize;
fCascadedShadowMapHeight:=Renderer.ShadowMapSize;
end;
fCameraViewMatrix:=TpvMatrix4x4.Identity;
fPointerToCameraViewMatrix:=@fCameraViewMatrix;
fPointerToInFlightFrameStates:=@fInFlightFrameStates;
fMinimumLuminance:=0.0;
fMaximumLuminance:=16777216.0;
fFrameGraph:=TpvFrameGraph.Create(Renderer.VulkanDevice,Renderer.CountInFlightFrames);
fFrameGraph.CanDoParallelProcessing:=false;
fFrameGraph.SurfaceIsSwapchain:=(fExternalImageFormat=VK_FORMAT_UNDEFINED) and not assigned(fVirtualReality);
if fFrameGraph.SurfaceIsSwapchain then begin
fExternalOutputImageData:=nil;
end else begin
fExternalOutputImageData:=TpvFrameGraph.TExternalImageData.Create(fFrameGraph);
end;
fHasExternalOutputImage:=(fExternalImageFormat<>VK_FORMAT_UNDEFINED) and not assigned(fVirtualReality);
fFrameGraph.DefaultResourceInstanceType:=TpvFrameGraph.TResourceInstanceType.InstancePerInFlightFrame;
FillChar(fInFlightFrameStates,SizeOf(TInFlightFrameStates),#0);
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
fVulkanRenderSemaphores[InFlightFrameIndex]:=TpvVulkanSemaphore.Create(Renderer.VulkanDevice);
end;
FillChar(fCascadedShadowMapVulkanUniformBuffers,SizeOf(TCascadedShadowMapVulkanUniformBuffers),#0);
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
fCascadedShadowMapVulkanUniformBuffers[InFlightFrameIndex]:=TpvVulkanBuffer.Create(Renderer.VulkanDevice,
SizeOf(TCascadedShadowMapUniformBuffer),
TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT),
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
0,
0,
0,
0,
0,
0,
[TpvVulkanBufferFlag.PersistentMapped]);
end;
case Renderer.TransparencyMode of
TpvScene3DRendererTransparencyMode.SPINLOCKOIT,
TpvScene3DRendererTransparencyMode.INTERLOCKOIT:begin
fLockOrderIndependentTransparentUniformVulkanBuffer:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
SizeOf(TLockOrderIndependentTransparentUniformBuffer),
TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT),
0,
0,
0,
0,
[]);
end;
TpvScene3DRendererTransparencyMode.LOOPOIT:begin
fLoopOrderIndependentTransparentUniformVulkanBuffer:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
SizeOf(TLoopOrderIndependentTransparentUniformBuffer),
TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT),
0,
0,
0,
0,
[]);
end;
TpvScene3DRendererTransparencyMode.WBOIT,
TpvScene3DRendererTransparencyMode.MBOIT:begin
fApproximationOrderIndependentTransparentUniformVulkanBuffer:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
SizeOf(TApproximationOrderIndependentTransparentUniformBuffer),
TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT),
0,
0,
0,
0,
[]);
end;
else begin
end;
end;
fLeft:=0;
fTop:=0;
fWidth:=1024;
fHeight:=768;
fMeshFragmentSpecializationConstants.UseReversedZ:=IfThen(fZFar<0.0,VK_TRUE,VK_FALSE);
fCascadedShadowMapBuilder:=TCascadedShadowMapBuilder.Create(self);
fImageBasedLightingReflectionProbeCubeMaps:=nil;
end;
destructor TpvScene3DRendererInstance.Destroy;
var InFlightFrameIndex:TpvSizeInt;
begin
FreeAndNil(fFrameGraph);
FreeAndNil(fCascadedShadowMapBuilder);
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
FreeAndNil(fVulkanRenderSemaphores[InFlightFrameIndex]);
end;
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
FreeAndNil(fCascadedShadowMapVulkanUniformBuffers[InFlightFrameIndex]);
end;
FreeAndNil(fImageBasedLightingReflectionProbeCubeMaps);
case Renderer.TransparencyMode of
TpvScene3DRendererTransparencyMode.SPINLOCKOIT,
TpvScene3DRendererTransparencyMode.INTERLOCKOIT:begin
FreeAndNil(fLockOrderIndependentTransparentUniformVulkanBuffer);
end;
TpvScene3DRendererTransparencyMode.LOOPOIT:begin
FreeAndNil(fLoopOrderIndependentTransparentUniformVulkanBuffer);
end;
TpvScene3DRendererTransparencyMode.WBOIT,
TpvScene3DRendererTransparencyMode.MBOIT:begin
FreeAndNil(fApproximationOrderIndependentTransparentUniformVulkanBuffer);
end;
else begin
end;
end;
FreeAndNil(fPasses);
FreeAndNil(fCameraPreset);
inherited Destroy;
end;
procedure TpvScene3DRendererInstance.Prepare;
begin
if assigned(fVirtualReality) then begin
fFrameGraph.AddImageResourceType('resourcetype_output_color',
true,
fVirtualReality.ImageFormat,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT),
1
);
fHUDSize:=TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.Absolute,Renderer.VirtualRealityHUDWidth,Renderer.VirtualRealityHUDHeight);
end else begin
fFrameGraph.AddImageResourceType('resourcetype_output_color',
true,
TVkFormat(VK_FORMAT_UNDEFINED),
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Surface,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT),
1
);
fHUDSize:=TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0);
end;
fFrameGraph.AddImageResourceType('resourcetype_hud_color',
false,
VK_FORMAT_R8G8B8A8_SRGB,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
fHUDSize,
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_TRANSFER_SRC_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_hud_depth',
false,
VK_FORMAT_D32_SFLOAT{pvApplication.VulkanDepthImageFormat},
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.From(VK_FORMAT_D32_SFLOAT{pvApplication.VulkanDepthImageFormat}),
fHUDSize,
TVkImageUsageFlags(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_msaa_color',
false,
VK_FORMAT_R16G16B16A16_SFLOAT,
Renderer.SurfaceSampleCountFlagBits,
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_msaa_color_optimized_non_alpha',
false,
Renderer.OptimizedNonAlphaFormat,
Renderer.SurfaceSampleCountFlagBits,
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_msaa_depth',
false,
VK_FORMAT_D32_SFLOAT{pvApplication.VulkanDepthImageFormat},
Renderer.SurfaceSampleCountFlagBits,
TpvFrameGraph.TImageType.From(VK_FORMAT_D32_SFLOAT{pvApplication.VulkanDepthImageFormat}),
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_msaa_predepth',
false,
VK_FORMAT_R32_SFLOAT,
Renderer.SurfaceSampleCountFlagBits,
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_msaa_velocity',
false,
VK_FORMAT_R32G32_SFLOAT,
Renderer.SurfaceSampleCountFlagBits,
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_msaa_normals',
false,
VK_FORMAT_A2B10G10R10_UNORM_PACK32,
Renderer.SurfaceSampleCountFlagBits,
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_reflectionprobe_color',
false,
// VK_FORMAT_R8G8B8A8_SRGB,
VK_FORMAT_R16G16B16A16_SFLOAT,
VK_SAMPLE_COUNT_1_BIT,
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.Absolute,ReflectionProbeWidth,ReflectionProbeHeight,1.0,6),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_reflectionprobe_optimized_non_alpha',
false,
Renderer.OptimizedNonAlphaFormat,
VK_SAMPLE_COUNT_1_BIT,
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.Absolute,ReflectionProbeWidth,ReflectionProbeHeight,1.0,6),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_reflectionprobe_depth',
false,
VK_FORMAT_D32_SFLOAT{pvApplication.VulkanDepthImageFormat},
VK_SAMPLE_COUNT_1_BIT,
TpvFrameGraph.TImageType.From(VK_FORMAT_D32_SFLOAT{pvApplication.VulkanDepthImageFormat}),
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.Absolute,ReflectionProbeWidth,ReflectionProbeHeight,1.0,6),
TVkImageUsageFlags(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_mboit_data',
false,
VK_FORMAT_R32G32B32A32_SFLOAT,
Renderer.SurfaceSampleCountFlagBits,
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_wboit_accumulation',
false,
VK_FORMAT_R16G16B16A16_SFLOAT,
Renderer.SurfaceSampleCountFlagBits,
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_wboit_revealage',
false,
VK_FORMAT_R32_SFLOAT,
Renderer.SurfaceSampleCountFlagBits,
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_color_optimized_non_alpha',
false,
Renderer.OptimizedNonAlphaFormat,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_color_temporal_antialiasing',
false,
Renderer.OptimizedNonAlphaFormat,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_TRANSFER_SRC_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_color_tonemapping',
false,
VK_FORMAT_R8G8B8A8_SRGB,//TVkFormat(TpvInt32(IfThen(Renderer.SurfaceSampleCountFlagBits=TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),TpvInt32(VK_FORMAT_R8G8B8A8_SRGB),TpvInt32(VK_FORMAT_R8G8B8A8_UNORM)))),
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_FORMAT_R8G8B8A8_UNORM
);
fFrameGraph.AddImageResourceType('resourcetype_dithering_color',
false,
VK_FORMAT_R8G8B8A8_SRGB,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_hud_output_color',
false,
VK_FORMAT_R8G8B8A8_SRGB,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_color',
false,
VK_FORMAT_R16G16B16A16_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_color_halfres',
false,
VK_FORMAT_R16G16B16A16_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,0.5,0.5,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
{fFrameGraph.AddImageResourceType('resourcetype_color_posteffect',
false,
VK_FORMAT_R16G16B16A16_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_color_posteffect_halfres',
false,
VK_FORMAT_R16G16B16A16_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,0.5,0.5,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);}
fFrameGraph.AddImageResourceType('resourcetype_color_antialiasing',
false,
VK_FORMAT_R8G8B8A8_SRGB,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_depth',
false,
VK_FORMAT_D32_SFLOAT{pvApplication.VulkanDepthImageFormat},
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.From(VK_FORMAT_D32_SFLOAT{pvApplication.VulkanDepthImageFormat}),
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT) or (IfThen(Renderer.AntialiasingMode=TpvScene3DRendererAntialiasingMode.TAA,TVkImageUsageFlags(VK_IMAGE_USAGE_TRANSFER_SRC_BIT),0)),
1
);
fFrameGraph.AddImageResourceType('resourcetype_predepth',
false,
VK_FORMAT_R32_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_velocity',
false,
VK_FORMAT_R32G32_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_normals',
false,
VK_FORMAT_A2B10G10R10_UNORM_PACK32,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_ssao',
false,
VK_FORMAT_R32G32_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_ssao_final',
false,
VK_FORMAT_R8_UNORM,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
case Renderer.ShadowMode of
TpvScene3DRendererShadowMode.MSM:begin
fFrameGraph.AddImageResourceType('resourcetype_cascadedshadowmap_msaa_data',
false,
VK_FORMAT_R16G16B16A16_UNORM,
// VK_FORMAT_R32G32B32A32_SFLOAT,
Renderer.ShadowMapSampleCountFlagBits,
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.Absolute,fCascadedShadowMapWidth,fCascadedShadowMapHeight,1.0,CountCascadedShadowMapCascades),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_cascadedshadowmap_msaa_depth',
false,
VK_FORMAT_D32_SFLOAT,
Renderer.ShadowMapSampleCountFlagBits,
TpvFrameGraph.TImageType.From(VK_FORMAT_D32_SFLOAT),
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.Absolute,fCascadedShadowMapWidth,fCascadedShadowMapHeight,1.0,CountCascadedShadowMapCascades),
TVkImageUsageFlags(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_cascadedshadowmap_data',
false,
VK_FORMAT_R16G16B16A16_UNORM,
// VK_FORMAT_R32G32B32A32_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.Absolute,fCascadedShadowMapWidth,fCascadedShadowMapHeight,1.0,CountCascadedShadowMapCascades),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_cascadedshadowmap_depth',
false,
VK_FORMAT_D32_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.From(VK_FORMAT_D32_SFLOAT),
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.Absolute,fCascadedShadowMapWidth,fCascadedShadowMapHeight,1.0,CountCascadedShadowMapCascades),
TVkImageUsageFlags(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
end;
else begin
fFrameGraph.AddImageResourceType('resourcetype_cascadedshadowmap_data',
false,
VK_FORMAT_D32_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.From(VK_FORMAT_D32_SFLOAT),
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.Absolute,fCascadedShadowMapWidth,fCascadedShadowMapHeight,1.0,CountCascadedShadowMapCascades),
TVkImageUsageFlags(VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
end;
end;
fFrameGraph.AddImageResourceType('resourcetype_smaa_edges',
false,
VK_FORMAT_R8G8_UNORM,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
fFrameGraph.AddImageResourceType('resourcetype_smaa_weights',
false,
VK_FORMAT_R8G8B8A8_UNORM,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);
{fFrameGraph.AddImageResourceType('resourcetype_depthoffield',
false,
VK_FORMAT_R16G16B16A16_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
TpvFrameGraph.TImageType.Color,
TpvFrameGraph.TImageSize.Create(TpvFrameGraph.TImageSize.TKind.SurfaceDependent,1.0,1.0,1.0,fCountSurfaceViews),
TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT),
1
);}
TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass:=TpvScene3DRendererPassesMeshComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthVelocityNormalsRenderPass:=TpvScene3DRendererPassesDepthVelocityNormalsRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthVelocityNormalsRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass);
TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass:=TpvScene3DRendererPassesDepthMipMapComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthVelocityNormalsRenderPass);
TpvScene3DRendererInstancePasses(fPasses).fFrustumClusterGridBuildComputePass:=TpvScene3DRendererPassesFrustumClusterGridBuildComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fFrustumClusterGridBuildComputePass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fFrustumClusterGridAssignComputePass:=TpvScene3DRendererPassesFrustumClusterGridAssignComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fFrustumClusterGridAssignComputePass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fFrustumClusterGridBuildComputePass);
case Renderer.ShadowMode of
TpvScene3DRendererShadowMode.None,
TpvScene3DRendererShadowMode.PCF,TpvScene3DRendererShadowMode.DPCF,TpvScene3DRendererShadowMode.PCSS:begin
TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapRenderPass:=TpvScene3DRendererPassesCascadedShadowMapRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass);
TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthVelocityNormalsRenderPass);
TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
end;
TpvScene3DRendererShadowMode.MSM:begin
TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapRenderPass:=TpvScene3DRendererPassesCascadedShadowMapRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass);
TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthVelocityNormalsRenderPass);
TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapResolveRenderPass:=TpvScene3DRendererPassesCascadedShadowMapResolveRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapBlurRenderPasses[0]:=TpvScene3DRendererPassesCascadedShadowMapBlurRenderPass.Create(fFrameGraph,self,true);
TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapBlurRenderPasses[1]:=TpvScene3DRendererPassesCascadedShadowMapBlurRenderPass.Create(fFrameGraph,self,false);
end;
else begin
Assert(false);
end;
end;
TpvScene3DRendererInstancePasses(fPasses).fSSAORenderPass:=TpvScene3DRendererPassesSSAORenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fSSAORenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fSSAOBlurRenderPasses[0]:=TpvScene3DRendererPassesSSAOBlurRenderPass.Create(fFrameGraph,self,true);
TpvScene3DRendererInstancePasses(fPasses).fSSAOBlurRenderPasses[1]:=TpvScene3DRendererPassesSSAOBlurRenderPass.Create(fFrameGraph,self,false);
if Renderer.GlobalIlluminatonMode=TpvScene3DRendererGlobalIlluminatonMode.CameraReflectionProbe then begin
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeRenderPass:=TpvScene3DRendererPassesReflectionProbeRenderPass.Create(fFrameGraph,self);
case Renderer.ShadowMode of
TpvScene3DRendererShadowMode.PCF,TpvScene3DRendererShadowMode.DPCF,TpvScene3DRendererShadowMode.PCSS:begin
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapRenderPass);
end;
TpvScene3DRendererShadowMode.MSM:begin
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapBlurRenderPasses[1]);
end;
else begin
end;
end;
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fFrustumClusterGridAssignComputePass);
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass);
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeMipMapComputePass:=TpvScene3DRendererPassesReflectionProbeMipMapComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeMipMapComputePass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeRenderPass);
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassGGX:=TpvScene3DRendererPassesReflectionProbeComputePass.Create(fFrameGraph,self,0);
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassGGX.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassCharlie:=TpvScene3DRendererPassesReflectionProbeComputePass.Create(fFrameGraph,self,1);
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassCharlie.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassLambertian:=TpvScene3DRendererPassesReflectionProbeComputePass.Create(fFrameGraph,self,2);
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassLambertian.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeMipMapComputePass);
end else begin
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeRenderPass:=nil;
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassGGX:=nil;
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassCharlie:=nil;
TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassLambertian:=nil;
end;
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass:=TpvScene3DRendererPassesForwardRenderPass.Create(fFrameGraph,self);
if assigned(TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeRenderPass) then begin
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassGGX);
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassCharlie);
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fReflectionProbeComputePassLambertian);
end;
case Renderer.ShadowMode of
TpvScene3DRendererShadowMode.PCF,TpvScene3DRendererShadowMode.DPCF,TpvScene3DRendererShadowMode.PCSS:begin
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapRenderPass);
end;
TpvScene3DRendererShadowMode.MSM:begin
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fCascadedShadowMapBlurRenderPasses[1]);
end;
else begin
end;
end;
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fFrustumClusterGridAssignComputePass);
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass);
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fSSAOBlurRenderPasses[1]);
if Renderer.SurfaceSampleCountFlagBits<>TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT) then begin
TpvScene3DRendererInstancePasses(fPasses).fForwardResolveRenderPass:=TpvScene3DRendererPassesForwardResolveRenderPass.Create(fFrameGraph,self);
end;
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderMipMapComputePass:=TpvScene3DRendererPassesForwardRenderMipMapComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fForwardRenderMipMapComputePass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass);
case Renderer.TransparencyMode of
TpvScene3DRendererTransparencyMode.Direct:begin
TpvScene3DRendererInstancePasses(fPasses).fDirectTransparencyRenderPass:=TpvScene3DRendererPassesDirectTransparencyRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDirectTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass);
TpvScene3DRendererInstancePasses(fPasses).fDirectTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fDirectTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fForwardRenderMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fDirectTransparencyResolveRenderPass:=TpvScene3DRendererPassesDirectTransparencyResolveRenderPass.Create(fFrameGraph,self);
end;
TpvScene3DRendererTransparencyMode.SPINLOCKOIT,
TpvScene3DRendererTransparencyMode.INTERLOCKOIT:begin
TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyClearCustomPass:=TpvScene3DRendererPassesLockOrderIndependentTransparencyClearCustomPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyRenderPass:=TpvScene3DRendererPassesLockOrderIndependentTransparencyRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass);
TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyClearCustomPass);
TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fForwardRenderMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyBarrierCustomPass:=TpvScene3DRendererPassesLockOrderIndependentTransparencyBarrierCustomPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyBarrierCustomPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyRenderPass);
TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyResolveRenderPass:=TpvScene3DRendererPassesLockOrderIndependentTransparencyResolveRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyResolveRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyBarrierCustomPass);
end;
TpvScene3DRendererTransparencyMode.LOOPOIT:begin
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyClearCustomPass:=TpvScene3DRendererPassesLoopOrderIndependentTransparencyClearCustomPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass1RenderPass:=TpvScene3DRendererPassesLoopOrderIndependentTransparencyPass1RenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass1RenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass1RenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyClearCustomPass);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass1RenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass1RenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fForwardRenderMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass1BarrierCustomPass:=TpvScene3DRendererPassesLoopOrderIndependentTransparencyPass1BarrierCustomPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass1BarrierCustomPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass1RenderPass);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass2RenderPass:=TpvScene3DRendererPassesLoopOrderIndependentTransparencyPass2RenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass2RenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass1BarrierCustomPass);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass2BarrierCustomPass:=TpvScene3DRendererPassesLoopOrderIndependentTransparencyPass2BarrierCustomPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass2BarrierCustomPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass2RenderPass);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyResolveRenderPass:=TpvScene3DRendererPassesLoopOrderIndependentTransparencyResolveRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyResolveRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyPass2BarrierCustomPass);
end;
TpvScene3DRendererTransparencyMode.WBOIT:begin
TpvScene3DRendererInstancePasses(fPasses).fWeightBlendedOrderIndependentTransparencyRenderPass:=TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fWeightBlendedOrderIndependentTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass);
TpvScene3DRendererInstancePasses(fPasses).fWeightBlendedOrderIndependentTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fWeightBlendedOrderIndependentTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fForwardRenderMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fWeightBlendedOrderIndependentTransparencyResolveRenderPass:=TpvScene3DRendererPassesWeightBlendedOrderIndependentTransparencyResolveRenderPass.Create(fFrameGraph,self);
end;
TpvScene3DRendererTransparencyMode.MBOIT:begin
TpvScene3DRendererInstancePasses(fPasses).fMomentBasedOrderIndependentTransparencyAbsorbanceRenderPass:=TpvScene3DRendererPassesMomentBasedOrderIndependentTransparencyAbsorbanceRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fMomentBasedOrderIndependentTransparencyAbsorbanceRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass);
TpvScene3DRendererInstancePasses(fPasses).fMomentBasedOrderIndependentTransparencyAbsorbanceRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fMomentBasedOrderIndependentTransparencyAbsorbanceRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fForwardRenderMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fMomentBasedOrderIndependentTransparencyTransmittanceRenderPass:=TpvScene3DRendererPassesMomentBasedOrderIndependentTransparencyTransmittanceRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fMomentBasedOrderIndependentTransparencyResolveRenderPass:=TpvScene3DRendererPassesMomentBasedOrderIndependentTransparencyResolveRenderPass.Create(fFrameGraph,self);
end;
TpvScene3DRendererTransparencyMode.SPINLOCKDFAOIT,
TpvScene3DRendererTransparencyMode.INTERLOCKDFAOIT:begin
TpvScene3DRendererInstancePasses(fPasses).fDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass:=TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDeepAndFastApproximateOrderIndependentTransparencyRenderPass:=TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDeepAndFastApproximateOrderIndependentTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDeepAndFastApproximateOrderIndependentTransparencyClearCustomPass);
TpvScene3DRendererInstancePasses(fPasses).fDeepAndFastApproximateOrderIndependentTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMeshComputePass);
TpvScene3DRendererInstancePasses(fPasses).fDeepAndFastApproximateOrderIndependentTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fDeepAndFastApproximateOrderIndependentTransparencyRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fForwardRenderMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fDeepAndFastApproximateOrderIndependentTransparencyResolveRenderPass:=TpvScene3DRendererPassesDeepAndFastApproximateOrderIndependentTransparencyResolveRenderPass.Create(fFrameGraph,self);
end
else begin
end;
end;
if assigned(LastOutputResource) and
(LastOutputResource.Resource.Name='resource_combinedopaquetransparency_final_msaa_color') then begin
TpvScene3DRendererInstancePasses(fPasses).fOrderIndependentTransparencyResolveRenderPass:=TpvScene3DRendererPassesOrderIndependentTransparencyResolveRenderPass.Create(fFrameGraph,self);
end;
if Renderer.AntialiasingMode=TpvScene3DRendererAntialiasingMode.TAA then begin
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAAPreCustomPass:=TpvScene3DRendererPassesAntialiasingTAAPreCustomPass.Create(fFrameGraph,self);
case Renderer.TransparencyMode of
TpvScene3DRendererTransparencyMode.Direct:begin
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAAPreCustomPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDirectTransparencyResolveRenderPass);
end;
TpvScene3DRendererTransparencyMode.SPINLOCKOIT,
TpvScene3DRendererTransparencyMode.INTERLOCKOIT:begin
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAAPreCustomPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLockOrderIndependentTransparencyResolveRenderPass);
end;
TpvScene3DRendererTransparencyMode.LOOPOIT:begin
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAAPreCustomPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLoopOrderIndependentTransparencyResolveRenderPass);
end;
TpvScene3DRendererTransparencyMode.WBOIT:begin
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAAPreCustomPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fWeightBlendedOrderIndependentTransparencyResolveRenderPass);
end;
TpvScene3DRendererTransparencyMode.MBOIT:begin
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAAPreCustomPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fMomentBasedOrderIndependentTransparencyResolveRenderPass);
end;
else begin
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAAPreCustomPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fForwardRenderPass);
end;
end;
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAARenderPass:=TpvScene3DRendererPassesAntialiasingTAARenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAARenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAAPreCustomPass);
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAAPostCustomPass:=TpvScene3DRendererPassesAntialiasingTAAPostCustomPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAAPostCustomPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAARenderPass);
end;
(**)
if (Renderer.DepthOfFieldMode<>TpvScene3DRendererDepthOfFieldMode.None) and not assigned(VirtualReality) then begin
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldAutoFocusComputePass:=TpvScene3DRendererPassesDepthOfFieldAutoFocusComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldAutoFocusComputePass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthMipMapComputePass);
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldPrepareRenderPass:=TpvScene3DRendererPassesDepthOfFieldPrepareRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldPrepareRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldAutoFocusComputePass);
case Renderer.DepthOfFieldMode of
TpvScene3DRendererDepthOfFieldMode.HalfResSeparateNearFar,
TpvScene3DRendererDepthOfFieldMode.HalfResBruteforce:begin
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldBokehComputePass:=TpvScene3DRendererPassesDepthOfFieldBokehComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldPrefilterRenderPass:=TpvScene3DRendererPassesDepthOfFieldPrefilterRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldBlurRenderPass:=TpvScene3DRendererPassesDepthOfFieldBlurRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldBlurRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldBokehComputePass);
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldPostBlurRenderPass:=TpvScene3DRendererPassesDepthOfFieldPostBlurRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldCombineRenderPass:=TpvScene3DRendererPassesDepthOfFieldCombineRenderPass.Create(fFrameGraph,self);
end;
TpvScene3DRendererDepthOfFieldMode.FullResBruteforce:begin
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldBokehComputePass:=TpvScene3DRendererPassesDepthOfFieldBokehComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldBruteforceRenderPass:=TpvScene3DRendererPassesDepthOfFieldBruteforceRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldBruteforceRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldBokehComputePass);
end;
else {TpvScene3DRendererDepthOfFieldMode.FullResHexagon:}begin
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldGatherPass1RenderPass:=TpvScene3DRendererPassesDepthOfFieldGatherPass1RenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldGatherPass2RenderPass:=TpvScene3DRendererPassesDepthOfFieldGatherPass2RenderPass.Create(fFrameGraph,self);
end;
end;
TpvScene3DRendererInstancePasses(fPasses).fDepthOfFieldResolveRenderPass:=TpvScene3DRendererPassesDepthOfFieldResolveRenderPass.Create(fFrameGraph,self);
end; //*)
if not assigned(VirtualReality) then begin
case Renderer.LensMode of
TpvScene3DRendererLensMode.DownUpsample:begin
TpvScene3DRendererInstancePasses(fPasses).fLensDownsampleComputePass:=TpvScene3DRendererPassesLensDownsampleComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLensUpsampleComputePass:=TpvScene3DRendererPassesLensUpsampleComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLensUpsampleComputePass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLensDownsampleComputePass);
TpvScene3DRendererInstancePasses(fPasses).fLensResolveRenderPass:=TpvScene3DRendererPassesLensResolveRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLensResolveRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLensUpsampleComputePass);
end;
else begin
end;
end;
end;
TpvScene3DRendererInstancePasses(fPasses).fLuminanceHistogramComputePass:=TpvScene3DRendererPassesLuminanceHistogramComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLuminanceAverageComputePass:=TpvScene3DRendererPassesLuminanceAverageComputePass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fLuminanceAverageComputePass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLuminanceHistogramComputePass);
TpvScene3DRendererInstancePasses(fPasses).fTonemappingRenderPass:=TpvScene3DRendererPassesTonemappingRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fTonemappingRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fLuminanceAverageComputePass);
if Renderer.AntialiasingMode=TpvScene3DRendererAntialiasingMode.TAA then begin
TpvScene3DRendererInstancePasses(fPasses).fTonemappingRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fAntialiasingTAAPostCustomPass);
end;
case Renderer.AntialiasingMode of
TpvScene3DRendererAntialiasingMode.DSAA:begin
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingDSAARenderPass:=TpvScene3DRendererPassesAntialiasingDSAARenderPass.Create(fFrameGraph,self);
end;
TpvScene3DRendererAntialiasingMode.FXAA:begin
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingFXAARenderPass:=TpvScene3DRendererPassesAntialiasingFXAARenderPass.Create(fFrameGraph,self);
end;
TpvScene3DRendererAntialiasingMode.SMAA:begin
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingSMAAEdgesRenderPass:=TpvScene3DRendererPassesAntialiasingSMAAEdgesRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingSMAAWeightsRenderPass:=TpvScene3DRendererPassesAntialiasingSMAAWeightsRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingSMAABlendRenderPass:=TpvScene3DRendererPassesAntialiasingSMAABlendRenderPass.Create(fFrameGraph,self);
end;
else begin
TpvScene3DRendererInstancePasses(fPasses).fAntialiasingNoneRenderPass:=TpvScene3DRendererPassesAntialiasingNoneRenderPass.Create(fFrameGraph,self);
end;
end;
if fUseDebugBlit or assigned(fHUDRenderPassClass) then begin
TpvScene3DRendererInstancePasses(fPasses).fDitheringRenderPass:=TpvScene3DRendererPassesDitheringRenderPass.Create(fFrameGraph,self,false);
if assigned(fHUDRenderPassClass) then begin
TpvScene3DRendererInstancePasses(fPasses).fHUDRenderPass:=fHUDRenderPassClass.Create(fFrameGraph,self,fHUDRenderPassParent);
TpvScene3DRendererInstancePasses(fPasses).fHUDRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fDitheringRenderPass);
TpvScene3DRendererInstancePasses(fPasses).fHUDMipMapCustomPass:=TpvScene3DRendererPassesHUDMipMapCustomPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fHUDMipMapCustomPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fHUDRenderPass);
TpvScene3DRendererInstancePasses(fPasses).fContentProjectionRenderPass:=TpvScene3DRendererPassesContentProjectionRenderPass.Create(fFrameGraph,self);
TpvScene3DRendererInstancePasses(fPasses).fContentProjectionRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fHUDMipMapCustomPass);
end;
if fUseDebugBlit then begin
TpvScene3DRendererInstancePasses(fPasses).fDebugBlitRenderPass:=TpvScene3DRendererPassesDebugBlitRenderPass.Create(fFrameGraph,self);
if assigned(fHUDRenderPassClass) then begin
TpvScene3DRendererInstancePasses(fPasses).fDebugBlitRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fHUDRenderPass);
TpvScene3DRendererInstancePasses(fPasses).fDebugBlitRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fContentProjectionRenderPass);
end;
fFrameGraph.RootPass:=TpvScene3DRendererInstancePasses(fPasses).fDebugBlitRenderPass;
end else begin
TpvScene3DRendererInstancePasses(fPasses).fBlitRenderPass:=TpvScene3DRendererPassesBlitRenderPass.Create(fFrameGraph,self);
if assigned(fHUDRenderPassClass) then begin
TpvScene3DRendererInstancePasses(fPasses).fBlitRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fHUDRenderPass);
TpvScene3DRendererInstancePasses(fPasses).fBlitRenderPass.AddExplicitPassDependency(TpvScene3DRendererInstancePasses(fPasses).fContentProjectionRenderPass);
end;
fFrameGraph.RootPass:=TpvScene3DRendererInstancePasses(fPasses).fBlitRenderPass;
end;
end else begin
TpvScene3DRendererInstancePasses(fPasses).fDitheringRenderPass:=TpvScene3DRendererPassesDitheringRenderPass.Create(fFrameGraph,self,true);
fFrameGraph.RootPass:=TpvScene3DRendererInstancePasses(fPasses).fDitheringRenderPass;
end;
fFrameGraph.DoWaitOnSemaphore:=true;
fFrameGraph.DoSignalSemaphore:=true;
fFrameGraph.Compile;
end;
procedure TpvScene3DRendererInstance.AcquirePersistentResources;
begin
fFrameGraph.AcquirePersistentResources;
if Renderer.GlobalIlluminatonMode=TpvScene3DRendererGlobalIlluminatonMode.CameraReflectionProbe then begin
fImageBasedLightingReflectionProbeCubeMaps:=TpvScene3DRendererImageBasedLightingReflectionProbeCubeMaps.Create(Renderer.VulkanDevice,
Max(16,fReflectionProbeWidth),
Max(16,fReflectionProbeHeight),
Renderer.CountInFlightFrames);
end else begin
fImageBasedLightingReflectionProbeCubeMaps:=nil;
end;
end;
procedure TpvScene3DRendererInstance.ReleasePersistentResources;
begin
fFrameGraph.ReleasePersistentResources;
FreeAndNil(fImageBasedLightingReflectionProbeCubeMaps);
end;
procedure TpvScene3DRendererInstance.AcquireVolatileResources;
const NaNVector4:TpvVector4=(x:NaN;y:NaN;z:NaN;w:NaN);
var InFlightFrameIndex,Index:TpvSizeInt;
UniversalQueue:TpvVulkanQueue;
UniversalCommandPool:TpvVulkanCommandPool;
UniversalCommandBuffer:TpvVulkanCommandBuffer;
UniversalFence:TpvVulkanFence;
begin
if assigned(fVirtualReality) then begin
fWidth:=fVirtualReality.Width;
fHeight:=fVirtualReality.Height;
fHUDWidth:=Renderer.VirtualRealityHUDWidth;
fHUDHeight:=Renderer.VirtualRealityHUDHeight;
end else if fHasExternalOutputImage then begin
// Nothing
end else begin
fWidth:=pvApplication.VulkanSwapChain.Width;
fHeight:=pvApplication.VulkanSwapChain.Height;
fHUDWidth:=fWidth;
fHUDHeight:=fHeight;
end;
fCameraPreset.MaxCoC:=((fCameraPreset.BlurKernelSize*4.0)+6.0)/fHeight;
FillChar(fInFlightFrameStates,SizeOf(TInFlightFrameStates),#0);
fFrameGraph.SetSwapChain(pvApplication.VulkanSwapChain,
pvApplication.VulkanDepthImageFormat);
if assigned(fVirtualReality) then begin
fFrameGraph.SurfaceWidth:=fWidth;
fFrameGraph.SurfaceHeight:=fHeight;
fExternalOutputImageData.VulkanImages.Clear;
for Index:=0 to fVirtualReality.VulkanImages.Count-1 do begin
fExternalOutputImageData.VulkanImages.Add(fVirtualReality.VulkanImages[Index]);
end;
(fFrameGraph.ResourceTypeByName['resourcetype_output_color'] as TpvFrameGraph.TImageResourceType).Format:=fVirtualReality.ImageFormat;
end else if fHasExternalOutputImage then begin
(fFrameGraph.ResourceTypeByName['resourcetype_output_color'] as TpvFrameGraph.TImageResourceType).Format:=fExternalImageFormat;
end;
UniversalQueue:=Renderer.VulkanDevice.UniversalQueue;
try
UniversalCommandPool:=TpvVulkanCommandPool.Create(Renderer.VulkanDevice,
Renderer.VulkanDevice.UniversalQueueFamilyIndex,
TVkCommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT));
try
UniversalCommandBuffer:=TpvVulkanCommandBuffer.Create(UniversalCommandPool,
VK_COMMAND_BUFFER_LEVEL_PRIMARY);
try
UniversalFence:=TpvVulkanFence.Create(Renderer.VulkanDevice);
try
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
fNearestFarthestDepthVulkanBuffers[InFlightFrameIndex]:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
SizeOf(TpvVector4),
TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
0,
0,
0,
0,
[]);
fDepthOfFieldAutoFocusVulkanBuffers[InFlightFrameIndex]:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
SizeOf(TpvVector4),
TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
0,
0,
0,
0,
[]);
fDepthOfFieldBokenShapeTapVulkanBuffers[InFlightFrameIndex]:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
(SizeOf(TpvVector2)*4096)+SizeOf(TpvVector4),
TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
0,
0,
0,
0,
[]);
end;
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
pvApplication.VulkanDevice.MemoryStaging.Upload(pvApplication.VulkanDevice.UniversalQueue,
UniversalCommandBuffer,
UniversalFence,
NaNVector4,
fDepthOfFieldAutoFocusVulkanBuffers[InFlightFrameIndex],
0,
SizeOf(TpvVector4));
end;
fFrustumClusterGridTileSizeX:=(fWidth+(fFrustumClusterGridSizeX-1)) div fFrustumClusterGridSizeX;
fFrustumClusterGridTileSizeY:=(fHeight+(fFrustumClusterGridSizeY-1)) div fFrustumClusterGridSizeY;
fFrustumClusterGridCountTotalViews:=fCountSurfaceViews; // +6 for local light and reflection probe cubemap
if Renderer.GlobalIlluminatonMode=TpvScene3DRendererGlobalIlluminatonMode.CameraReflectionProbe then begin
inc(fFrustumClusterGridCountTotalViews,6); // +6 for local light and reflection probe cubemap
end;
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
fFrustumClusterGridGlobalsVulkanBuffers[InFlightFrameIndex]:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
SizeOf(TFrustumClusterGridPushConstants),
TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
0,
0,
0,
0,
[TpvVulkanBufferFlag.PersistentMapped]);
fFrustumClusterGridAABBVulkanBuffers[InFlightFrameIndex]:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
fFrustumClusterGridSizeX*fFrustumClusterGridSizeY*fFrustumClusterGridSizeZ*SizeOf(TpvVector4)*4*fFrustumClusterGridCountTotalViews,
TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
0,
0,
0,
0,
[]);
fFrustumClusterGridIndexListCounterVulkanBuffers[InFlightFrameIndex]:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
SizeOf(TpvUInt32),
TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
0,
0,
0,
0,
[]);
fFrustumClusterGridIndexListVulkanBuffers[InFlightFrameIndex]:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
fFrustumClusterGridSizeX*fFrustumClusterGridSizeY*fFrustumClusterGridSizeZ*SizeOf(TpvUInt32)*128*fFrustumClusterGridCountTotalViews,
TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
0,
0,
0,
0,
[]);
fFrustumClusterGridDataVulkanBuffers[InFlightFrameIndex]:=TpvVulkanBuffer.Create(pvApplication.VulkanDevice,
fFrustumClusterGridSizeX*fFrustumClusterGridSizeY*fFrustumClusterGridSizeZ*SizeOf(TpvUInt32)*4*fFrustumClusterGridCountTotalViews,
TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
0,
0,
0,
0,
[]);
end;
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
fDepthMipmappedArray2DImages[InFlightFrameIndex]:=TpvScene3DRendererMipmappedArray2DImage.Create(fWidth,fHeight,fCountSurfaceViews,VK_FORMAT_R32_SFLOAT,false,VK_SAMPLE_COUNT_1_BIT,VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
fSceneMipmappedArray2DImages[InFlightFrameIndex]:=TpvScene3DRendererMipmappedArray2DImage.Create(fWidth,fHeight,fCountSurfaceViews,Renderer.OptimizedNonAlphaFormat,true,VK_SAMPLE_COUNT_1_BIT,VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
if assigned(fHUDRenderPassClass) then begin
fHUDMipmappedArray2DImages[InFlightFrameIndex]:=TpvScene3DRendererMipmappedArray2DImage.Create(fHUDWidth,fHUDHeight,1,VK_FORMAT_R8G8B8A8_SRGB,true,VK_SAMPLE_COUNT_1_BIT,VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
end else begin
fHUDMipmappedArray2DImages[InFlightFrameIndex]:=nil;
end;
end;
case Renderer.TransparencyMode of
TpvScene3DRendererTransparencyMode.SPINLOCKOIT,
TpvScene3DRendererTransparencyMode.INTERLOCKOIT:begin
fCountLockOrderIndependentTransparencyLayers:=CountOrderIndependentTransparencyLayers;//Min(Max(CountOrderIndependentTransparencyLayers,fCountSurfaceMSAASamples),16);
fLockOrderIndependentTransparentUniformBuffer.ViewPort.x:=fWidth;
fLockOrderIndependentTransparentUniformBuffer.ViewPort.y:=fHeight;
fLockOrderIndependentTransparentUniformBuffer.ViewPort.z:=fLockOrderIndependentTransparentUniformBuffer.ViewPort.x*fLockOrderIndependentTransparentUniformBuffer.ViewPort.y;
fLockOrderIndependentTransparentUniformBuffer.ViewPort.w:=(fCountLockOrderIndependentTransparencyLayers and $ffff) or ((Renderer.CountSurfaceMSAASamples and $ffff) shl 16);
fLockOrderIndependentTransparentUniformVulkanBuffer.UploadData(pvApplication.VulkanDevice.UniversalQueue,
UniversalCommandBuffer,
UniversalFence,
fLockOrderIndependentTransparentUniformBuffer,
0,
SizeOf(TLockOrderIndependentTransparentUniformBuffer));
for InFlightFrameIndex:=0 to fFrameGraph.CountInFlightFrames-1 do begin
fLockOrderIndependentTransparencyABufferBuffers[InFlightFrameIndex]:=TpvScene3DRendererOrderIndependentTransparencyBuffer.Create(fWidth*fHeight*fCountLockOrderIndependentTransparencyLayers*fCountSurfaceViews*(SizeOf(UInt32)*4),
VK_FORMAT_R32G32B32A32_UINT,
TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT));
fLockOrderIndependentTransparencyAuxImages[InFlightFrameIndex]:=TpvScene3DRendererOrderIndependentTransparencyImage.Create(fWidth,
fHeight,
fCountSurfaceViews,
VK_FORMAT_R32_UINT,
VK_SAMPLE_COUNT_1_BIT);
if Renderer.TransparencyMode=TpvScene3DRendererTransparencyMode.SPINLOCKOIT then begin
fLockOrderIndependentTransparencySpinLockImages[InFlightFrameIndex]:=TpvScene3DRendererOrderIndependentTransparencyImage.Create(fWidth,
fHeight,
fCountSurfaceViews,
VK_FORMAT_R32_UINT,
VK_SAMPLE_COUNT_1_BIT);
end;
end;
end;
TpvScene3DRendererTransparencyMode.LOOPOIT:begin
fCountLoopOrderIndependentTransparencyLayers:=CountOrderIndependentTransparencyLayers;//Min(Max(CountOrderIndependentTransparencyLayers,fCountSurfaceMSAASamples),16);
fLoopOrderIndependentTransparentUniformBuffer.ViewPort.x:=fWidth;
fLoopOrderIndependentTransparentUniformBuffer.ViewPort.y:=fHeight;
fLoopOrderIndependentTransparentUniformBuffer.ViewPort.z:=fLoopOrderIndependentTransparentUniformBuffer.ViewPort.x*fLoopOrderIndependentTransparentUniformBuffer.ViewPort.y;
fLoopOrderIndependentTransparentUniformBuffer.ViewPort.w:=(fCountLoopOrderIndependentTransparencyLayers and $ffff) or ((Renderer.CountSurfaceMSAASamples and $ffff) shl 16);
fLoopOrderIndependentTransparentUniformVulkanBuffer.UploadData(pvApplication.VulkanDevice.UniversalQueue,
UniversalCommandBuffer,
UniversalFence,
fLoopOrderIndependentTransparentUniformBuffer,
0,
SizeOf(TLoopOrderIndependentTransparentUniformBuffer));
for InFlightFrameIndex:=0 to fFrameGraph.CountInFlightFrames-1 do begin
fLoopOrderIndependentTransparencyABufferBuffers[InFlightFrameIndex]:=TpvScene3DRendererOrderIndependentTransparencyBuffer.Create(fWidth*fHeight*fCountLoopOrderIndependentTransparencyLayers*fCountSurfaceViews*(SizeOf(UInt32)*2),
VK_FORMAT_R32G32_UINT,
TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT));
fLoopOrderIndependentTransparencyZBufferBuffers[InFlightFrameIndex]:=TpvScene3DRendererOrderIndependentTransparencyBuffer.Create(fWidth*fHeight*fCountLoopOrderIndependentTransparencyLayers*fCountSurfaceViews*(SizeOf(UInt32)*1),
VK_FORMAT_R32_UINT,
TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT));
if Renderer.SurfaceSampleCountFlagBits<>TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT) then begin
fLoopOrderIndependentTransparencySBufferBuffers[InFlightFrameIndex]:=TpvScene3DRendererOrderIndependentTransparencyBuffer.Create(fWidth*fHeight*fCountLoopOrderIndependentTransparencyLayers*fCountSurfaceViews*(SizeOf(UInt32)*1),
VK_FORMAT_R32_UINT,
TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT));
end else begin
fLoopOrderIndependentTransparencySBufferBuffers[InFlightFrameIndex]:=nil;
end;
end;
end;
TpvScene3DRendererTransparencyMode.MBOIT,
TpvScene3DRendererTransparencyMode.WBOIT:begin
fApproximationOrderIndependentTransparentUniformBuffer.ZNearZFar.x:=abs(fZNear);
fApproximationOrderIndependentTransparentUniformBuffer.ZNearZFar.y:=IfThen(IsInfinite(fZFar),4096.0,abs(fZFar));
fApproximationOrderIndependentTransparentUniformBuffer.ZNearZFar.z:=ln(fApproximationOrderIndependentTransparentUniformBuffer.ZNearZFar.x);
fApproximationOrderIndependentTransparentUniformBuffer.ZNearZFar.w:=ln(fApproximationOrderIndependentTransparentUniformBuffer.ZNearZFar.y);
fApproximationOrderIndependentTransparentUniformVulkanBuffer.UploadData(pvApplication.VulkanDevice.UniversalQueue,
UniversalCommandBuffer,
UniversalFence,
fApproximationOrderIndependentTransparentUniformBuffer,
0,
SizeOf(TApproximationOrderIndependentTransparentUniformBuffer));
end;
TpvScene3DRendererTransparencyMode.SPINLOCKDFAOIT,
TpvScene3DRendererTransparencyMode.INTERLOCKDFAOIT:begin
for InFlightFrameIndex:=0 to fFrameGraph.CountInFlightFrames-1 do begin
fDeepAndFastApproximateOrderIndependentTransparencyFragmentCounterImages[InFlightFrameIndex]:=TpvScene3DRendererOrderIndependentTransparencyImage.Create(fWidth,
fHeight,
fCountSurfaceViews,
VK_FORMAT_R32G32B32A32_UINT,
Renderer.SurfaceSampleCountFlagBits);
fDeepAndFastApproximateOrderIndependentTransparencyAccumulationImages[InFlightFrameIndex]:=TpvScene3DRendererOrderIndependentTransparencyImage.Create(fWidth,
fHeight,
fCountSurfaceViews,
VK_FORMAT_R16G16B16A16_SFLOAT,
Renderer.SurfaceSampleCountFlagBits);
fDeepAndFastApproximateOrderIndependentTransparencyAverageImages[InFlightFrameIndex]:=TpvScene3DRendererOrderIndependentTransparencyImage.Create(fWidth,
fHeight,
fCountSurfaceViews,
VK_FORMAT_R16G16B16A16_SFLOAT,
Renderer.SurfaceSampleCountFlagBits);
fDeepAndFastApproximateOrderIndependentTransparencyBucketImages[InFlightFrameIndex]:=TpvScene3DRendererOrderIndependentTransparencyImage.Create(fWidth,
fHeight,
fCountSurfaceViews*2,
VK_FORMAT_R16G16B16A16_SFLOAT,
Renderer.SurfaceSampleCountFlagBits);
if Renderer.TransparencyMode=TpvScene3DRendererTransparencyMode.SPINLOCKDFAOIT then begin
fDeepAndFastApproximateOrderIndependentTransparencySpinLockImages[InFlightFrameIndex]:=TpvScene3DRendererOrderIndependentTransparencyImage.Create(fWidth,
fHeight,
fCountSurfaceViews,
VK_FORMAT_R32_UINT,
VK_SAMPLE_COUNT_1_BIT);
end;
end;
end;
else begin
end;
end;
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
fLuminanceHistogramVulkanBuffers[InFlightFrameIndex]:=TpvVulkanBuffer.Create(Renderer.VulkanDevice,
SizeOf(TpvUInt32)*256,
TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
0,
0,
0,
0,
[]);
fLuminanceHistogramVulkanBuffers[InFlightFrameIndex].ClearData(pvApplication.VulkanDevice.UniversalQueue,
UniversalCommandBuffer,
UniversalFence,
0,
SizeOf(TpvUInt32)*256,
TpvVulkanBufferUseTemporaryStagingBufferMode.Automatic);
fLuminanceVulkanBuffers[InFlightFrameIndex]:=TpvVulkanBuffer.Create(Renderer.VulkanDevice,
SizeOf(TpvFloat),
TVkBufferUsageFlags(VK_BUFFER_USAGE_TRANSFER_DST_BIT) or TVkBufferUsageFlags(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT),
TVkSharingMode(VK_SHARING_MODE_EXCLUSIVE),
[],
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
0,
0,
TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) or TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_HOST_COHERENT_BIT),
0,
0,
0,
0,
[]);
fLuminanceVulkanBuffers[InFlightFrameIndex].ClearData(pvApplication.VulkanDevice.UniversalQueue,
UniversalCommandBuffer,
UniversalFence,
0,
SizeOf(TpvFloat),
TpvVulkanBufferUseTemporaryStagingBufferMode.Automatic);
fLuminanceEvents[InFlightFrameIndex]:=TpvVulkanEvent.Create(Renderer.VulkanDevice);
fLuminanceEventReady[InFlightFrameIndex]:=false;
end;
finally
FreeAndNil(UniversalFence);
end;
finally
FreeAndNil(UniversalCommandBuffer);
end;
finally
FreeAndNil(UniversalCommandPool);
end;
finally
UniversalQueue:=nil;
end;
if Renderer.AntialiasingMode=TpvScene3DRendererAntialiasingMode.TAA then begin
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
fTAAHistoryColorImages[InFlightFrameIndex]:=TpvScene3DRendererArray2DImage.Create(fWidth,
fHeight,
fCountSurfaceViews,
Renderer.OptimizedNonAlphaFormat,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
fTAAHistoryDepthImages[InFlightFrameIndex]:=TpvScene3DRendererArray2DImage.Create(fWidth,
fHeight,
fCountSurfaceViews,
VK_FORMAT_D32_SFLOAT,
TVkSampleCountFlagBits(VK_SAMPLE_COUNT_1_BIT),
VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
fTAAEvents[InFlightFrameIndex]:=TpvVulkanEvent.Create(Renderer.VulkanDevice);
fTAAEventReady[InFlightFrameIndex]:=false;
end;
end;
fFrameGraph.AcquireVolatileResources;
end;
procedure TpvScene3DRendererInstance.ReleaseVolatileResources;
var InFlightFrameIndex:TpvSizeInt;
begin
fFrameGraph.ReleaseVolatileResources;
if Renderer.AntialiasingMode=TpvScene3DRendererAntialiasingMode.TAA then begin
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
FreeAndNil(fTAAHistoryColorImages[InFlightFrameIndex]);
FreeAndNil(fTAAHistoryDepthImages[InFlightFrameIndex]);
FreeAndNil(fTAAEvents[InFlightFrameIndex]);
end;
end;
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
FreeAndNil(fLuminanceHistogramVulkanBuffers[InFlightFrameIndex]);
FreeAndNil(fLuminanceVulkanBuffers[InFlightFrameIndex]);
FreeAndNil(fLuminanceEvents[InFlightFrameIndex]);
end;
if assigned(fExternalOutputImageData) then begin
fExternalOutputImageData.VulkanImages.Clear;
end;
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
FreeAndNil(fDepthMipmappedArray2DImages[InFlightFrameIndex]);
FreeAndNil(fSceneMipmappedArray2DImages[InFlightFrameIndex]);
FreeAndNil(fHUDMipmappedArray2DImages[InFlightFrameIndex]);
end;
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
FreeAndNil(fNearestFarthestDepthVulkanBuffers[InFlightFrameIndex]);
FreeAndNil(fDepthOfFieldAutoFocusVulkanBuffers[InFlightFrameIndex]);
FreeAndNil(fDepthOfFieldBokenShapeTapVulkanBuffers[InFlightFrameIndex]);
end;
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
FreeAndNil(fFrustumClusterGridGlobalsVulkanBuffers[InFlightFrameIndex]);
FreeAndNil(fFrustumClusterGridAABBVulkanBuffers[InFlightFrameIndex]);
FreeAndNil(fFrustumClusterGridIndexListCounterVulkanBuffers[InFlightFrameIndex]);
FreeAndNil(fFrustumClusterGridIndexListVulkanBuffers[InFlightFrameIndex]);
FreeAndNil(fFrustumClusterGridDataVulkanBuffers[InFlightFrameIndex]);
end;
case Renderer.TransparencyMode of
TpvScene3DRendererTransparencyMode.SPINLOCKOIT,
TpvScene3DRendererTransparencyMode.INTERLOCKOIT:begin
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
FreeAndNil(fLockOrderIndependentTransparencyABufferBuffers[InFlightFrameIndex]);
FreeAndNil(fLockOrderIndependentTransparencyAuxImages[InFlightFrameIndex]);
if Renderer.TransparencyMode=TpvScene3DRendererTransparencyMode.SPINLOCKOIT then begin
FreeAndNil(fLockOrderIndependentTransparencySpinLockImages[InFlightFrameIndex]);
end;
end;
end;
TpvScene3DRendererTransparencyMode.LOOPOIT:begin
for InFlightFrameIndex:=0 to Renderer.CountInFlightFrames-1 do begin
FreeAndNil(fLoopOrderIndependentTransparencyABufferBuffers[InFlightFrameIndex]);
FreeAndNil(fLoopOrderIndependentTransparencyZBufferBuffers[InFlightFrameIndex]);
FreeAndNil(fLoopOrderIndependentTransparencySBufferBuffers[InFlightFrameIndex]);
end;
end;
TpvScene3DRendererTransparencyMode.SPINLOCKDFAOIT,
TpvScene3DRendererTransparencyMode.INTERLOCKDFAOIT:begin
for InFlightFrameIndex:=0 to fFrameGraph.CountInFlightFrames-1 do begin
FreeAndNil(fDeepAndFastApproximateOrderIndependentTransparencyFragmentCounterImages[InFlightFrameIndex]);
FreeAndNil(fDeepAndFastApproximateOrderIndependentTransparencyAccumulationImages[InFlightFrameIndex]);
FreeAndNil(fDeepAndFastApproximateOrderIndependentTransparencyAverageImages[InFlightFrameIndex]);
FreeAndNil(fDeepAndFastApproximateOrderIndependentTransparencyBucketImages[InFlightFrameIndex]);
if Renderer.TransparencyMode=TpvScene3DRendererTransparencyMode.SPINLOCKDFAOIT then begin
FreeAndNil(fDeepAndFastApproximateOrderIndependentTransparencySpinLockImages[InFlightFrameIndex]);
end;
end;
end;
else begin
end;
end;
end;
procedure TpvScene3DRendererInstance.Update(const aInFlightFrameIndex:TpvInt32;const aFrameCounter:TpvInt64);
begin
fFrameGraph.Update(aInFlightFrameIndex,aFrameCounter);
end;
procedure TpvScene3DRendererInstance.Reset;
begin
fViews.Count:=0;
fCountRealViews:=0;
end;
function TpvScene3DRendererInstance.AddView(const aView:TpvScene3D.TView):TpvInt32;
begin
result:=fViews.Add(aView);
end;
function TpvScene3DRendererInstance.AddViews(const aViews:array of TpvScene3D.TView):TpvInt32;
begin
result:=fViews.Add(aViews);
end;
procedure TpvScene3DRendererInstance.CalculateCascadedShadowMaps(const aInFlightFrameIndex:TpvInt32);
begin
fCascadedShadowMapBuilder.Calculate(aInFlightFrameIndex);
end;
function TpvScene3DRendererInstance.GetJitterOffset(const aFrameCounter:TpvInt64):TpvVector2;
begin
if (Renderer.AntialiasingMode=TpvScene3DRendererAntialiasingMode.TAA) and (aFrameCounter>=0) then begin
result:=((JitterOffsets[aFrameCounter and JitterOffsetMask]-TpvVector2.InlineableCreate(0.5,0.5))*1.0)/TpvVector2.InlineableCreate(fWidth,fHeight);
end else begin
result.x:=0.0;
result.y:=0.0;
end;
end;
function TpvScene3DRendererInstance.AddTemporalAntialiasingJitter(const aProjectionMatrix:TpvMatrix4x4;const aFrameCounter:TpvInt64):TpvMatrix4x4;
begin
if Renderer.AntialiasingMode=TpvScene3DRendererAntialiasingMode.TAA then begin
result:=aProjectionMatrix*TpvMatrix4x4.CreateTranslation(GetJitterOffset(aFrameCounter));
end else begin
result:=aProjectionMatrix;
end;
end;
procedure TpvScene3DRendererInstance.AddCameraReflectionProbeViews(const aInFlightFrameIndex:TpvInt32);
const CubeMapMatrices:array[0..5] of TpvMatrix4x4=
(
(RawComponents:((0.0,0.0,-1.0,0.0),(0.0,1.0,0.0,0.0),(1.0,0.0,0.0,0.0),(0.0,0.0,0.0,1.0))), // pos x
(RawComponents:((0.0,0.0,1.0,0.0),(0.0,1.0,0.0,0.0),(-1.0,0.0,0.0,0.0),(0.0,0.0,0.0,1.0))), // neg x
(RawComponents:((-1.0,0.0,0.0,0.0),(0.0,0.0,-1.0,0.0),(0.0,-1.0,0.0,0.0),(0.0,0.0,0.0,1.0))), // pos y
(RawComponents:((-1.0,0.0,0.0,0.0),(0.0,0.0,1.0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,0.0,1.0))), // neg y
(RawComponents:((-1.0,0.0,0.0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,-1.0,0.0),(0.0,0.0,0.0,1.0))), // pos z
(RawComponents:((1.0,0.0,0.0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,1.0,0.0),(0.0,0.0,0.0,1.0))) // neg z
);//}
{ (
(RawComponents:((0.0,0.0,-1.0,0.0),(0.0,-1.0,0.0,0.0),(-1.0,0.0,0.0,0.0),(0.0,0.0,0.0,1.0))), // pos x
(RawComponents:((0.0,0.0,1.0,0.0),(0.0,-1.0,0.0,0.0),(1.0,0.0,0.0,0.0),(0.0,0.0,0.0,1.0))), // neg x
(RawComponents:((1.0,0.0,0.0,0.0),(0.0,0.0,-1.0,0.0),(0.0,1.0,0.0,0.0),(0.0,0.0,0.0,1.0))), // pos y
(RawComponents:((1.0,0.0,0.0,0.0),(0.0,0.0,1.0,0.0),(0.0,-1.0,0.0,0.0),(0.0,0.0,0.0,1.0))), // neg y
(RawComponents:((1.0,0.0,0.0,0.0),(0.0,-1.0,0.0,0.0),(0.0,0.0,-1.0,0.0),(0.0,0.0,0.0,1.0))), // pos z
(RawComponents:((-1.0,0.0,0.0,0.0),(0.0,-1.0,0.0,0.0),(0.0,0.0,1.0,0.0),(0.0,0.0,0.0,1.0))) // neg z
);//}
CubeMapDirections:array[0..5,0..1] of TpvVector3=
(
((x:1.0;y:0.0;z:0.0),(x:0.0;y:1.0;z:0.0)), // pos x
((x:-1.0;y:0.0;z:0.0),(x:0.0;y:1.0;z:0.0)), // neg x
((x:0.0;y:1.0;z:0.0),(x:0.0;y:0.0;z:-1.0)), // pos y
((x:0.0;y:-1.0;z:0.0),(x:0.0;y:0.0;z:1.0)), // neg y
((x:0.0;y:0.0;z:1.0),(x:0.0;y:1.0;z:0.0)), // pos z
((x:0.0;y:0.0;z:-1.0),(x:0.0;y:1.0;z:0.0)) // neg z
);
var Index:TpvSizeInt;
InFlightFrameState:PInFlightFrameState;
CameraPositon:TpvVector3;
View:TpvScene3D.TView;
zNeaz,zFar:TpvScalar;
begin
InFlightFrameState:=@fInFlightFrameStates[aInFlightFrameIndex];
//CameraPositon:=-fViews.Items[InFlightFrameState^.FinalViewIndex].ViewMatrix.Translation.xyz;
CameraPositon:=fCameraViewMatrix.SimpleInverse.Translation.xyz;
zNear:=abs(fZNear);
zFar:=IfThen(IsInfinite(fZFar),1024.0,abs(fZFar));
View.ProjectionMatrix.RawComponents[0,0]:=-1.0;
View.ProjectionMatrix.RawComponents[0,1]:=0.0;
View.ProjectionMatrix.RawComponents[0,2]:=0.0;
View.ProjectionMatrix.RawComponents[0,3]:=0.0;
View.ProjectionMatrix.RawComponents[1,0]:=0.0;
View.ProjectionMatrix.RawComponents[1,1]:=-1.0; // Flipped Y
View.ProjectionMatrix.RawComponents[1,2]:=0.0;
View.ProjectionMatrix.RawComponents[1,3]:=0.0;
if fZFar>0.0 then begin
View.ProjectionMatrix.RawComponents[2,0]:=0.0;
View.ProjectionMatrix.RawComponents[2,1]:=0.0;
View.ProjectionMatrix.RawComponents[2,2]:=zFar/(zNear-zFar);
View.ProjectionMatrix.RawComponents[2,3]:=-1.0;
View.ProjectionMatrix.RawComponents[3,0]:=0.0;
View.ProjectionMatrix.RawComponents[3,1]:=0.0;
View.ProjectionMatrix.RawComponents[3,2]:=(-(zNear*zFar))/(zFar-zNear);
View.ProjectionMatrix.RawComponents[3,3]:=0.0;
{ View.ProjectionMatrix:=TpvMatrix4x4.CreatePerspectiveRightHandedZeroToOne(90.0,
1.0,
abs(fZNear),
IfThen(IsInfinite(fZFar),1024.0,abs(fZFar)));//}
end else begin
View.ProjectionMatrix.RawComponents[2,0]:=0.0;
View.ProjectionMatrix.RawComponents[2,1]:=0.0;
View.ProjectionMatrix.RawComponents[2,2]:=zNear/(zFar-zNear);
View.ProjectionMatrix.RawComponents[2,3]:=-1.0;
View.ProjectionMatrix.RawComponents[3,0]:=0.0;
View.ProjectionMatrix.RawComponents[3,1]:=0.0;
View.ProjectionMatrix.RawComponents[3,2]:=(zNear*zFar)/(zFar-zNear);
View.ProjectionMatrix.RawComponents[3,3]:=0.0;
{ View.ProjectionMatrix:=TpvMatrix4x4.CreatePerspectiveRightHandedOneToZero(90.0,
1.0,
abs(fZNear),
IfThen(IsInfinite(fZFar),1024.0,abs(fZFar)));//}
end;
if fZFar<0.0 then begin
if IsInfinite(fZFar) then begin
// Convert to reversed infinite Z
View.ProjectionMatrix.RawComponents[2,2]:=0.0;
View.ProjectionMatrix.RawComponents[2,3]:=-1.0;
View.ProjectionMatrix.RawComponents[3,2]:=abs(fZNear);
end else begin
// Convert to reversed non-infinite Z
View.ProjectionMatrix.RawComponents[2,2]:=abs(fZNear)/(abs(fZFar)-abs(fZNear));
View.ProjectionMatrix.RawComponents[2,3]:=-1.0;
View.ProjectionMatrix.RawComponents[3,2]:=(abs(fZNear)*abs(fZFar))/(abs(fZFar)-abs(fZNear));
end;
end;
//View.ProjectionMatrix:=View.ProjectionMatrix*TpvMatrix4x4.FlipYClipSpace;
View.InverseProjectionMatrix:=View.ProjectionMatrix.Inverse;
for Index:=0 to 5 do begin
View.ViewMatrix:=TpvMatrix4x4.CreateTranslated(CubeMapMatrices[Index],-CameraPositon);
{ View.ViewMatrix:=TpvMatrix4x4.CreateLookAt(CameraPositon,
CameraPositon+CubeMapDirections[Index,0],
CubeMapDirections[Index,1]);//}
View.InverseViewMatrix:=View.ViewMatrix.Inverse;
if Index=0 then begin
InFlightFrameState^.ReflectionProbeViewIndex:=fViews.Add(View);
end else begin
fViews.Add(View);
end;
end;
InFlightFrameState^.CountReflectionProbeViews:=6;
end;
procedure TpvScene3DRendererInstance.DrawUpdate(const aInFlightFrameIndex:TpvInt32;const aFrameCounter:TpvInt64);
var Index:TpvSizeInt;
InFlightFrameState:PInFlightFrameState;
ViewLeft,ViewRight:TpvScene3D.TView;
ViewMatrix:TpvMatrix4x4;
begin
InFlightFrameState:=@fInFlightFrameStates[aInFlightFrameIndex];
if fViews.Count=0 then begin
ViewMatrix:=fCameraViewMatrix;
if assigned(fVirtualReality) then begin
ViewLeft.ViewMatrix:=ViewMatrix*fVirtualReality.GetPositionMatrix(0);
ViewLeft.ProjectionMatrix:=AddTemporalAntialiasingJitter(fVirtualReality.GetProjectionMatrix(0),aFrameCounter);
ViewLeft.InverseViewMatrix:=ViewLeft.ViewMatrix.Inverse;
ViewLeft.InverseProjectionMatrix:=ViewLeft.ProjectionMatrix.Inverse;
ViewRight.ViewMatrix:=ViewMatrix*fVirtualReality.GetPositionMatrix(1);
ViewRight.ProjectionMatrix:=AddTemporalAntialiasingJitter(fVirtualReality.GetProjectionMatrix(1),aFrameCounter);
ViewRight.InverseViewMatrix:=ViewRight.ViewMatrix.Inverse;
ViewRight.InverseProjectionMatrix:=ViewRight.ProjectionMatrix.Inverse;
InFlightFrameState^.FinalViewIndex:=fViews.Add([ViewLeft,ViewRight]);
fCountRealViews:=fViews.Count;
InFlightFrameState^.CountFinalViews:=2;
ViewLeft.ViewMatrix:=fVirtualReality.GetPositionMatrix(0);
ViewLeft.ProjectionMatrix:=AddTemporalAntialiasingJitter(fVirtualReality.GetProjectionMatrix(0),aFrameCounter);
ViewLeft.InverseViewMatrix:=ViewLeft.ViewMatrix.Inverse;
ViewLeft.InverseProjectionMatrix:=ViewLeft.ProjectionMatrix.Inverse;
ViewRight.ViewMatrix:=fVirtualReality.GetPositionMatrix(1);
ViewRight.ProjectionMatrix:=AddTemporalAntialiasingJitter(fVirtualReality.GetProjectionMatrix(1),aFrameCounter);
ViewRight.InverseViewMatrix:=ViewRight.ViewMatrix.Inverse;
ViewRight.InverseProjectionMatrix:=ViewRight.ProjectionMatrix.Inverse;
InFlightFrameState^.HUDViewIndex:=fViews.Add([ViewLeft,ViewRight]);
InFlightFrameState^.CountHUDViews:=2;
end else begin
ViewLeft.ViewMatrix:=ViewMatrix;
if fZFar>0.0 then begin
ViewLeft.ProjectionMatrix:=TpvMatrix4x4.CreatePerspectiveRightHandedZeroToOne(fFOV,
fWidth/fHeight,
abs(fZNear),
IfThen(IsInfinite(fZFar),1024.0,abs(fZFar)));
end else begin
ViewLeft.ProjectionMatrix:=TpvMatrix4x4.CreatePerspectiveRightHandedOneToZero(fFOV,
fWidth/fHeight,
abs(fZNear),
IfThen(IsInfinite(fZFar),1024.0,abs(fZFar)));
end;
if fZFar<0.0 then begin
if IsInfinite(fZFar) then begin
// Convert to reversed infinite Z
ViewLeft.ProjectionMatrix.RawComponents[2,2]:=0.0;
ViewLeft.ProjectionMatrix.RawComponents[2,3]:=-1.0;
ViewLeft.ProjectionMatrix.RawComponents[3,2]:=abs(fZNear);
end else begin
// Convert to reversed non-infinite Z
ViewLeft.ProjectionMatrix.RawComponents[2,2]:=abs(fZNear)/(abs(fZFar)-abs(fZNear));
ViewLeft.ProjectionMatrix.RawComponents[2,3]:=-1.0;
ViewLeft.ProjectionMatrix.RawComponents[3,2]:=(abs(fZNear)*abs(fZFar))/(abs(fZFar)-abs(fZNear));
end;
end;
ViewLeft.ProjectionMatrix:=AddTemporalAntialiasingJitter(ViewLeft.ProjectionMatrix*TpvMatrix4x4.FlipYClipSpace,aFrameCounter);
ViewLeft.InverseViewMatrix:=ViewLeft.ViewMatrix.Inverse;
ViewLeft.InverseProjectionMatrix:=ViewLeft.ProjectionMatrix.Inverse;
InFlightFrameState^.FinalViewIndex:=fViews.Add(ViewLeft);
fCountRealViews:=fViews.Count;
InFlightFrameState^.CountFinalViews:=1;
ViewLeft.ViewMatrix:=TpvMatrix4x4.Identity;
ViewLeft.ProjectionMatrix:=AddTemporalAntialiasingJitter(ViewLeft.ProjectionMatrix*TpvMatrix4x4.FlipYClipSpace,aFrameCounter);
ViewLeft.InverseViewMatrix:=ViewLeft.ViewMatrix.Inverse;
ViewLeft.InverseProjectionMatrix:=ViewLeft.ProjectionMatrix.Inverse;
InFlightFrameState^.HUDViewIndex:=fViews.Add(ViewLeft);
InFlightFrameState^.CountHUDViews:=1;
end;
end else begin
InFlightFrameState^.FinalViewIndex:=0;
InFlightFrameState^.CountFinalViews:=1;
InFlightFrameState^.HUDViewIndex:=0;
InFlightFrameState^.CountHUDViews:=1;
end;
if Renderer.GlobalIlluminatonMode=TpvScene3DRendererGlobalIlluminatonMode.CameraReflectionProbe then begin
AddCameraReflectionProbeViews(aInFlightFrameIndex);
end else begin
InFlightFrameState^.ReflectionProbeViewIndex:=-1;
InFlightFrameState^.CountReflectionProbeViews:=0;
end;
InFlightFrameState^.ReflectiveShadowMapViewIndex:=-1;
InFlightFrameState^.CountReflectiveShadowMapProbeViews:=0;
CalculateCascadedShadowMaps(aInFlightFrameIndex);
for Index:=0 to fViews.Count-1 do begin
Renderer.Scene3D.AddView(fViews.Items[Index]);
end;
InFlightFrameState^.CountViews:=fViews.Count;
fCascadedShadowMapVulkanUniformBuffers[aInFlightFrameIndex].UpdateData(fCascadedShadowMapUniformBuffers[aInFlightFrameIndex],
0,
SizeOf(TCascadedShadowMapUniformBuffer));
InFlightFrameState^.ViewRenderPassIndex:=Renderer.Scene3D.AcquireRenderPassIndex;
if InFlightFrameState^.CountCascadedShadowMapViews>0 then begin
InFlightFrameState^.CascadedShadowMapRenderPassIndex:=Renderer.Scene3D.AcquireRenderPassIndex;
end else begin
InFlightFrameState^.CascadedShadowMapRenderPassIndex:=-1;
end;
if InFlightFrameState^.CountReflectionProbeViews>0 then begin
InFlightFrameState^.ReflectionProbeRenderPassIndex:=Renderer.Scene3D.AcquireRenderPassIndex;
end else begin
InFlightFrameState^.ReflectionProbeRenderPassIndex:=-1;
end;
if InFlightFrameState^.CountReflectiveShadowMapProbeViews>0 then begin
InFlightFrameState^.ReflectiveShadowMapRenderPassIndex:=Renderer.Scene3D.AcquireRenderPassIndex;
end else begin
InFlightFrameState^.ReflectiveShadowMapRenderPassIndex:=-1;
end;
InFlightFrameState^.Jitter.xy:=GetJitterOffset(aFrameCounter);
InFlightFrameState^.Jitter.zw:=GetJitterOffset(aFrameCounter-1);
// Final viewport(s)
if InFlightFrameState^.CountFinalViews>0 then begin
Renderer.Scene3D.Prepare(aInFlightFrameIndex,
InFlightFrameState^.ViewRenderPassIndex,
InFlightFrameState^.FinalViewIndex,
InFlightFrameState^.CountFinalViews,
fWidth,
fHeight,
true,
true,
true);
end;
// Reflection probe viewport(s)
if InFlightFrameState^.CountReflectionProbeViews>0 then begin
Renderer.Scene3D.Prepare(aInFlightFrameIndex,
InFlightFrameState^.ReflectionProbeRenderPassIndex,
InFlightFrameState^.ReflectionProbeViewIndex,
InFlightFrameState^.CountReflectionProbeViews,
fReflectionProbeWidth,
fReflectionProbeHeight,
true,
true,
true);
end;
// Cascaded shadow map viewport(s)
Renderer.Scene3D.Prepare(aInFlightFrameIndex,
InFlightFrameState^.CascadedShadowMapRenderPassIndex,
InFlightFrameState^.CascadedShadowMapViewIndex,
InFlightFrameState^.CountCascadedShadowMapViews,
fCascadedShadowMapWidth,
fCascadedShadowMapHeight,
false,
true,
true);
Renderer.Scene3D.UpdateDebugPrimitives(aInFlightFrameIndex);
Renderer.Scene3D.UpdateParticles(aInFlightFrameIndex);
TPasMPInterlocked.Write(InFlightFrameState^.Ready,true);
end;
procedure TpvScene3DRendererInstance.Draw(const aSwapChainImageIndex,aInFlightFrameIndex:TpvInt32;const aFrameCounter:TpvInt64;var aWaitSemaphore:TpvVulkanSemaphore;const aWaitFence:TpvVulkanFence=nil);
const MinDeltaTime=1.0/480.0; // 480 Hz
MaxDeltaTime=1.0/1.0; // 1 Hz
LN2=0.6931471805599453;
var t:TpvDouble;
begin
FillChar(fFrustumClusterGridPushConstants,SizeOf(TpvScene3DRendererInstance.TFrustumClusterGridPushConstants),#0);
fFrustumClusterGridPushConstants.TileSizeX:=fFrustumClusterGridTileSizeX;
fFrustumClusterGridPushConstants.TileSizeY:=fFrustumClusterGridTileSizeY;
fFrustumClusterGridPushConstants.ZNear:=InFlightFrameStates[aInFlightFrameIndex].ZNear;
fFrustumClusterGridPushConstants.ZFar:=InFlightFrameStates[aInFlightFrameIndex].ZFar;
fFrustumClusterGridPushConstants.ViewRect:=TpvVector4.InlineableCreate(0.0,0.0,fWidth,fHeight);
fFrustumClusterGridPushConstants.CountLights:=Renderer.Scene3D.LightBuffers[aInFlightFrameIndex].LightItems.Count;
fFrustumClusterGridPushConstants.Size:=fFrustumClusterGridSizeX*fFrustumClusterGridSizeY*fFrustumClusterGridSizeZ;
fFrustumClusterGridPushConstants.OffsetedViewIndex:=fInFlightFrameStates[aInFlightFrameIndex].FinalViewIndex;
fFrustumClusterGridPushConstants.ClusterSizeX:=fFrustumClusterGridSizeX;
fFrustumClusterGridPushConstants.ClusterSizeY:=fFrustumClusterGridSizeY;
fFrustumClusterGridPushConstants.ClusterSizeZ:=fFrustumClusterGridSizeZ;
fFrustumClusterGridPushConstants.ZScale:=fFrustumClusterGridSizeZ/Log2(fFrustumClusterGridPushConstants.ZFar/fFrustumClusterGridPushConstants.ZNear);
fFrustumClusterGridPushConstants.ZBias:=-((fFrustumClusterGridSizeZ*Log2(fFrustumClusterGridPushConstants.ZNear))/Log2(fFrustumClusterGridPushConstants.ZFar/fFrustumClusterGridPushConstants.ZNear));
fFrustumClusterGridPushConstants.ZMax:=fFrustumClusterGridSizeZ-1;
fFrustumClusterGridGlobalsVulkanBuffers[aInFlightFrameIndex].UpdateData(fFrustumClusterGridPushConstants,0,SizeOf(TpvScene3DRendererInstance.TFrustumClusterGridPushConstants));
fLuminancePushConstants.MinLogLuminance:=Renderer.MinLogLuminance;
fLuminancePushConstants.LogLuminanceRange:=Renderer.MaxLogLuminance-Renderer.MinLogLuminance;
fLuminancePushConstants.InverseLogLuminanceRange:=1.0/fLuminancePushConstants.LogLuminanceRange;
t:=pvApplication.DeltaTime;
if t<=MinDeltaTime then begin
t:=MinDeltaTime;
end else if t>=MaxDeltaTime then begin
t:=MaxDeltaTime;
end;
fLuminancePushConstants.TimeCoefficient:=Clamp(1.0-exp(t*(-TwoPI)),0.025,1.0);
fLuminancePushConstants.MinLuminance:=exp(LN2*Renderer.MinLogLuminance);
fLuminancePushConstants.MaxLuminance:=exp(LN2*Renderer.MaxLogLuminance);
fLuminancePushConstants.CountPixels:=fWidth*fHeight*fCountSurfaceViews;
fFrameGraph.Draw(aSwapChainImageIndex,
aInFlightFrameIndex,
aFrameCounter,
aWaitSemaphore,
fVulkanRenderSemaphores[aInFlightFrameIndex],
aWaitFence);
aWaitSemaphore:=fVulkanRenderSemaphores[aInFlightFrameIndex];
TPasMPInterlocked.Write(fInFlightFrameStates[aInFlightFrameIndex].Ready,false);
end;
procedure InitializeJitterOffsets;
var Index:TpvSizeInt;
begin
for Index:=0 to CountJitterOffsets-1 do begin
JitterOffsets[Index]:=TpvVector2.InlineableCreate(GetHaltonSequence(Index+1,2),GetHaltonSequence(Index+1,3));
end;
end;
initialization
InitializeJitterOffsets;
end.
|
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
unit storable;
interface
uses
hashtable, sysutils;
type
TStorable = class;
StorableClass = class of TStorable;
PPendingFixupItem = ^TPendingFixupItem;
TPendingFixupItem = record
Destination: PPointer;
ObjectID: PtrUInt;
Next: PPendingFixupItem;
end;
TReferenceFixerProcedure = procedure (const Data: Pointer; const Value: Pointer) of object;
TMethodFixerProcedure = procedure (const Data: Pointer; const Value: TMethod) of object;
TFinalFixerProcedure = procedure () of object;
PMethod = ^TMethod;
PPendingReferenceFixerItem = ^TPendingReferenceFixerItem;
TPendingReferenceFixerItem = record
Fixer: TReferenceFixerProcedure;
Data, Value: Pointer;
Next: PPendingReferenceFixerItem;
end;
PPendingMethodFixerItem = ^TPendingMethodFixerItem;
TPendingMethodFixerItem = record
Fixer: TMethodFixerProcedure;
Data: Pointer;
Value: TMethod;
Next: PPendingMethodFixerItem;
end;
PFinalFixerItem = ^TFinalFixerItem;
TFinalFixerItem = record
Fixer: TFinalFixerProcedure;
Next: PFinalFixerItem;
end;
TFixupHashTable = specialize THashTable<PtrUInt, Pointer>;
TReadStream = class
protected
type
PMethodFixupData = ^TMethodFixupData;
TMethodFixupData = record
Field: PMethod;
MethodName: AnsiString;
end;
var
FActive: Boolean;
FObjectsRead: TFixupHashTable;
FPendingFixups: PPendingFixupItem;
FPendingReferenceFixers: PPendingReferenceFixerItem;
FPendingMethodFixers: PPendingMethodFixerItem;
FFinalFixers: PFinalFixerItem;
FInput: File;
FVersion: Cardinal;
procedure VerifyFieldType(FieldType: Byte);
function GetFilename(): AnsiString;
procedure FixupMethod(const Data: Pointer; const Value: Pointer);
public
constructor Create(var AInput: File);
destructor Destroy; override;
procedure DisableChecks();
function ReadByte: Byte;
function ReadBoolean: Boolean;
function ReadCardinal: Cardinal;
function ReadInteger: Integer;
function ReadPtrUInt: PtrUInt;
function ReadDouble: Double;
function ReadAnsiString: RawByteString;
procedure ReadByteStream(var Buffer; Length: Cardinal);
function ReadClass: StorableClass;
function ReadObject: TStorable;
procedure ReadReference(Destination: PPointer);
procedure ReadReference(Fixer: TReferenceFixerProcedure; const Data: Pointer);
procedure ReadMethod(Destination: PMethod);
procedure ReadMethod(Fixer: TMethodFixerProcedure; const Data: Pointer);
procedure AddFinalFixer(Fixer: TFinalFixerProcedure);
procedure VerifySentinel();
procedure FixupReferences();
property Version: Cardinal read FVersion;
property Filename: AnsiString read GetFilename;
end;
TWriteStream = class
protected
FOutput: File;
procedure WriteFieldType(FieldType: Byte);
public
constructor Create(var AOutput: File; Version: Cardinal);
destructor Destroy; override;
procedure WriteByte(Value: Byte);
procedure WriteBoolean(Value: Boolean);
procedure WriteCardinal(Value: Cardinal);
procedure WriteInteger(Value: Integer);
procedure WritePtrUInt(Value: PtrUInt);
procedure WriteDouble(Value: Double);
procedure WriteAnsiString(Value: RawByteString);
procedure WriteByteStream(var Buffer; Length: Cardinal);
procedure WriteClass(Value: StorableClass);
procedure WriteObject(Value: TStorable);
procedure WriteReference(Value: Pointer);
procedure WriteMethod(Value: TMethod);
procedure WriteSentinel();
end;
TStorable = class abstract
protected
{$IFOPT C+} FDebugCalledInherited: Boolean; {$ENDIF}
public
constructor Create();
constructor Read(Stream: TReadStream); virtual;
procedure Write(Stream: TWriteStream); virtual;
end;
EStorageError = class(Exception)
end;
procedure RegisterStorableClass(AClass: StorableClass);
procedure RegisterStorableClassSynonym(AClassName: AnsiString; RestoreClass: StorableClass);
function GetRegisteredClass(AClassName: AnsiString): StorableClass;
procedure StoreObjectToFile(FileName: AnsiString; Value: TStorable; Version: Cardinal);
function ReadObjectFromFile(FileName: AnsiString): TStorable;
implementation
uses
exceptions;
type
TStorableClassesHashTable = specialize THashTable<AnsiString, StorableClass>;
var
RegisteredClasses: TStorableClassesHashTable;
const { values with bit patterns unlikely to be found in typical data (so e.g. not $00, $01, $FF) }
btSignature = $AA;
btStream = $BB;
btStreamEnd = $DD;
btBoolean = $60;
btCardinal = $61;
btInteger = $62;
btPtrUInt = $63;
btDouble = $63;
btAnsiString = $65;
btByteStream = $66;
btClass = $80;
btReference = $81;
btMethod = $82;
btObject = $51;
btObjectData = $52;
btObjectEnd = $54;
btSentinel = $58;
const
ciNoClass = 'nil';
procedure RegisterStorableClass(AClass: StorableClass);
begin
Assert(not RegisteredClasses.Has(AClass.ClassName), AClass.ClassName + ' registered twice');
RegisteredClasses[AClass.ClassName] := AClass;
end;
procedure RegisterStorableClassSynonym(AClassName: AnsiString; RestoreClass: StorableClass);
begin
Assert(not RegisteredClasses.Has(AClassName), AClassName + ' registered twice');
RegisteredClasses[AClassName] := RestoreClass;
end;
function GetRegisteredClass(AClassName: AnsiString): StorableClass;
begin
Result := RegisteredClasses[AClassName];
end;
procedure StoreObjectToFile(FileName: AnsiString; Value: TStorable; Version: Cardinal);
var
F, OldF: File;
Stream: TWriteStream;
begin
Assign(F, FileName + '.$$$');
Stream := nil;
try
Rewrite(F, 1);
Stream := TWriteStream.Create(F, Version);
Stream.WriteObject(Value);
finally
Stream.Free();
Close(F);
end;
Assign(OldF, FileName);
if (FileExists(FileName)) then
Erase(OldF);
Rename(F, FileName);
end;
function ReadObjectFromFile(FileName: AnsiString): TStorable;
var
F: File;
Stream: TReadStream;
IOResultValue: Word;
begin
Assign(F, FileName);
Stream := nil;
try
{$I-} Reset(F, 1); {$I+}
IOResultValue := IOResult();
if (IOResultValue = 2) then
begin
Result := nil;
Exit;
end;
if (IOResultValue <> 0) then
RunError(IOResultValue);
Stream := TReadStream.Create(F);
try
Result := Stream.ReadObject();
Stream.FixupReferences();
except
Stream.DisableChecks();
raise;
end;
finally
Stream.Free();
Close(F);
end;
end;
constructor TReadStream.Create(var AInput: File);
begin
inherited Create();
FActive := True;
FInput := AInput;
FObjectsRead := TFixupHashTable.Create(@PtrUIntHash32);
VerifyFieldType(btStream);
FVersion := ReadCardinal();
if (ReadByte() <> SizeOf(PtrUInt)) then
raise EStorageError.Create('Stream was written on a platform with a different pointer size.');
end;
destructor TReadStream.Destroy;
var
NextFixup: PPendingFixupItem;
NextReferenceFixer: PPendingReferenceFixerItem;
NextMethodFixer: PPendingMethodFixerItem;
NextFinalFixer: PFinalFixerItem;
begin
if (FActive) then
VerifyFieldType(btStreamEnd);
while (Assigned(FPendingFixups)) do
begin
NextFixup := FPendingFixups^.Next;
Dispose(FPendingFixups);
FPendingFixups := NextFixup;
end;
while (Assigned(FPendingReferenceFixers)) do
begin
NextReferenceFixer := FPendingReferenceFixers^.Next;
Dispose(FPendingReferenceFixers);
FPendingReferenceFixers := NextReferenceFixer;
end;
while (Assigned(FPendingMethodFixers)) do
begin
NextMethodFixer := FPendingMethodFixers^.Next;
Dispose(FPendingMethodFixers);
FPendingMethodFixers := NextMethodFixer;
end;
while (Assigned(FFinalFixers)) do
begin
NextFinalFixer := FFinalFixers^.Next;
Dispose(FFinalFixers);
FFinalFixers := NextFinalFixer;
end;
FObjectsRead.Free();
inherited;
end;
procedure TReadStream.DisableChecks();
begin
FActive := False;
end;
procedure TReadStream.VerifyFieldType(FieldType: Byte);
var
Signature: Byte;
begin
if (ReadByte() <> btSignature) then
raise EStorageError.Create('Stream inconsistent - type signature marker not found');
Signature := ReadByte();
if (Signature <> FieldType) then
raise EStorageError.Create('Stream inconsistent - expected type signature ' + IntToHex(FieldType, 2) + ' but found ' + IntToHex(Signature, 2));
end;
function TReadStream.ReadByte: Byte;
begin
{$HINTS OFF} // The following statement is guaranteed to either set Result or throw an exception, but compiler doesn't know that
BlockRead(FInput, Result, SizeOf(Result));
{$HINTS ON}
end;
function TReadStream.ReadBoolean: Boolean;
begin
VerifyFieldType(btBoolean);
Result := ReadByte() = $01;
end;
function TReadStream.ReadCardinal: Cardinal;
begin
VerifyFieldType(btCardinal);
{$HINTS OFF} // The following statement is guaranteed to either set Result or throw an exception, but compiler doesn't know that
BlockRead(FInput, Result, SizeOf(Result));
{$HINTS ON}
end;
function TReadStream.ReadInteger: Integer;
begin
VerifyFieldType(btInteger);
{$HINTS OFF} // The following statement is guaranteed to either set Result or throw an exception, but compiler doesn't know that
BlockRead(FInput, Result, SizeOf(Result));
{$HINTS ON}
end;
function TReadStream.ReadPtrUInt: PtrUInt;
begin
VerifyFieldType(btPtrUInt);
{$HINTS OFF} // The following statement is guaranteed to either set Result or throw an exception, but compiler doesn't know that
BlockRead(FInput, Result, SizeOf(Result));
{$HINTS ON}
end;
function TReadStream.ReadDouble: Double;
begin
VerifyFieldType(btDouble);
{$HINTS OFF} // The following statement is guaranteed to either set Result or throw an exception, but compiler doesn't know that
BlockRead(FInput, Result, SizeOf(Result));
{$HINTS ON}
end;
function TReadStream.ReadAnsiString: RawByteString;
var
Length: Cardinal;
begin
VerifyFieldType(btAnsiString);
Result := '';
Length := ReadCardinal();
// XXX should also read dynamic code page
if (Length > 0) then
begin
SetLength(Result, Length);
BlockRead(FInput, Result[1], Length);
end;
end;
procedure TReadStream.ReadByteStream(var Buffer; Length: Cardinal);
begin
VerifyFieldType(btByteStream);
BlockRead(FInput, Buffer, Length);
end;
function TReadStream.ReadClass: StorableClass;
var
RestoreClassName: AnsiString;
begin
VerifyFieldType(btClass);
RestoreClassName := ReadAnsiString();
if (RestoreClassName <> ciNoClass) then
begin
Assert(RegisteredClasses.Has(RestoreClassName), 'Tried to restore unregistered class ' + RestoreClassName);
Result := GetRegisteredClass(RestoreClassName);
end
else
begin
Result := nil;
end;
end;
function TReadStream.ReadObject: TStorable;
var
ClassValue: StorableClass;
ObjectID: PtrUInt;
begin
VerifyFieldType(btObject);
ClassValue := ReadClass();
if (not Assigned(ClassValue)) then
begin
Result := nil;
end
else
begin
ObjectID := ReadPtrUInt();
Result := ClassValue.Read(Self);
{$IFOPT C+} Assert(Result.FDebugCalledInherited); {$ENDIF} // it's initialised to false when the object is created
FObjectsRead.Add(ObjectID, Result);
end;
VerifyFieldType(btObjectEnd);
end;
procedure TReadStream.ReadReference(Destination: PPointer);
var
Item: PPendingFixupItem;
ObjectID: PtrUInt;
begin
VerifyFieldType(btReference);
ObjectID := ReadPtrUInt();
{$HINTS OFF} // Compiler thinks casting 'nil' to PtrUInt might be non-portable
if (ObjectID <> PtrUInt(nil)) then
{$HINTS ON}
begin
New(Item);
Item^.Destination := Destination;
Item^.ObjectID := ObjectID;
Item^.Next := FPendingFixups;
FPendingFixups := Item;
end
else
begin
Destination^ := nil;
end;
end;
procedure TReadStream.ReadReference(Fixer: TReferenceFixerProcedure; const Data: Pointer);
var
Item: PPendingReferenceFixerItem;
begin
New(Item);
Item^.Fixer := Fixer;
Item^.Data := Data;
ReadReference(@(Item^.Value));
Item^.Next := FPendingReferenceFixers;
FPendingReferenceFixers := Item;
end;
procedure TReadStream.ReadMethod(Destination: PMethod);
var
MethodData: PMethodFixupData;
begin
Assert(Assigned(Destination));
VerifyFieldType(btMethod);
New(MethodData);
MethodData^.Field := Destination;
MethodData^.MethodName := ReadAnsiString();
ReadReference(@FixupMethod, MethodData);
end;
procedure TReadStream.FixupMethod(const Data: Pointer; const Value: Pointer);
var
MethodData: PMethodFixupData;
ResolvedMethodAddress: Pointer;
begin
Assert(Assigned(Data));
MethodData := PMethodFixupData(Data);
Assert(Assigned(MethodData^.Field));
if (Assigned(Value)) then
begin
ResolvedMethodAddress := TObject(Value).MethodAddress(MethodData^.MethodName);
if (not Assigned(ResolvedMethodAddress)) then
raise EStorageError.Create('Stream references non-existent method name "' + MethodData^.MethodName + '" for class ' + TObject(Value).ClassName);
MethodData^.Field^.Data := Value;
MethodData^.Field^.Code := ResolvedMethodAddress;
end
else
begin
if (MethodData^.MethodName <> '') then
raise EStorageError.Create('Stream inconsistent - method name present ("'+ MethodData^.MethodName + '") but reference is missing');
MethodData^.Field^.Data := nil;
MethodData^.Field^.Code := nil;
end;
Dispose(MethodData);
end;
procedure TReadStream.ReadMethod(Fixer: TMethodFixerProcedure; const Data: Pointer);
var
Item: PPendingMethodFixerItem;
begin
New(Item);
Item^.Fixer := Fixer;
Item^.Data := Data;
ReadMethod(@(Item^.Value));
Item^.Next := FPendingMethodFixers;
FPendingMethodFixers := Item;
end;
procedure TReadStream.AddFinalFixer(Fixer: TFinalFixerProcedure);
var
Item: PFinalFixerItem;
begin
New(Item);
Item^.Fixer := Fixer;
Item^.Next := FFinalFixers;
FFinalFixers := Item;
end;
procedure TReadStream.VerifySentinel();
begin
VerifyFieldType(btSentinel);
end;
procedure TReadStream.FixupReferences();
var
NextFixup: PPendingFixupItem;
NextReferenceFixer: PPendingReferenceFixerItem;
NextMethodFixer: PPendingMethodFixerItem;
NextFinalFixer: PFinalFixerItem;
begin
while (Assigned(FPendingFixups)) do
begin
FPendingFixups^.Destination^ := FObjectsRead[FPendingFixups^.ObjectID];
NextFixup := FPendingFixups^.Next;
Dispose(FPendingFixups);
FPendingFixups := NextFixup;
end;
while (Assigned(FPendingReferenceFixers)) do
begin
FPendingReferenceFixers^.Fixer(FPendingReferenceFixers^.Data, FPendingReferenceFixers^.Value);
NextReferenceFixer := FPendingReferenceFixers^.Next;
Dispose(FPendingReferenceFixers);
FPendingReferenceFixers := NextReferenceFixer;
end;
while (Assigned(FPendingMethodFixers)) do
begin
FPendingMethodFixers^.Fixer(FPendingMethodFixers^.Data, FPendingMethodFixers^.Value);
NextMethodFixer := FPendingMethodFixers^.Next;
Dispose(FPendingMethodFixers);
FPendingMethodFixers := NextMethodFixer;
end;
while (Assigned(FFinalFixers)) do
begin
FFinalFixers^.Fixer();
NextFinalFixer := FFinalFixers^.Next;
Dispose(FFinalFixers);
FFinalFixers := NextFinalFixer;
end;
end;
function TReadStream.GetFilename(): AnsiString;
begin
Result := FileRec(FInput).Name;
end;
constructor TWriteStream.Create(var AOutput: File; Version: Cardinal);
begin
inherited Create();
FOutput := AOutput;
WriteFieldType(btStream);
WriteCardinal(Version);
WriteByte(SizeOf(PtrUInt));
end;
destructor TWriteStream.Destroy;
begin
WriteFieldType(btStreamEnd);
inherited;
end;
procedure TWriteStream.WriteFieldType(FieldType: Byte);
begin
WriteByte(btSignature);
WriteByte(FieldType);
end;
procedure TWriteStream.WriteByte(Value: Byte);
begin
BlockWrite(FOutput, Value, SizeOf(Value));
end;
procedure TWriteStream.WriteBoolean(Value: Boolean);
begin
WriteFieldType(btBoolean);
if (Value) then
WriteByte($01)
else
WriteByte($00);
end;
procedure TWriteStream.WriteCardinal(Value: Cardinal);
begin
WriteFieldType(btCardinal);
BlockWrite(FOutput, Value, SizeOf(Value));
end;
procedure TWriteStream.WriteInteger(Value: Integer);
begin
WriteFieldType(btInteger);
BlockWrite(FOutput, Value, SizeOf(Value));
end;
procedure TWriteStream.WritePtrUInt(Value: PtrUInt);
begin
WriteFieldType(btPtrUInt);
BlockWrite(FOutput, Value, SizeOf(Value));
end;
procedure TWriteStream.WriteDouble(Value: Double);
begin
WriteFieldType(btDouble);
BlockWrite(FOutput, Value, SizeOf(Value));
end;
procedure TWriteStream.WriteAnsiString(Value: RawByteString);
var
Result: Cardinal;
begin
WriteFieldType(btAnsiString);
WriteCardinal(Length(Value));
// XXX should also write dynamic code page
if (Length(Value) > 0) then
begin
Result := 0;
BlockWrite(FOutput, Value[1], Length(Value), Result);
Assert(Result = Length(Value));
end;
end;
procedure TWriteStream.WriteByteStream(var Buffer; Length: Cardinal);
begin
WriteFieldType(btByteStream);
BlockWrite(FOutput, Buffer, Length);
end;
procedure TWriteStream.WriteClass(Value: StorableClass);
begin
WriteFieldType(btClass);
if (not Assigned(Value)) then
begin
WriteAnsiString(ciNoClass);
end
else
begin
Assert(RegisteredClasses.Has(Value.ClassName), 'Tried to store unregistered class ' + Value.ClassName);
WriteAnsiString(Value.ClassName);
end;
end;
procedure TWriteStream.WriteObject(Value: TStorable);
begin
WriteFieldType(btObject);
if (not Assigned(Value)) then
begin
WriteClass(nil);
end
else
begin
WriteClass(StorableClass(Value.ClassType));
WritePtrUInt(PtrUInt(Value));
{$IFOPT C+} Value.FDebugCalledInherited := False; {$ENDIF}
Value.Write(Self);
{$IFOPT C+} Assert(Value.FDebugCalledInherited); {$ENDIF}
end;
WriteFieldType(btObjectEnd);
end;
procedure TWriteStream.WriteReference(Value: Pointer);
begin
WriteFieldType(btReference);
{$HINTS OFF} // Compiler thinks casting a pointer to PtrUInt might not be portable
WritePtrUInt(PtrUInt(Value));
{$HINTS ON}
end;
procedure TWriteStream.WriteMethod(Value: TMethod);
var
ResolvedMethodName: AnsiString;
begin
WriteFieldType(btMethod);
if (Assigned(Value.Data)) then
begin
ResolvedMethodName := TObject(Value.Data).MethodName(Value.Code);
Assert(ResolvedMethodName <> '', 'Methods to be saved by TStorable.WriteMethod() must be published');
WriteAnsiString(ResolvedMethodName);
end
else
begin
WriteAnsiString('');
end;
WriteReference(Value.Data);
end;
procedure TWriteStream.WriteSentinel();
begin
WriteFieldType(btSentinel);
end;
constructor TStorable.Create();
begin
inherited;
Assert(RegisteredClasses.Has(ClassName), 'Class ' + ClassName + ' has not been registered with RegisterStorableClass().');
end;
constructor TStorable.Read(Stream: TReadStream);
begin
{$IFOPT C+} FDebugCalledInherited := True; {$ENDIF}
Stream.VerifyFieldType(btObjectData);
end;
procedure TStorable.Write(Stream: TWriteStream);
begin
{$IFOPT C+} FDebugCalledInherited := True; {$ENDIF}
Stream.WriteFieldType(btObjectData);
end;
initialization
RegisteredClasses := TStorableClassesHashTable.Create(@AnsiStringHash32);
finalization
RegisteredClasses.Free();
end.
|
unit uDlgEquipamentoClienteContrato;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDlg_CadastroERP, StdCtrls, Buttons, ExtCtrls, Mask, EditPesquisa;
type
TfrmDlg_EquipamentoClienteContrato = class(TfrmDlg_CadastroERP)
edtEquipamentoCliente: TEditPesquisa;
edtPeriodoVisita: TEditPesquisa;
procedure FormShow(Sender: TObject);
procedure edtEquipamentoClienteBtnNovoClick(Sender: TObject);
procedure edtEquipamentoClienteBtnEditarClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
private
FIdCliente: Integer;
procedure SetIdCliente(const Value: Integer);
{ Private declarations }
public
{ Public declarations }
property IdCliente: Integer read FIdCliente write SetIdCliente;
end;
var
frmDlg_EquipamentoClienteContrato: TfrmDlg_EquipamentoClienteContrato;
implementation
uses MinhasClasses, Comandos, uForms;
{$R *.dfm}
procedure TfrmDlg_EquipamentoClienteContrato.btnOkClick(Sender: TObject);
begin
VerificaEdit(edtEquipamentoCliente,'Infome o equipamento do ciente');
if ExisteRegistro(pDataSet,'IDCLIENTEEQUIPAMENTOS',True,True) Then
Avisa('Esse equipamento jŠ foi usado nesse contrato')
else
inherited;
end;
procedure TfrmDlg_EquipamentoClienteContrato.edtEquipamentoClienteBtnEditarClick(
Sender: TObject);
begin
inherited;
edtEquipamentoCliente.ValorChave := TrotinasForms.AbreManutencaoEquipamentoCliente(IdCliente,toEditar);
edtEquipamentoCliente.Localiza;
end;
procedure TfrmDlg_EquipamentoClienteContrato.edtEquipamentoClienteBtnNovoClick(
Sender: TObject);
begin
inherited;
edtEquipamentoCliente.ValorChave := TrotinasForms.AbreManutencaoEquipamentoCliente(IdCliente,toIncluir);
edtEquipamentoCliente.Localiza;
end;
procedure TfrmDlg_EquipamentoClienteContrato.FormShow(Sender: TObject);
begin
inherited;
ConfiguraEditPesquisa(edtEquipamentoCliente,pDataSet,tpERPClienteEquipamento,True);
ConfiguraEditPesquisa(edtPeriodoVisita,pDataSet,tpERPPeridicidade,False,'','','CODIGO','IDPERIODICIADEVISITA');
edtEquipamentoCliente.SQLComp := 'idcliente = '+IntToStr(IdCliente);
end;
procedure TfrmDlg_EquipamentoClienteContrato.SetIdCliente(const Value: Integer);
begin
FIdCliente := Value;
end;
end.
|
unit DialogForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FramesWizard, ToolWin, ComCtrls, BaseObjects, CommonFrame,
ImgList, ActnList;
type
TCommonDialogForm = class(TForm)
tlbr: TToolBar;
dlg: TDialogFrame;
ActionList1: TActionList;
actnDoNotClose: TAction;
actnLoadNext: TAction;
tlbtnCloseAfterFinish: TToolButton;
ToolButton2: TToolButton;
imgLst: TImageList;
procedure FormCreate(Sender: TObject);
procedure actnDoNotCloseExecute(Sender: TObject);
procedure actnLoadNextExecute(Sender: TObject);
procedure actnLoadNextUpdate(Sender: TObject);
private
{ Private declarations }
FEditingObjectCopy: TIDObject;
FOnAfterBasketClosed: TNotifyEvent;
FToolBarVisible: boolean;
FLoadNextAfterFinish: boolean;
procedure SetToolBarVisible(const Value: boolean);
procedure SetEditingObject(const Value: TIDObject); virtual;
function GetEditingObject: TIDObject; virtual;
protected
function GetEditingObjectName: string; virtual;
procedure NextFrame(Sender: TObject); virtual;
public
{ Public declarations }
property EditingObject: TIDObject read GetEditingObject write SetEditingObject;
property EditingObjectCopy: TIDObject read FEditingObjectCopy;
property EditingObjectName: string read GetEditingObjectName;
property OnAfterBasketClosed: TNotifyEvent read FOnAfterBasketClosed write FOnAfterBasketClosed;
procedure Save(AObject: TIDObject = nil); virtual;
procedure CancelEdit;
procedure Clear;
property ToolBarVisible: boolean read FToolBarVisible write SetToolBarVisible;
property LoadNextAfterFinish: boolean read FLoadNextAfterFinish write FLoadNextAfterFinish;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TCommonDialogFormSimpleInstantiator = class(TCommonDialogForm)
protected
procedure SetEditingObject(const Value: TIDObject); override;
function GetEditingObject: TIDObject; override;
public
class function GetInstance(AFrameClass: TFrameClass): TCommonDialogForm;
end;
var
CommonDialogForm: TCommonDialogForm;
implementation
uses Contnrs;
{$R *.dfm}
procedure TCommonDialogForm.FormCreate(Sender: TObject);
begin
//
end;
procedure TCommonDialogForm.CancelEdit;
var i: integer;
begin
for i := 0 to dlg.FrameCount - 1 do
(dlg.Frames[i] as TfrmCommonFrame).CancelEdit;
end;
constructor TCommonDialogForm.Create(AOwner: TComponent);
begin
inherited;
dlg.OnBeforePageChange := NextFrame;
Width := 718;
Height := 527;
Position := poMainFormCenter;
{ TODO : тулбар - на будущее }
ToolBarVisible := false;
end;
destructor TCommonDialogForm.Destroy;
begin
inherited;
end;
function TCommonDialogForm.GetEditingObject: TIDObject;
begin
Result := (dlg.Frames[0] as TfrmCommonFrame).EditingObject;
end;
function TCommonDialogForm.GetEditingObjectName: string;
begin
Result := '';
end;
procedure TCommonDialogForm.NextFrame(Sender: TObject);
begin
if Dlg.LastActiveFrameIndex < Dlg.NextActiveFrameIndex then
begin
// проверка при переходе от фрэйма к фрэйму
(dlg.Frames[dlg.ActiveFrameIndex + 1] as TfrmCommonFrame).EditingObject := EditingObject;
(dlg.Frames[dlg.ActiveFrameIndex + 1] as TfrmCommonFrame).Check;
end
else
begin
(dlg.Frames[dlg.ActiveFrameIndex - 1] as TfrmCommonFrame).EditingObject := EditingObject;
(dlg.Frames[dlg.ActiveFrameIndex - 1] as TfrmCommonFrame).Check;
end;
Caption := EditingObjectName + ' (шаг ' + IntToStr(dlg.NextActiveFrameIndex + 1) + ' из ' + IntToStr(dlg.FrameCount) + ')';
end;
procedure TCommonDialogForm.Save(AObject: TIDObject = nil);
var i, iIndex: integer;
frm: TfrmCommonFrame;
oNext: TIDObject;
begin
for i := 0 to dlg.FrameCount - 1 do
begin
// если не было ничего загружено
// то при сохранении может получиться так,
// что данные будут почищены
// поэтому прежде чем сохранить
// обязательно загрузить инфу
// с другой стороны может быть случай,
// когда этого как раз делать не надо
// добавиль новый элемент
// editingObject не назначен
// в результате переназначения теряется редактирование
// поэтому переназначаем только в том случае,
// если это не вновь добавленный объект
frm := dlg.Frames[i] as TfrmCommonFrame;
if (not Assigned(frm.EditingObject))
and Assigned(EditingObjectCopy)
and (EditingObjectCopy.ID > 0) then
frm.EditingObject := EditingObjectCopy;
(dlg.Frames[i] as TfrmCommonFrame).Save(AObject);
end;
if not LoadNextAfterFinish then
dlg.ActiveFrameIndex := 0;
if LoadNextAfterFinish then
begin
iIndex := EditingObject.Collection.IndexOf(EditingObject);
if iIndex + 1 < EditingObject.Collection.Count then iIndex := iIndex + 1
else iIndex := 0;
if iIndex >= EditingObject.Collection.Count then dlg.CloseAfterFinish := true
else
begin
oNext := EditingObject.Collection.Items[iIndex];
for i := 0 to dlg.FrameCount - 1 do
(dlg.Frames[i] as TfrmCommonFrame).EditingObject := nil;
EditingObject := oNext;
dlg.ActiveFrameIndex := 0;
end;
end;
end;
procedure TCommonDialogForm.SetEditingObject(const Value: TIDObject);
begin
Clear;
(dlg.Frames[0] as TfrmCommonFrame).EditingObject := Value;
end;
procedure TCommonDialogForm.SetToolBarVisible(const Value: boolean);
begin
FToolBarVisible := Value;
tlbr.Visible := FToolBarVisible;
end;
procedure TCommonDialogForm.Clear;
var i: integer;
begin
FEditingObjectCopy := nil;
for i := 0 to dlg.FrameCount - 1 do
(dlg.Frames[i] as TfrmCommonFrame).Clear;
end;
procedure TCommonDialogForm.actnDoNotCloseExecute(Sender: TObject);
begin
actnDoNotClose.Checked := not actnDoNotClose.Checked;
dlg.CloseAfterFinish := not actnDoNotClose.Checked;
end;
procedure TCommonDialogForm.actnLoadNextExecute(Sender: TObject);
begin
actnLoadNext.Checked := not actnLoadNext.Checked;
LoadNextAfterFinish := actnLoadNext.Checked;
end;
procedure TCommonDialogForm.actnLoadNextUpdate(Sender: TObject);
begin
actnLoadNext.Enabled := not dlg.CloseAfterFinish;
end;
function TCommonDialogFormSimpleInstantiator.GetEditingObject: TIDObject;
begin
Assert(dlg.FrameCount > 0, 'FrameCount не может быть равен 0');
Result := (dlg.Frames[0] as TfrmCommonFrame).EditingObject;
end;
class function TCommonDialogFormSimpleInstantiator.GetInstance(
AFrameClass: TFrameClass): TCommonDialogForm;
const FSimpleInstance: TCommonDialogForm = nil;
begin
if not Assigned(FSimpleInstance) then
begin
FSimpleInstance := TCommonDialogFormSimpleInstantiator.Create(Application.MainForm);
FSimpleInstance.ToolBarVisible := false;
FSimpleInstance.dlg.Buttons := [btFinish, btCancel];
FSimpleInstance.dlg.ActiveFrameIndex := 0;
end;
FSimpleInstance.dlg.Clear;
FSimpleInstance.dlg.AddFrame(AFrameClass);
Result := FSimpleInstance;
end;
procedure TCommonDialogFormSimpleInstantiator.SetEditingObject(
const Value: TIDObject);
begin
Clear;
(dlg.Frames[0] as TfrmCommonFrame).EditingObject := Value;
end;
end.
|
unit StrUtil;
interface
uses
Classes;
type
TFilterFormatter = class
public
constructor Create();
destructor Destroy(); override;
procedure AddFilter(s: string);
function GetString(): string;
protected
FList: TStringList;
end;
implementation
{ TFilterFormatter }
constructor TFilterFormatter.Create;
begin
FList := TStringList.Create;
end;
destructor TFilterFormatter.Destroy;
begin
FList.Free;
inherited;
end;
procedure TFilterFormatter.AddFilter(s: string);
begin
FList.Add(s);
end;
function TFilterFormatter.GetString: string;
var
i: Integer;
begin
Result := '';
for i := 0 to FList.Count - 1 do
begin
if Result <> '' then
Result := Result + ' and ';
Result := Result + FList[i];
end;
end;
end.
|
unit _RES;
/////////////////////////////////////////////////////////////////////
//
// Hi-Files Version 2
// Copyright (c) 1997-2004 Dmitry Liman [2:461/79]
//
// http://hi-files.narod.ru
//
/////////////////////////////////////////////////////////////////////
interface
uses
Objects, Views, Dialogs;
procedure OpenResource;
procedure CloseResource;
function LoadString( id: Word ) : String;
function ShoeHorn( Dialog: PDialog; Control: PView ) : PView;
procedure SwapDlg(OldDlg, NewDlg : PDialog);
var
Res: PResourceFile;
const
// AreaFix
_SLogSendingHelp = 128;
_SLogHelpNotAvail = 129;
_SReplyHelpNotAvail = 130;
_SLogSendingEchoList = 131;
_SReplyListFooter = 132;
_SLogSendingEchoQuery = 133;
_SReplyQueryFooter = 134;
_SLogInvalidAfixCmd = 135;
_SReplyInvalidAfixCmd = 136;
_SReplyAlreadyDL = 137;
_SLogDLinked = 138;
_SReplyDLinked = 139;
_SLogDUnlinked = 140;
_SReplyUnlinked = 141;
_SLogUUnlinked = 142;
_SPauseWarning = 143;
_SReplyWildNotFound = 144;
_SLogNoSuchEcho = 145;
_SReplyNoSuchEcho = 146;
_SSubChangedSubj = 147;
_SYourAfixReqSubj = 148;
_SLogAfixReply = 149;
_SLogWrongAfixPw = 150;
_SReplyWrongAfixPw = 151;
_SLogStartAfix = 152;
_SLogStopAfix = 153;
_SLogUplinksLost = 154;
_SNotifyUplinksLost = 155;
_SNotifyWarnSubj = 156;
_SLogDownlinksLost = 157;
_SCfmDelAvailRec = 158;
_SReplyReqForw = 159;
_SLogWriteFwd = 160;
_SLogSendingAvail = 161;
_SLogInvalidNotifyCmd = 162;
_SReplyInvalidNotifyCmd = 163;
_SNotifyChanged = 164;
_SModeTurnedOn = 165;
_SModeTurnedOff = 166;
_SPauseChanged = 167;
_SEchoDenied = 168;
_SAfixEchoDenied = 169;
_SAfixReplyRW = 170; // 170..175
// AreaPane
_SAloneCmtText = 200;
_SMissingText = 201;
_SInvalidNumeric = 202;
_ScantMoveToSameArea = 203;
_SCantMoveAlreadyExists = 204;
_SLogMovingFileToArea = 205;
_SCantMoveSrcNotFound = 206;
_SMovingFailed = 207;
_SConfirmDelFile = 208;
_SCantDelFile = 209;
_SCantAloneNearAlone = 210;
_SViewerError = 211;
_SNoViewer = 212;
_SViewersCaption = 213;
_SConfirmSaveFilesBbs = 214;
_SMoreDLPathCaption = 215;
_SCantRenameAreaExists = 216;
_SNewAreaName = 217;
_SCantDelHostArea = 218;
_SConfirmDelArea = 219;
_SConfirmDelMultiArea = 220;
_SConfirmDelMultiFile = 221;
_SFileAreaCounter = 222; // 222..224
_SFileCounter = 225; // 225..227
_SDirAdded = 228;
// EchoPane
_SNoHostArea = 250;
_SNoValidDLPath = 251;
// _SUplinksCaption = 252;
// _SDownlinksCaption = 253;
_SHooksCaption = 254;
_SCantRenEchoNameExists = 255;
_SNewEchoName = 256;
_SConfirmDelEcho = 257;
// Finder
_SLogAnswering = 300;
_SLogMsgFailed = 301;
_SLogPktFailed = 302;
_SStartFinder = 303;
// Gen
_SBadAnFile = 350;
_SBadAnVer = 351;
_SAnFailed = 352;
_SLogCheckingAn = 353;
_SOpeningAnFile = 354;
_SCantOpenAn = 355;
_SLogSavingAn = 356;
_ScantCreateAn = 357;
_SLogNoDizInArc = 358;
_SCantSetTmpDir = 359;
_SCantDelTmpFile = 360;
_SExtRunError = 361;
_SExtRunErrLevel = 362;
_SDizExtracted = 363;
_SRunExternal = 364;
_SDizNotBuilt = 365;
_SDizBuilt = 366;
_SBadFileDate = 367;
_SDateShouldFixed = 368;
_SForceDiz = 369;
_SUpdatedFile = 370;
_SNewFile = 371;
_SCantSetFTime = 372;
_SLogPostInArea = 373;
_SBestAreaFailedNoDLC = 374;
_SLogScanningFileBase = 375;
_SScanFailedNoBbs = 376;
_SLogExportFreq = 377;
_SLogBuildingBest = 378;
_SLogBuildingAll = 379;
_SLogLeavingNew = 380;
_SLogBuildingNew = 381;
_SLogBuildingNewRep = 382;
_SLogNothingToAn = 383;
_SLogNoNewFiles = 384;
_SLogUnrarOpenError = 385;
_SLogUnrarError = 386;
_SLogUnrarHdrBroken = 387;
_SLogAnCreated = 388;
_SLeavingNewFiles = 389;
_SCfmIgnoreErrors = 390;
// Hatch
_SHatchCaption = 400;
_SFileNameCaption = 401;
_SFileNotFound = 402;
_SLogStartHatcher = 403;
_SCantCopyToInbound = 404;
_SFileHatchOk = 405;
_STicBuilt = 406;
_SGetShortPathFailed = 407;
_SRenameToShortFailed = 408;
_SGetDizFailed = 409;
_SHatchDone = 410;
// Import
_SNameExists = 450;
_SDLPathExists = 451;
_SDLPathNotExists = 452;
_SAreaRejected = 453;
_SImportingTree = 454;
_SImportSummary = 455;
_SImportHiFiCaption = 456;
_SImportingHiFi = 457;
_SLogImportingHiFi = 458;
_SLogJustAddLinks = 459;
_SLogEchoCreated = 460;
_SLogPassthrough = 461;
_SLogParking = 462;
_SLogNewHostCreated = 463;
_SLogAreaNameMissing = 464;
_SBadULAddr = 465;
_SBadDLAddr = 466;
_SBadLineIgnored = 467;
_SImportEchoSummary = 468;
_SImportAllfixCaption = 469;
_SImportingAllfix = 470;
_SImpLnkAfixCaption = 471;
_SImportingAfixLnk = 472;
_SLogAddLink = 473;
_SImportLinkSummary = 474;
_SImportDMCaption = 475;
_SImportingDMT = 476;
_SImportBlstCaption = 477;
_SImportingBlst = 478;
_SBlstBbsSummary = 479;
// Main
_SSaveConfig = 500;
_SCmdLineError = 501;
_SCreateNewCfg = 502;
_SNewCfgDisabled = 503;
_SBatchRejected = 504;
_SBatchRunning = 505;
_SBatchInterrupted = 506;
_SNoHelpFile = 507;
// MyLib
_SInvalidBool = 550;
_SAskCreateDir = 551;
_SMkDirFailed = 552;
_SDirNotExists = 553;
_SFileMustExists = 554;
_SQuotedExpected = 555;
// Setup
_SChooseFACtl = 600;
_SBadBakLevel = 601;
_SDizCaption = 602;
_SArcCaption = 603;
_SFetchCaption = 604;
_SDefCmtCaption = 605;
_SBadStrCaption = 606;
_SFinderRobotsCaption = 607;
_SForgetCaption = 608;
_SAddrExists = 609;
_SBadAddr = 610;
_SCfmFileApi = 611;
_SFapiNotAvail = 612;
_SFapiNeedCompact = 613;
_SExclCaption = 614;
_SNeedReformat = 615;
_SEditDenyCaption = 616;
// SetupEcho
_SAfixRobots = 650;
_SCantChgAddrDupe = 651;
_SEmptyPwd = 652;
_SCantAddLinkDupe = 653;
_SCantAddLinkEmptyPwd = 654;
_SAskKillLink = 655;
_SUnknownAvailLink = 656;
_SAvailAddrDupe = 657;
_SBrowseAvailCaption = 658;
_SCfmClrAllRights = 659;
_SCfmClrWriteRights = 660;
// _BSY
_SBusyCaption = 700;
_SBusyMsg1 = 701;
_SBusyMsg2 = 702;
_SKillFlagBtn = 703;
_SExitBtn = 704;
_SCantKillFlag = 705;
_SWaiting = 706;
// _CFG
_SBadCmdLine = 750;
_SBadChapter = 751;
_SBadToken = 752;
_SBadPoster = 753;
_SBadArea = 754;
_SBadLinks = 755;
_SLinkDupe = 756;
_SBadLinkToken = 757;
_SLogReadingCfg = 758;
_SReadingCfg = 759;
_SLogSavingCfg = 760;
_SBadAvail = 761;
_SBadAvailToken = 762;
// _Fareas
//_SWrongCmt = 800; died
_SFilesBbsMissing = 801;
_SNoFilesBbs = 802;
_SDroppingMiss = 803;
_SLogRescan = 804;
_SNoDLPath = 805;
_SBadFListFormat = 806;
_SBadParanoic = 807;
_SDupeAreaDef = 808;
_SNoHost = 809;
_SNeedHost = 810;
_SNoFileAreaCtl = 811;
_SReadingFileAreaCtl = 812;
// _SBadDir = 813; died
_SNoActiveArea = 814;
_SSavingFileAreaCtl = 815;
_SCantCreateFile = 816;
_SReadingFilesBbs = 817;
_SSavingFilesBbs = 818;
_SDropMissFiles = 819;
_SReadingMagic = 820;
_SSavingMagic = 821;
_SSaveMagicFailed = 822;
_SAliasRefNotFound = 823;
_SLinkingMagic = 824;
_SAskSaveAreaDef = 825;
_SLogLoadingAvail = 826;
_SBadEchoState = 827;
// _Inspector
_SAloneText = 850;
// _Log
_SMsgWinCaption = 900;
// _Report & _Inspector
_SCantCreateRep = 950;
_SCancelled = 951;
_SCancelBtn = 952;
_SConfirmCancel = 953;
// _Script
_SScriptInitComplete = 1000;
_SScriptDoneComplete = 1001;
_SBadOperator = 1002;
_SEnterFileFrame = 1003;
_SLeaveFileFrame = 1004;
_SUpdateFileFrameAlone = 1005;
_SUpdateFileFrameFile = 1006;
_SUpdateFileFrameCompl = 1007;
_SEnterRelFileFrame = 1008;
_SExitRelFileFrame = 1009;
_SEnterCreAreaFrame = 1010;
_SExitCreAreaFrame = 1011;
_SEnterUpdtAreaFrame = 1012;
_SExitUpdtAreaFrame = 1013;
_SEnterRelAreaFrame = 1014;
_SExitRelAreaFrame = 1015;
_SReformatOutsideFLoop = 1016;
_SNestedFLoop = 1017;
_SOrphanFLoop = 1018;
_SNestedALoop = 1019;
_SIfNotBool = 1020;
_SOrphanElse = 1021;
_SOrphanEndif = 1022;
_SEmptyDecList = 1023;
_SWhileNotBool = 1024;
_SOrphanWhile = 1025;
_SNoBlockBreak = 1026;
_SNewAreaDupe = 1027;
_SBadNewArea = 1028;
_SLogIncluding = 1029;
_SOrphanCopy = 1030;
_SCopyAreaNotExists = 1031;
_SCopySameArea = 1032;
_SCopyNeedVirtual = 1033;
_SCopyFileDupe = 1034;
_SBadValType = 1035;
_SMismatchedBlock = 1036;
_SBlockTooNested = 1037;
_SLogRunningScript = 1038;
_SScriptCancelled = 1039;
_SBadRedirArg = 1040;
_SLogRedir = 1041;
// _Tic
_SBadSeenBy = 1050;
_SBadTicToken = 1051;
_STicBuild = 1052;
_SCantCreBadTicLog = 1053;
_SCantMoveRej = 1054;
_STicRejected = 1055;
_SOldAttachCut = 1056;
_SOldTicDied = 1057;
_SMsgHi = 1058;
_SLogNotifying = 1059;
_SLogAutoCre = 1060;
_SLogHostCre = 1061;
_SMsgAutoCre = 1062;
_SCantBsoLock = 1063;
_SBsoTimeout = 1064;
_SCantKillBsy = 1065;
_SCantOpenTempLo = 1066;
_SCantCreLo = 1067;
_SCantAppendLo = 1068;
_SCantReadTempLo = 1069;
_SUpdatingLo = 1070;
_SRestoringLo = 1071;
_SErrorSavingLo = 1072;
_SKillingDupe = 1073;
_SFailed = 1074;
_SCantKillFile = 1075;
_SDupeKilled = 1076;
_SErrCalcCrc = 1077;
_SDupeFound = 1078;
_SAcceptingTarget = 1079;
_SErrorParking = 1080;
_SReplacesKill = 1081;
_SReplacesFailed = 1082;
_SLogSkippingRepl = 1083;
_SHookExec = 1084;
_SExecError = 1085;
_SErrRetCode = 1086;
_SLogEatTic = 1087;
_SNotOurTic = 1088;
_SOurHatchedTic = 1089;
_SBadHatchPw = 1090;
_SSenderNotOurLink = 1091;
_SBadTicPw = 1092;
_SNoEchotag = 1093;
_SEchoNotExists = 1094;
_SLogAutolinked = 1095;
_SMsgNewUplink = 1096;
_SNotUplink = 1097;
_SNoGlueFileName = 1098;
_SNoGlueFile = 1099;
_SUnableCRC = 1100;
_SCRCFailed = 1101;
_SNoPasruDir = 1102;
_SLogTicPassed = 1104;
_SLogFileDied = 1105;
_SLogFileNotDied = 1106;
_SLogCleanPasru = 1107;
_SLogTicTosserStart = 1108;
_SLogTicTosserStop = 1109;
_SEchoDown = 1110;
_SReplyAvailFrom = 1111;
_SExpandToLFN = 1112;
_STicEchoDenied = 1113;
_SReadingBHatch = 1114;
_SJobNeed = 1115;
_SUnknownOp = 1116;
_SBatchComplete = 1117;
_SUnclosedJob = 1118;
_SDoingJob = 1119;
_SJobCancel = 1120;
_SBHatchStarted = 1121;
_SCouldNotCopyToFileBox = 1122;
_SCouldNotCreateFileBox = 1123;
_STryBso = 1124;
_SFileBoxRootMissed = 1125;
_SGlueHidden = 1126;
_SLogTicHeader = 1127;
// _pal
_SOpenPalCaption = 1200;
_SSavePalCaption = 1201;
_SBadPalFile = 1202;
_SConfirmOverwrite = 1203;
// _fopen
_SScanningDrives = 5000;
{ ========================================================= }
implementation
uses
SysUtils, Editors, MyLib;
var
StrList: PStringList;
{ --------------------------------------------------------- }
{ OpenResource }
{ --------------------------------------------------------- }
procedure OpenResource;
var
S: PBufStream;
begin
S := New( PBufStream, Init(ChangeFileExt(HomeDir, '.res'), stOpenRead, 8 * 1024 ));
if S^.Status <> stOk then
begin
Writeln( '! Fatal error: can''t open resource file'^M^J );
Dispose( S, Done );
Abort;
end;
Res := New( PResourceFile, Init( S ) );
StrList := PStringList(Res^.Get( 'STRLIST' ));
end; { OpenResource }
{ --------------------------------------------------------- }
{ CloseResource }
{ --------------------------------------------------------- }
procedure CloseResource;
begin
Destroy( StrList );
Destroy( Res );
end; { CloseResource }
{ --------------------------------------------------------- }
{ LoadString }
{ --------------------------------------------------------- }
function LoadString( id: Word ) : String;
begin
Result := StrList^.Get( id );
if Result = '' then
begin
Writeln( 'Fatal error: no string resource, id=' + IntToStr(id) );
Abort;
end;
end; { LoadString }
{ --------------------------------------------------------- }
{ ShoeHorn }
{ --------------------------------------------------------- }
const
ofShoeHorn = $8000; { Shoehorn bit }
function ShoeHorn( Dialog: PDialog; Control: PView ) : PView;
var
DummyControl : PView;
LabelP : PLabel;
OldListViewer : PListViewer;
NewListViewer : PListViewer;
OldButton : PButton;
NewButton : PButton;
OldCluster : PCluster;
NewCluster : PCluster;
OldILine : PInputLine;
NewILine : PInputLine;
OldSText : PStaticText;
NewSText : PStaticText;
OldPText : PParamText;
NewPText : PParamText;
NewMemo : PMemo;
I : Integer;
R : TRect;
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
{ }
{ TestLabelPtr }
{ }
{ function TestLabelPtr(View : PView) : boolean; far; }
{ }
{ Description This function returns True if View is a label and its }
{ owner is DummyControl. }
{ }
{_____________________________________________________________________}
function TestLabelPtr(View : PView) : boolean; far;
begin {TestLabelPtr}
if (TypeOf(View^) = TypeOf(TLabel)) and
(PLabel(View)^.Link = PView(DummyControl)) then
begin
TestLabelPtr := True;
Exit;
end;
TestLabelPtr := False;
end; {TestLabelPtr}
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
{ }
{ TestShoeHornBit }
{ }
{ function TestShoeHornBit(View : PView) : boolean; far; }
{ }
{ Description This function returns True if the shoehorn bit, }
{ ofShoeHorn, is set in View's Options. }
{ }
{_____________________________________________________________________}
function TestShoeHornBit(View : PView) : boolean; far;
begin {TestShoeHornBit}
TestShoeHornBit := ((View^.Options and ofShoeHorn) <> 0);
end; {TestShoeHornBit}
begin {bShoeHorn}
{ Look in Z-order for first control with shoehorn bit set }
DummyControl := PView(Dialog^.FirstThat(@TestShoeHornBit));
if (DummyControl = NIL) then { Error ! }
begin
ShoeHorn := NIL;
Exit;
end
else
begin
{ See if a label points to the dummy control so we can change }
{ its link field. }
LabelP := PLabel(Dialog^.FirstThat(@TestLabelPtr));
if (LabelP <> NIL) then
LabelP^.Link := Control;
with Control^ do
begin
{ TView specific fields }
Owner := DummyControl^.Owner;
Next := DummyControl^.Next;
Origin := DummyControl^.Origin;
Size := DummyControl^.Size;
HelpCtx := DummyControl^.HelpCtx;
Options := DummyControl^.Options and not ofShoeHorn;
end;
{ Make sure the circular list is intact }
DummyControl^.Prev^.Next := Control;
{ We need to clear the owner field so that we avoid being }
{ deleted from the dialog box during Done (see TGroup.Done) }
DummyControl^.Owner := NIL;
{ Check the type of the original control to see which control }
{ specific fields we have to transfer to the new control. }
if (TypeOf(DummyControl^) = TypeOf(TListViewer)) then
begin
OldListViewer := PListViewer(DummyControl);
NewListViewer := PListViewer(Control);
with NewListViewer^ do
begin
{ TListViewer specific fields }
HScrollBar := OldListViewer^.HScrollBar;
if (HScrollBar <> NIL) then
HScrollBar^.SetParams(0,0,Range-1,1,1);
VScrollBar := OldListViewer^.VScrollBar;
if (VScrollBar <> NIL) then
VScrollBar^.SetParams(0,0,Range-1,Size.Y-1,1);
NumCols := OldListViewer^.NumCols;
TopItem := 0;
if (Dialog^.Current = PView(OldListViewer)) then
NewListViewer^.Select;
Dispose(OldListViewer,Done);
end;
end
else if (TypeOf(DummyControl^) = TypeOf(TButton)) then
begin
OldButton := PButton(DummyControl);
NewButton := PButton(Control);
with NewButton^ do
begin
{ TButton specific fields }
Title := AllocStr(OldButton^.Title^);
Command := OldButton^.Command;
Flags := OldButton^.Flags;
AmDefault := OldButton^.AmDefault;
if (Dialog^.Current = PView(OldButton)) then
NewButton^.Select;
Dispose(OldButton,Done);
end;
end
else if ((TypeOf(DummyControl^) = TypeOf(TRadioButtons)) or
(TypeOf(DummyControl^) = TypeOf(TCheckBoxes))) then
begin
OldCluster := PCluster(DummyControl);
NewCluster := PCluster(Control);
with NewCluster^ do
begin
{ TCluster specific fields }
Value := OldCluster^.Value;
Sel := OldCluster^.Sel;
{ If Strings is empty, then add the strings from the }
{ base control; otherwise, allow the user to also }
{ specify the strings at run time. }
if (Strings.Count = 0) then
begin
Strings.FreeAll;
Strings.SetLimit(OldCluster^.Strings.Count);
for I := 0 to (OldCluster^.Strings.Count - 1) do
Strings.AtInsert(I,
AllocStr(PString(OldCluster^.Strings.At(I))^) );
end;
if (Dialog^.Current = PView(OldCluster)) then
NewCluster^.Select;
Dispose(OldCluster,Done);
end;
end
else if (TypeOf(DummyControl^) = TypeOf(TInputLine)) then
begin
OldILine := PInputLine(DummyControl);
NewILine := PInputLine(Control);
with NewILine^ do
begin
{ TInputLine specific fields }
if (Data <> nil) then
FreeMem( Data, MaxLen + 1 );
GetMem(Data, OldILine^.MaxLen + 1);
Data^ := OldILine^.Data^;
MaxLen := OldILine^.MaxLen;
CurPos := OldILine^.CurPos;
FirstPos := OldILine^.FirstPos;
SelStart := OldILine^.SelStart;
SelEnd := OldILine^.SelEnd;
end;
if (Dialog^.Current = PView(OldILine)) then
NewILine^.Select;
Dispose(OldILine,Done);
end
else if (TypeOf(DummyControl^) = TypeOf(TStaticText)) then
begin
OldSText := PStaticText(DummyControl);
NewSText := PStaticText(Control);
with NewSText^ do
begin
{ TStaticText specific fields }
Text := AllocStr(OldSText^.Text^);
end;
if (Dialog^.Current = PView(OldSText)) then
NewSText^.Select;
Dispose(OldSText,Done);
end
else if (TypeOf(DummyControl^) = TypeOf(TParamText)) then
begin
OldPText := PParamText(DummyControl);
NewPText := PParamText(Control);
with NewPText^ do
begin
{ TParamText specific fields }
Text := AllocStr(OldPText^.Text^);
ParamCount := OldPText^.ParamCount;
end;
if (Dialog^.Current = PView(OldPText)) then
NewPText^.Select;
Dispose(OldPText,Done);
end
else if TypeOf( DummyControl^ ) = TypeOf( TView ) then
begin
Dispose( PView(DummyControl), Done );
end;
ShoeHorn := Control;
end;
end; {ShoeHorn}
{***********************************************************************}
{ }
{ SwapDlg }
{ Replace a standard dialog with a user dialog box }
{ }
{ procedure SwapDlg( OldDlg, NewDlg : PDialog ); }
{ }
{ OldDlg Pointer to the dialog box which is }
{ being replaced. }
{ NewDlg Pointer to the user dialog box. }
{ }
{ Description This procedure copies all data from the OldDlg original }
{ dialog box into the NewDlg object which is created by }
{ the user. This provides the programmer with a simple }
{ way to use ResEdit to create a dialog box "shell" which }
{ can contain any number of standard or "custom" controls, }
{ and then swap a user dialog box object derived from }
{ TDialog to contain the controls. The user dialog box }
{ object can then implement its own event handling or }
{ override any TDialog method. }
{ }
{ We start by copying all of the data from the old dialog }
{ to the new dialog. Then we change the pointers of the }
{ old dialog to nil in preparation for disposal since the }
{ new dialog will be maintaining the previous data. Next, }
{ all of the Owner fields of the dialog box subviews are }
{ updated to reflect the change in ownership. Finally, the }
{ old dialog box is disposed and a pointer to the new one }
{ is returned. }
{_______________________________________________________________________}
procedure SwapDlg(OldDlg, NewDlg : PDialog);
{+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
{ }
{ ChangeOwner }
{ Change the owner field to that of the new dialog }
{ }
{ procedure ChangeOwner( PSubView : PView ); far; }
{ }
{ PSubView Pointer to the control whose owner }
{ field will be changed. }
{ }
{ Description This iterator procedure is used in a dialog box to }
{ change the Owner field of each subview to the address }
{ of the new dialog box NewDlg. }
{_____________________________________________________________________}
procedure ChangeOwner(PSubView : PView); far;
begin {ChangeOwner}
PSubView^.Owner := NewDlg;
end; {ChangeOwner}
var
POld, PNew : Pointer;
begin {SwapDlg}
if (NewDlg^.Frame <> nil) then
Dispose(NewDlg^.Frame, Done);
POld := Ptr(Ofs(OldDlg^)+SizeOf(Word));
PNew := Ptr(Ofs(NewDlg^)+SizeOf(Word));
Move(POld^,PNew^,SizeOf(OldDlg^)-2);
with OldDlg^ do
begin
Owner := nil;
Next := nil;
Last := nil;
Current := nil;
Buffer := nil;
Frame := nil;
Title := nil;
end;
NewDlg^.ForEach(@ChangeOwner);
Dispose(OldDlg,Done);
end; {SwapDlg}
end.
|
unit Security.Authentication.PasswordValidator;
interface
uses
Security.Authentication.IPasswordValidator
, Data.Repositories.IUsersRepository
;
type
TPasswordValidator = class (TInterfacedObject, IPasswordValidator)
private
FUsersRepository : IUsersRepository;
public
constructor Create(usersRepository : IUsersRepository); reintroduce;
function Validate(userName, password: string): Boolean;
end;
implementation
uses
Data.Entities.User,
Spring.Cryptography,
Spring.Container;
{ TPasswordValidator }
constructor TPasswordValidator.Create(usersRepository: IUsersRepository);
begin
inherited Create();
FUsersRepository := usersRepository;
end;
function TPasswordValidator.Validate(userName, password: string): Boolean;
//TODO: delegate HASH calculation to a separate class
function calculateMD5(data: string): string;
var
md5 : IMD5;
begin
md5 := CreateMD5;
Result := md5.ComputeHash(data).ToHexString();;
end;
var
User : TUser;
begin
User := nil;
Result := False;
User := FUsersRepository.GetByLogin(userName);
if User <> nil then
begin
Result := User.PasswdHash = calculateMD5(password + User.PasswdSalt);
User.Free;
end;
end;
initialization
GlobalContainer.RegisterType<TPasswordValidator>.Implements<IPasswordValidator>;
end.
|
{*******************************************************}
{ }
{ Turbo Pascal Runtime Library }
{ Overlay Interface Unit }
{ }
{ Copyright (C) 1988,92 Borland International }
{ }
{*******************************************************}
unit Overlay;
{$I-,S-}
interface
const
ovrOk = 0;
ovrError = -1;
ovrNotFound = -2;
ovrNoMemory = -3;
ovrIOError = -4;
ovrNoEMSDriver = -5;
ovrNoEMSMemory = -6;
const
OvrResult: Integer = 0;
OvrEmsPages: Word = 0;
OvrTrapCount: Word = 0;
OvrLoadCount: Word = 0;
OvrFileMode: Byte = 0;
type
OvrReadFunc = function(OvrSeg: Word): Integer;
var
OvrReadBuf: OvrReadFunc;
procedure OvrInit(FileName: String);
procedure OvrInitEMS;
Procedure OvrInitXMS;
procedure OvrSetBuf(Size: LongInt);
function OvrGetBuf: LongInt;
procedure OvrSetRetry(Size: LongInt);
function OvrGetRetry: LongInt;
procedure OvrClearBuf;
implementation
{$L OVERLAY.OBJ}
{$L OVEREMS.OBJ}
{$L OVERXMS.OBJ }
const
OvrRetrySize: Word = 0;
OvrFileBase: Longint = 0;
procedure OvrInit(FileName: String); external;
procedure OvrInitEMS; external;
Procedure OvrInitXMS;External;
procedure OvrSetBuf(Size: LongInt); external;
function OvrGetBuf: LongInt; external;
procedure OvrSetRetry(Size: LongInt); external;
function OvrGetRetry: LongInt; external;
procedure OvrClearBuf; external;
procedure OverlayHalt;
begin
RunError(209);
end;
end.
|
(* HBMisc.PAS
;
; Miscelanea
; Diversos componentes e funções
;
*)
unit HBMisc;
interface
uses
StrUtils,
SysUtils, Messages, Classes, Graphics, Controls,
Forms, Dialogs;
function Extenso(i: Longint): String;
function ValorExtenso(r: Real): String;
function ProximaQuebra(const s: String; Inicio: Integer): String;
{ funções para problemas de geometria analítica }
function SegTamanho(x0, y0, x1, y1: Real): Real;
procedure SegPonto(x0, y0, x1, y1, d: Real; var x2, y2: Real);
procedure SegParalelo(x0, y0, x1, y1, d: Real; var xp0, yp0, xp1, yp1: Real);
procedure SegPontoMedio(x0, y0, x1, y1: Real; var xm, ym: Real);
// validações
function CPFValido (const CPF: String): Boolean;
implementation
type
Str12 = String[12];
const
Milhao = 1000000;
Bilhao = 1000000000;
Unidades: array[1..19] of Str12 = ('UM', 'DOIS', 'TRES', 'QUATRO',
'CINCO', 'SEIS', 'SETE', 'OITO',
'NOVE', 'DEZ', 'ONZE', 'DOZE',
'TREZE', 'CATORZE', 'QUINZE',
'DEZESSEIS', 'DEZESSETE', 'DEZOITO',
'DEZENOVE');
Dezenas: array[1..10] of Str12 = ('DEZ', 'VINTE', 'TRINTA',
'QUARENTA', 'CINQÜENTA', 'SESSENTA',
'SETENTA', 'OITENTA', 'NOVENTA', 'CEM');
Centenas:array[1..10] of Str12 = ('CENTO', 'DUZENTOS', 'TREZENTOS',
'QUATROCENTOS', 'QUINHENTOS',
'SEISCENTOS', 'SETECENTOS',
'OITOCENTOS', 'NOVECENTOS', 'MIL');
Milhoes: array[1..2] of Str12 = ('MILHAO', 'MILHOES');
Bilhoes: array[1..2] of Str12 = ('BILHAO', 'BILHOES');
(* Extenso
;
; retorna o extenso de
; um número inteiro
;
*)
function Extenso(i: Longint): String;
var
b, m, mm, c, d, u: Longint;
bStr, mStr, mmStr, cStr, dStr, uStr: String;
begin
{ decompõe em bilhões, milhões, milhares, }
{ centenas, dezenas e unidades }
b := i div Bilhao;
mm := (i-b*Bilhao) div Milhao;
m := (i-b*Bilhao - mm*Milhao) div 1000;
c := (i-b*Bilhao - mm*Milhao - m*1000) div 100;
d := (i-b*Bilhao - mm*Milhao - m*1000 - c*100) div 10;
u := (i-b*Bilhao - mm*Milhao - m*1000 - c*100 - d*10);
{ inicializa as strings }
bStr := ''; mmStr := ''; mStr := '';
cStr := ''; dStr := ''; uStr := '';
{ para cada componente maior que zero }
{ entra em recursão para gerar o fragmento }
{ do extenso para aquele componente }
if b > 0 then begin
bStr := Extenso(b);
if b > 1 then bStr := bStr+' '+Bilhoes[1]
else bStr := bStr+' '+Bilhoes[2];
end;
if mm > 0 then begin
mmStr := Extenso(mm);
if mm > 1 then mmStr := mmStr+' '+Milhoes[2]
else mmStr := mmStr+' '+Milhoes[1];
end;
if m > 0 then mStr := Extenso(m) + ' MIL';
if c > 0 then begin
if c > 1 then cStr := Centenas[c] else
if c = 1 then begin
if (d > 0) or (u > 0) then cStr := Centenas[c]
else cStr := Dezenas[10];
end;
end;
if d > 0 then begin
if (d > 1) or (u = 0) then dStr := Dezenas[d];
if (d > 1) and (u > 0) then uStr := Unidades[u] else
if (d = 1) and (u > 0) then dStr := Unidades[10*d+u];
end
else if (d = 0) and (u > 0) then uStr := Unidades[u];
Result := bStr;
if (b > 0) and ((mm+m+c+d+u) > 0)
then Result := Result+' E '
else if (b > 0) and ((mm+m+c+d+u) = 0)
then Result := Result+' DE';
Result := Result+mmStr;
if (mm > 0) and ((m+c+d+u) > 0) then Result := Result+' E ' else
if (mm > 0) and ((m+c+d+u) = 0) then Result := Result+' DE';
Result := Result+mStr;
if (m > 0) and ((c+d+u) > 0) then Result := Result+' E ';
Result := Result+cStr;
if (c > 0) and ((d+u) > 0) then Result := Result+' E ';
Result := Result+dStr;
if (d > 1) and (u > 0) then Result := Result+' E ';
Result := Result+uStr;
end;
(* ValorExtenso
;
; retorna o valor de r
; acompanhados de reais e centavos
;
*)
function ValorExtenso(r: Real): String;
var
Reais,
Centavos: Longint;
n: Real;
begin
Reais := Trunc(r);
n := r-Reais;
Centavos := Round((r-Reais)*100);
Result := '';
if Reais > 0 then begin
Result := Extenso(Reais);
if Reais > 1
then Result := Result + ' REAIS'
else Result := Result + ' REAL';
if Centavos > 0 then Result := Result+' E ';
end;
if Centavos > 0 then begin
Result := Result+Extenso(Centavos)+' CENTAVO';
if Centavos > 1 then Result := Result+'S';
end;
end;
(* ProximaQuebra
;
; retorna o texto até
; a próxima quebra a partir
; da posição Início
;
*)
function ProximaQuebra(const s: String; Inicio: Integer): String;
var
t: String;
i, l: Integer;
begin
{ considera os seguintes caracteres para quebra: }
{ .,;-+|/|}
t := '';
i := Inicio;
l := Length(s);
repeat
t := t+s[i];
Inc(i);
until (i > l) or (s[i] in [' ', '.', ',', ';', '-', '+', '|', '/']);
Result := t;
end;
(* um pouquinho de geometria analítica *)
(* SegTamanho
;
; retorna o tamanho do segmento
; que vai de x0, y0 a x1, y1
;
*)
function SegTamanho(x0, y0, x1, y1: Real): Real;
var
DeltaX,
DeltaY: Real;
begin
DeltaX := Abs(x1-x0);
DeltaY := Abs(y1-y0);
{ a soma dos quadrados dos catetos }
{ é igual ao quadrado da hipotenusa }
{ DeltaX^2 + DeltaY^2 = Result^2 }
{ => Result = Sqrt(DeltaX^2 + DeltaY^2) }
Result := Sqrt(Sqr(DeltaX) + Sqr(DeltaY));
end;
(* SegPonto
;
; dado um segmento x0, y0 -> x1, y1
; e uma distancia d
; determinar o ponto x2, y2 que define
; o segmento x0, y0 -> x2, y2 de tamanho d
; na mesma reta que x0, y0 -> x1, y1
;
*)
procedure SegPonto(x0, y0, x1, y1, d: Real; var x2, y2: Real);
var
DeltaX,
DeltaY,
d0: Real;
begin
DeltaX := x1-x0;
DeltaY := y1-y0;
d0 := SegTamanho(x0, y0, x1, y1);
x2 := x0+(DeltaX/d0)*d;
y2 := y0+(DeltaY/d0)*d;
end;
(* SegParalelo
;
; encontra o segmento paralelo
; a x0, y0 -> x1, y1 a uma distancia
; perpendicular d
;
*)
procedure SegParalelo(x0, y0, x1, y1, d: Real; var xp0, yp0, xp1, yp1: Real);
var
DeltaX, DeltaY,
DeltaPx, DeltaPy,
l: Real;
begin
{ DeltaPx = d*(DeltaY/l) }
{ DeltaPy = d*(DeltaX/l) }
{ determinar o tamanho do segmento }
l := SegTamanho(x0, y0, x1, y1);
{ calcular os Deltas do segmento origem }
DeltaX := x1-x0;
DeltaY := y1-y0;
{ calcular os Deltas do segmento destino }
DeltaPx := -d*(DeltaY/l);
DeltaPy := d*(DeltaX/l);
{ calcular os pontos que definem o segmento }
xp0 := x0+DeltaPx;
yp0 := y0+DeltaPy;
xp1 := x1+DeltaPx;
yp1 := y1+DeltaPy;
end;
(* SegPontoMedio
;
; retorna o ponto médio
; do segmento x0, y0 -> x1, y1
;
*)
procedure SegPontoMedio(x0, y0, x1, y1: Real; var xm, ym: Real);
begin
xm := (x1-x0)/2+x0;
ym := (y1-y0)/2+y0;
end;
(** SomenteNumeros
*
* remove caracteres não numéricos
*
*)
function SomenteNumeros (Expressao: String): String;
var
i: Integer;
begin
Result := '';
for i := 1 to Length(Expressao) do
if Expressao[i] in ['0'..'9'] then
Result := Result + Expressao[i];
end;
(** GetDigitoModulo11
*
* calcula um dígito módulo 11
*
*)
function GetDigitoModulo11 (Expressao: String): Integer;
var
i, Len: Integer;
begin
Result := 0;
Len := Length(Expressao);
for i := 1 to Len do
Result := Result + (StrToInt(Expressao[i])*(Len+2-i));
Result := 11 - Result mod 11;
if (Result = 10) or (Result = 11) then
Result := 0;
end;
(** CPFDigitosVerificadores
*
* calcula dígitos verificadores para um número de CPF
*
*)
function CPFDigitosVerificadores (const CPF: String): String;
var
Expressao: String;
begin
Expressao := Copy (CPF, 1, 9);
Expressao := Expressao + IntToStr(GetDigitoModulo11(Expressao));
Expressao := Expressao + IntToStr(GetDigitoModulo11(Expressao));
Result := Copy (Expressao, 10, 2);
end;
(** CPFFajuto
*
* identifica tentativas fáceis de fajutar o CPF
*
*)
function CPFFajuto (const CPF: String): Boolean;
begin
Result := AnsiIndexStr(CPF,
[
'00000000000', '11111111111', '22222222222', '33333333333', '44444444444',
'55555555555', '66666666666', '77777777777', '88888888888', '99999999999'
]
) >= 0;
end;
(** CPFValido
*
* faz validação de CPF
*
*)
function CPFValido (const CPF: String): Boolean;
var
CPFLimpo: String;
begin
// default false
Result := False;
// remove separadores
CPFLimpo := SomenteNumeros(CPF);
// CPF sem sepradores deve ter 11 caracteres
// e evita enganação barata
if (Length(CPFLimpo) <> 11) or CPFFajuto(CPFLimpo) then
Exit;
// calcula os digitos verificadores
Result := CPFDigitosVerificadores(CPFLimpo) = Copy (CPFLimpo, 10, 2);
end;
end.
|
unit Kernel;
{$H-}
interface
uses
ExprShared, ExprTree, ExprParser, StrUtils, CoreFunctions, Ejercicios;
const
HASHROWS = 13; { número de listas en la tabla hash de símbolos }
type
{ tabla de símbolos - asocia una expresión (clave) a otra (valor) }
TSymbolTable = record
{ claves y valores están en listas de expresiones }
Keys : array[0..HASHROWS] of TExprList;
Values : array[0..HASHROWS] of TExprList;
end;
{ núcleo - almacena el último resultado y símbolos definidos con "Set" }
TKernel = record
E1 : Expr; { resultado de la última evaluación }
Defs : TSymbolTable; { tabla de símbolos }
nExprEval : Word; { evaluaciones }
end;
{ inicializa / termina }
procedure StartKernel(var K : TKernel);
procedure StopKernel(var K : TKernel);
{ evalúa una expresión que viene del intérprete }
procedure FrontEndEval(E : String; var Ker : TKernel; var ec : TException);
{ guarda las expresiones Set[] para reconstruir la tabla de símbolos }
procedure SaveSymbolTableInto(var F : Text; Ker : TKernel);
implementation
{ Utilidades }
function nSubExprs(X : Expr) : Word;
begin
nSubExprs:=LengthOfTExprList(X^.SubExprs);
end;
function SubExpr(X : Expr; n : Word) : Expr;
begin
SubExpr:=ExprAtIndex(X^.SubExprs, n);
end;
procedure MoveToFirstSubExpr(X : Expr; var k : TExprIt);
begin
MoveToFirst(X^.SubExprs, k);
end;
procedure SaveSymbolTableInto(var F : Text; Ker : TKernel);
var
h : Word; Ki, Vi : TExprIt;
begin
{ para cada 'fila' de la tabla hash }
for h:=0 to HASHROWS do
begin
{ se mueve sobre las correspondientes listas de claves y valores }
MoveToFirst(Ker.Defs.Keys[h], Ki); MoveToFirst(Ker.Defs.Values[h], Vi);
while (IsAtNode(Ki)) do
begin
{ reproduce la expresión Set[Clave,Valor] necesaria para recrear la definición }
WriteLn(F, 'Set[' + ExprToStr(ExprAt(Ki)) + ',' + ExprToStr(ExprAt(Vi)) + ']');
{ avanza los iteradores de ambas listas }
MoveToNext(Ki); MoveToNext(Vi);
end;
end;
end;
{ Retiene R como último resultado conocido en el núcleo }
procedure StoreLastKnownResult(var K : TKernel; R : Expr);
begin
{ libera la expresión anterior }
ReleaseExpr(K.E1);
{ guarda una referencia a R }
K.E1:=R;
end;
{ Inicializa una tabla de símbolos }
procedure InitSymbolTable(var T : TSymbolTable);
var
i : Word;
begin
{ para cada par de listas }
for i:=0 to HASHROWS do
begin
InitTExprList(T.Keys[i]);
InitTExprList(T.Values[i]);
end;
end;
{ Vacía una tabla de símbolos }
procedure EmptySymbolTable(var T : TSymbolTable);
var
i : Word;
begin
for i:=0 to HASHROWS do
begin
ReleaseElementsInTExprList(T.Keys[i]);
ReleaseElementsInTExprList(T.Values[i]);
end;
end;
{ Valor hash de una clave (cadena) dada }
function Hash(Key : String) : Word;
var
i : Word;
Acc : QWord;
begin
Acc:=0; for i:=1 to Length(Key) do Acc:=Acc + Ord(Key[i]);
Hash:=Acc mod HASHROWS;
end;
{ Guarda una definición en la tabla, asociada a la expresión clave (Key), con valor (Value) }
procedure StoreInto(var T : TSymbolTable; Key, Value : Expr);
var
hKey : Word; Ki, Vi : TExprIt; A : Expr;
begin
{ aplica la función de hash a la clave }
hKey:=Hash(ExprToStr(Key));
{ hKey es el índice que indica qué lista de claves y qué lista de valores usar }
{ intenta localizar la clave (por si ya existe) y su correspondiente valor }
MoveToFirst(T.Keys[hKey], Ki); MoveToFirst(T.Values[hKey], Vi);
while (IsAtNode(Ki) and (not Equals(ExprAt(Ki), Key))) do
begin
{ mientras queden claves y en la que está Ki no sea igual a la que piden }
MoveToNext(Ki); MoveToNext(Vi);
end;
{ si Ki está en un nodo de la lista de claves, es que se encontró Key en ella }
if (IsAtNode(Ki)) then
begin
{ intercambia el valor }
A:=SwitchExprAt(Vi, DeepCopy(Value));
{ libera la memoria de la expresión sustituída }
ReleaseExpr(A);
end
else
begin
{ no está, inserta como último }
InsertAsLast(T.Keys[hKey], DeepCopy(Key));
InsertAsLast(T.Values[hKey], DeepCopy(Value));
end;
end;
{ Devuelve una copia de la expresión almacenada bajo la clave dada }
function RecallFrom(T : TSymbolTable; Key : Expr) : Expr;
var
hKey : Word; Ki, Vi : TExprIt;
begin
hKey:=Hash(ExprToStr(Key)) mod HASHROWS;
MoveToFirst(T.Keys[hKey], Ki); MoveToFirst(T.Values[hKey], Vi);
while (IsAtNode(Ki) and (not Equals(ExprAt(Ki), Key))) do
begin
MoveToNext(Ki); MoveToNext(Vi);
end;
if (IsAtNode(Ki)) then
RecallFrom:=DeepCopy(ExprAt(Vi))
else
RecallFrom:=Nil;
end;
procedure RemoveFrom(var T : TSymbolTable; Key : Expr);
var
hKey : Word; Ki, Vi : TExprIt;
begin
hKey:=Hash(ExprToStr(Key));
MoveToFirst(T.Keys[hKey], Ki); MoveToFirst(T.Values[hKey], Vi);
while (IsAtNode(Ki) and (not Equals(ExprAt(Ki), Key))) do
begin
MoveToNext(Ki); MoveToNext(Vi);
end;
if (IsAtNode(Ki)) then
begin
RemoveNodeAndReleaseExprAt(T.Keys[hKey], Ki);
RemoveNodeAndReleaseExprAt(T.Values[hKey], Vi);
end;
end;
procedure StartKernel(var K : TKernel);
begin
K.E1:=AllocExpr('List','');
InitSymbolTable(K.Defs);
K.nExprEval:=0;
end;
procedure StopKernel(var K : TKernel);
begin
ReleaseExpr(K.E1);
EmptySymbolTable(K.Defs);
end;
{ sustituye '%' por el último resultado conocido }
function ReplaceInString(S : String; Rx : String) : String;
begin
ReplaceInString:=AnsiReplaceStr(S,'%',Rx);
end;
{ evaluación de E (cadena) }
procedure FrontEndEval(E : String; var Ker : TKernel; var ec : TException);
{ Evalúa la expresión Ex de forma recursiva (de las hojas hacia arriba) }
{ + La evaluación puede modificar el núcleo Ker y devuelve un código de resultado en ec }
{ + El cliente se hace responsable de la memoria dinámica del resultado }
function EvaluateExpr(Ex : Expr; var Ker : TKernel; var ec : TException) : Expr;
var
Exi, Exj : TExprIt;
Ri : Expr;
begin
ec.nError:=0; ec.Msg:='';
{ primero evalúa las sub-expresiones }
MoveToFirst(Ex^.SubExprs, Exi);
while ((ec.nError = 0) and (IsAtNode(Exi))) do
begin
Ri:=EvaluateExpr(ExprAt(Exi), Ker, ec);
{ si no hay error, continúa }
if (ec.nError = 0) then
begin
{ guarda el resultado como sub-expresión de Ex }
Ri:=SwitchExprAt(Exi,Ri);
{ elimina la que había antes }
ReleaseExpr(Ri);
MoveToNext(Exi);
end;
end;
{ después, evalúa la raíz }
if (ec.nError = 0) then
begin
if (Ex^.Head = 'Symbol') then
begin
{ si no es '%' - por ejemplo, evaluar "A1" }
if (Ex^.Terminal <> '%') then
begin
{ evaluación de un símbolo - puede tener un valor asociado en la tabla de símbolos }
EvaluateExpr:=RecallFrom(Ker.Defs, Ex);
{ si no lo tiene, devuelve el propio símbolo }
if (EvaluateExpr = Nil) then
EvaluateExpr:=DeepCopy(Ex);
end
else
{ la evaluación de % es el "último resultado conocido" }
EvaluateExpr:=DeepCopy(Ker.E1);
end { expresiones implementadas }
else if (Ex^.Head = 'Flatten') then
EvaluateExpr:=Flatten(SubExpr(Ex,1),ec)
else if (Ex^.Head = 'Tally') then
EvaluateExpr:=Tally(SubExpr(Ex,1),ec)
else if (Ex^.Head = 'Part') then
EvaluateExpr:=Part(SubExpr(Ex,1), SubExpr(Ex,2), ec)
else if (Ex^.Head = 'Partition') then
EvaluateExpr:=Partition(SubExpr(Ex,1), SubExpr(Ex,2), ec)
else if (Ex^.Head = 'RemoveAll') then
EvaluateExpr:=RemoveAll(SubExpr(Ex,1), SubExpr(Ex,2))
else if (Ex^.Head = 'TreeForm') then
begin
TreeForm(SubExpr(Ex,1));
EvaluateExpr:=DeepCopy(SubExpr(Ex,1));
end
else if (Ex^.Head = 'QTreeForm') then
begin
QTreeForm(SubExpr(Ex,1), ec);
EvaluateExpr:=DeepCopy(SubExpr(Ex,1));
end
else if (Ex^.Head = 'MatrixForm') then
begin
MatrixForm(SubExpr(Ex, 1), ec);
EvaluateExpr:=DeepCopy(SubExpr(Ex, 1));
end
else if (Ex^.Head = 'ReplaceAll') then
EvaluateExpr:=ReplaceAll(SubExpr(Ex, 1), SubExpr(Ex, 2), ec)
else if (Ex^.Head = 'Depth') then
EvaluateExpr:=Depth(SubExpr(Ex,1))
else if (Ex^.Head = 'First') then
EvaluateExpr:=First(SubExpr(Ex,1), ec)
else if (Ex^.Head = 'Sort') then
EvaluateExpr:=Sort(SubExpr(Ex,1), ec)
else if (Ex^.Head = 'Join') then
EvaluateExpr:=Join(SubExpr(Ex,1), ec)
else if (Ex^.Head = 'Terminals') then
EvaluateExpr:=PartsOfTerminalNodes(SubExpr(Ex,1), ec)
else if (Ex^.Head = 'CartesianProduct') then
EvaluateExpr:=CartesianProduct(SubExpr(Ex,1), SubExpr(Ex,2), ec)
else if (Ex^.Head = 'Equals') then
begin
{ devuelve una expresión 'True', o 'False' (símbolos) }
if (Equals(SubExpr(Ex, 1), SubExpr(Ex, 2))) then
EvaluateExpr:=AllocExpr('Symbol', 'True')
else
EvaluateExpr:=AllocExpr('Symbol', 'False');
end
else if (Ex^.Head = 'ExprCmp') then
begin
case ExprCmp(SubExpr(Ex, 1), SubExpr(Ex, 2)) of
'<': begin
EvaluateExpr:=AllocExpr('Symbol', 'LessThan');
end;
'=': begin
EvaluateExpr:=AllocExpr('Symbol', 'Equal');
end;
'>': begin
EvaluateExpr:=AllocExpr('Symbol', 'GreaterThan');
end;
end;
end
else
{ si no se conoce, devuelve una copia }
EvaluateExpr:=DeepCopy(Ex);
end;
end;
var
Ex : Expr;
Rx : Expr;
begin
Inc(Ker.nExprEval);
if (E = 'Show') then
{ muestra los símbolos en la tabla del núcleo }
SaveSymbolTableInto(Output, Ker)
else
begin
{ construye el árbol de expresión }
Ex:=ParseExpr(E);
{ asignación - Set[LHS,RHS] asigna al lado izquierdo LHS el resultado de evaluar RHS }
if (Ex^.Head = 'Set') then
begin
if (SubExpr(Ex,1)^.Head <> 'Symbol') then
begin
ec.nError:=1; ec.Msg:='Únicamente se pueden asignar valores a símbolos';
end
else
begin
{ evalúa la parte derecha de la asignación }
Rx:=EvaluateExpr(SubExpr(Ex, 2), Ker, ec);
{ si no hubo error }
if (ec.nError = 0) then
begin
{ almacena el resultado, asociado a la parte izquierda }
StoreInto(Ker.Defs, SubExpr(Ex, 1), Rx);
{ guarda como último resultado conocido }
StoreLastKnownResult(Ker, Rx);
end
else
begin
ec.Msg:='Error al evaluar el lado derecho de la asignación : ' + ec.Msg;
{ error, libera la memoria utilizada }
ReleaseExpr(Rx);
end;
end;
end
else
begin
{ evaluación de otras expresiones (no Set) }
Rx:=EvaluateExpr(Ex, Ker, ec);
{ si no hubo error }
if (ec.nError = 0) then
begin
{ guarda como último resultado conocido }
StoreLastKnownResult(Ker, Rx);
end
else
begin
ec.Msg:='Error al evaluar la expresión : ' + ec.Msg;
{ error, libera la memoria utilizada }
ReleaseExpr(Rx);
end;
end;
{ libera el árbol de expresión }
ReleaseExpr(Ex);
end;
end;
begin
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.